Compare commits

..
225 changed files with 803 additions and 12533 deletions

No files matched your search

+8 -12
View File
@@ -562,12 +562,6 @@ 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
@@ -623,11 +617,12 @@ 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
curl -fsSL --retry 5 --retry-all-errors --retry-delay 10 -o venus.tzst \
"https://github.com/${VENUS_REPO}/releases/download/${VENUS_TAG}/venus.tzst"
gh release download "${VENUS_TAG}" -R "${VENUS_REPO}" -p venus.tzst -O 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
@@ -803,11 +798,9 @@ jobs:
set -o pipefail
cd app/src/main/rust/stores
cargo test --locked 2>&1 | tail -60
- name: Windows launcher service host unit tests
- name: Ubisoft launcher service host unit tests
timeout-minutes: 10
run: |
cargo test --locked --manifest-path tools/ubisoft-launcher/Cargo.toml
cargo test --locked --manifest-path tools/rockstar-launcher/Cargo.toml
run: cargo test --locked --manifest-path tools/ubisoft-launcher/Cargo.toml
python-tests:
name: Python and native regression tests
@@ -840,6 +833,9 @@ jobs:
env:
XBOX_SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
run: test "$(git rev-parse 'HEAD^{tree}')" = "$XBOX_SOURCE_TREE"
- uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install Python test dependencies
timeout-minutes: 7
run: bash tools/ci/install-ubuntu-packages.sh python3-yaml gcc-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user libvulkan-dev mesa-vulkan-drivers
-1
View File
@@ -36,4 +36,3 @@ __pycache__/
app/src/main/assets/directaudio/
app/src/main/assets/hybris/
/tools/vr/out/
app/src/main/resources/rockstar/helpers/
-10
View File
@@ -1,13 +1,3 @@
# 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.
-8
View File
@@ -277,8 +277,6 @@ 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)
}
@@ -382,11 +380,6 @@ 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'
@@ -394,7 +387,6 @@ 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'
-7
View File
@@ -18,15 +18,8 @@
<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" />
-2
View File
@@ -1,2 +0,0 @@
#!/bin/sh
exec python3 /root/.local/share/droiddeck/ctl/droiddeckctl "$@"
@@ -1,6 +1,5 @@
add_library(droiddeckwayland SHARED
src/compositor.c
src/clock_domain.c
src/vk_present.c
src/effects_chain.c
src/cardboard.c
@@ -1,72 +0,0 @@
#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);
}
@@ -1,11 +0,0 @@
#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,7 +36,6 @@
#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__)
@@ -728,7 +727,9 @@ 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;
t = droiddeck_clock_domain_now_ms();
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
t = (uint32_t)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
wl_resource_for_each_safe(cb, tmp, frames) {
wl_callback_send_done(cb, t);
wl_resource_destroy(cb);
@@ -1060,7 +1061,6 @@ 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,7 +2493,8 @@ static void on_vsync(int64_t frame_time_ns) {
static uint32_t now_ms(void) {
return droiddeck_clock_domain_now_ms();
struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint32_t)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
}
static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint32_t serial,
@@ -3113,10 +3114,12 @@ 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;
ut = (uint64_t)(droiddeck_clock_domain_now_ns() / 1000);
clock_gettime(CLOCK_MONOTONIC, &ts);
ut = (uint64_t)ts.tv_sec * 1000000ULL + (uint64_t)ts.tv_nsec / 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,9 +33,7 @@ static PFN_vkGetInstanceProcAddr g_gipa;
static VkPhysicalDevice g_pd;
static VkQueue g_queue;
static uint32_t g_qfam;
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 int g_dev_ready, g_dev_lost, g_features_enabled;
static VkPhysicalDeviceMemoryProperties g_memprops;
static struct {
PFN_vkCreateImage CreateImage;
@@ -143,12 +141,9 @@ static void mark_failed(int kind) {
}
int vkp_framegen_problem(void) {
if (!atomic_load(&g_dev_ready)) return -1;
if (!g_dev_ready) return -1;
int kind = atomic_load(&g_kind);
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 (!fge_caps_ok(kind)) return 1;
if (start_failed_for(kind)) return 2;
if (g_engine_ok && g_engine_kind == kind && fge_unavailable()) return 2;
return 0;
@@ -184,17 +179,13 @@ 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);
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);
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) { atomic_store(&g_dev_lost, 1); }
void vkp_framegen_device_lost(void) { g_dev_lost = 1; }
static void destroy_ring(void) {
@@ -253,12 +244,7 @@ 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);
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);
return g_dev_ready && !g_dev_lost && fge_caps_ok(kind) && !start_failed_for(kind);
}
int vkp_framegen_format_ok(VkFormat fmt) {
@@ -50,12 +50,6 @@ 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,7 +18,6 @@
#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);
@@ -355,13 +354,6 @@ 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,9 +43,7 @@ class App : Application() {
process == "$packageName:shortcuts_sync" || process == "$packageName:bottom_desktop") return
CrashHandler.install(this)
com.droiddeck.launcher.agent.AgentHost.refresh(this)
com.droiddeck.launcher.agent.AgentTab.load(this)
com.droiddeck.launcher.ui.AgentPet.install(this)
if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent"
if (com.droiddeck.launcher.agent.AgentHost.available) 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)
@@ -72,7 +70,6 @@ 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(), com.droiddeck.launcher.ui.AgentPetHost {
class FrontEndActivity : ComponentActivity() {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
@@ -196,7 +196,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
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("")
@@ -227,11 +226,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
refreshWifiDiscovery()
}
}
private val dateReceiver = object : android.content.BroadcastReceiver() {
override fun onReceive(context: android.content.Context?, intent: Intent?) {
refreshAndroidApps()
}
}
private val mediaRefresh = Runnable {
refresh()
refreshAddedGames()
@@ -599,7 +593,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
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)
@@ -835,10 +828,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
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()
@@ -1117,7 +1106,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
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.AgentTab.visible) navRequest = "agent"
if (savedInstanceState == null && navRequest == null && com.droiddeck.launcher.lab.LabOverlay.promoted && com.droiddeck.launcher.agent.AgentHost.available) navRequest = "agent"
gameSyncFolder = GameFileSync.folder(this)
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
refreshPhantomStatus()
@@ -1132,7 +1121,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
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)
@@ -1190,7 +1178,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
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,
@@ -1229,7 +1216,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
showPhantomGate = showPhantomGate,
orientation = orientation,
launcherOrientation = launcherOrientation,
homePage = homePage,
launcherFullscreen = launcherFullscreen,
downloadSource = downloadSource,
downloadMirror = downloadMirror,
@@ -1430,11 +1416,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
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)
@@ -1527,10 +1508,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
launcherOrientation = value
requestedOrientation = value
},
onHomePage = { value ->
com.droiddeck.launcher.core.AppUiPrefs.setHomePage(this, value)
homePage = value
},
onLauncherFullscreen = { on ->
SessionPrefs.setLauncherFullscreen(this, on)
launcherFullscreen = on
@@ -1599,7 +1576,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
refreshHomeAppState()
}
},
onAppIconsChanged = { refreshAndroidApps() },
onAndroidApp = { app, displayId -> launchAndroidApp(app, displayId) },
onBackActionsInverted = { inverted ->
SessionPrefs.setBackActionsInverted(this, inverted)
@@ -1782,8 +1758,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}, "finish-abandoned").start()
}
override val petBlocked: Boolean get() = false
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
@@ -1877,7 +1851,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
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()
@@ -1927,7 +1900,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
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)
@@ -1981,7 +1953,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
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)
@@ -2048,7 +2019,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
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)
@@ -2897,7 +2867,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
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)
@@ -3077,7 +3046,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
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)
if (!switchLauncherIcon(LauncherIcon.DARK)) recreate()
}
}, "reset-settings").start()
@@ -25,12 +25,6 @@ class HomeActivity : Activity() {
} 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)
finish()
@@ -41,7 +41,7 @@ object HomeApp {
val userSerial: Long = 0L,
) {
val component get() = ComponentName(packageName, className)
val key get() = appKey(packageName, className, userSerial)
val key get() = "$packageName/$className" + if (userSerial != 0L) "#$userSerial" else ""
val work get() = userSerial != 0L
}
@@ -101,9 +101,6 @@ 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
@@ -119,25 +116,13 @@ 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 {
(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 icon = 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")
@@ -1,46 +0,0 @@
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])
}
}
@@ -1,198 +0,0 @@
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, com.droiddeck.launcher.ui.AgentPetHost {
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
@@ -159,8 +159,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
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)
@@ -454,7 +452,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
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 &&
@@ -463,7 +460,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET,
)) || SessionState.mode == SessionService.MODE_DESKTOP
private val drawerGameInventory = GameProfileInventoryCache<Library.SteamGame>()
@Volatile private var drawerGameInventoryRevision = 0L
private var drawerGameInventoryRevision = 0L
private var drawerGameFexPresetSaving by mutableStateOf(false)
private var drawerGameNoSteamSaving by mutableStateOf(false)
private val drawerGameProfileFollowState = GameProfileFollowState()
@@ -559,25 +556,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
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)
@@ -879,7 +859,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
hud.attach(root, root.childCount)
memoryHud = com.droiddeck.launcher.session.MemoryHud(this)
hud.onPresentingWindowChanged = {
CompositorHost.rearmFrameGen { applyFrameGen(force = true) }
if (FrameGen.engine(this) != FrameGen.ENGINE_OFF) CompositorHost.rearmFrameGen { applyFrameGen() }
}
if (SessionState.running && SessionState.firstFrameSeen) {
loading.visible = false
@@ -912,24 +892,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} }
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)
}
}
@@ -992,7 +956,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
applyOutputPacing()
if (pipUi != frameGenPip) {
frameGenPip = pipUi
if (::surfaceView.isInitialized) applyFrameGen()
if (FrameGen.engine(this@SessionActivity) != FrameGen.ENGINE_OFF && ::surfaceView.isInitialized) applyFrameGen()
}
}
androidx.compose.runtime.LaunchedEffect(AgentGuest.steamKeyboard) { updateOnScreenControls() }
@@ -1068,7 +1032,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(android.graphics.Color.BLACK))
},
)
LaunchedEffect(AgentGuest.focusRevision, secondScreenDisplays.isNotEmpty(), drawerGameInventoryRevision) {
LaunchedEffect(AgentGuest.focusRevision, secondScreenDisplays.isNotEmpty()) {
val nextGame = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
if (SessionState.mode == SessionService.MODE_RUN) SessionState.program?.let { "program:$it" }
else {
@@ -1081,40 +1045,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
}
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) }
}
@@ -1299,18 +1234,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
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,
@@ -1370,22 +1293,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
applyOutputPacing()
},
onFrameGenPick = { mode ->
val appId = frameGenTargetGameId()
if (appId == null) FrameGen.set(this@SessionActivity, mode)
else FrameGen.setForGame(this@SessionActivity, appId.toString(), mode)
loadFrameGenFor(appId)
FrameGen.set(this@SessionActivity, mode)
readPrefs()
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)
applyFrameGen()
},
onImportLossless = {
pickLossless.launch(InAppFilePicker.buildIntent(
@@ -1718,35 +1628,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}, "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()
@@ -1819,7 +1703,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (refresh.followsSteam) {
if (drawerGameProfileFollowState.followsSteam) {
drawerGameProfileId = result.selectedAppId
loadFrameGenFor(result.selectedAppId)
readDrawerTextureFiltering(result.selectedAppId)
}
}
@@ -1844,8 +1727,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
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),
)
}
@@ -2089,7 +1970,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (routedTouchMode != nextRoutedTouchMode) gestureTouchStreamGate.reset()
routedTouchMode = nextRoutedTouchMode
requestRelativeMouse()
loadFrameGenFor(frameGenTargetGameId())
frameGen = FrameGen.mode(this)
fexPreset = SessionPrefs.fexPreset(this)
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
@@ -2376,7 +2257,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (resized) {
cancelTouchGestures()
Log.i(TAG, "surface resized to ${width}x$height - rebinding the compositor")
CompositorHost.resize(holder.surface) { applyFrameGen(force = true) }
CompositorHost.resize(holder.surface) { applyFrameGen() }
resizeOutputForWindow(width, height)
}
}
@@ -2517,161 +2398,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
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()
}
private fun applyFrameGen() {
val hz = refreshHz()
val pip = pipUi && mirrorRefreshLimit() <= 0
val request = frameGenRequests.incrementAndGet()
Thread({
val mode = if (pip) FrameGen.Mode.OFF else frameGenModeForActiveGame(request)
val needsApply = synchronized(frameGenGlobalLock) {
if (frameGenActivityGeneration != frameGenGlobalGeneration.get()) return@Thread
val problem = synchronized(frameGenRequests) {
if (request != frameGenRequests.get()) return@Thread
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
}
}
}
if (pip) FrameGen.apply(this, FrameGen.Mode.OFF, hz) else FrameGen.apply(this, hz)
}
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()
}
@@ -2688,13 +2425,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun importLossless(dll: File) {
Thread({
val result = Lossless.import(this, dll)
val message = Lossless.message(this, result)
val message = Lossless.message(this, Lossless.import(this, dll))
val state = Lossless.state(this)
runOnUiThread {
lossless = state
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
applyFrameGen(force = result == Lossless.ImportResult.UPDATED)
if (FrameGen.engine(this) == FrameGen.ENGINE_LSFG) applyFrameGen()
}
}, "lossless-import").start()
}
@@ -2901,7 +2637,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
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 =
@@ -4973,14 +4708,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
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
@@ -5658,10 +5391,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
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()
@@ -5776,8 +5505,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
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 > Developer > Debugging tools on the device",
"Debugging tools are off: turn on Setup > Diagnostics > Debugging tools on the device",
)
}
@@ -74,11 +74,7 @@ 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 {
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)
}
entry.usage?.let { put("ms", it.durationMs).put("cost", it.costUsd).put("in", it.inputTokens).put("out", it.outputTokens) }
}
}.toString()
@@ -109,8 +105,7 @@ 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"), o.optLong("ctx"), o.optLong("win")) else null,
o.optBoolean("planned"),
if (o.has("ms")) AgentHost.Usage(o.optLong("ms"), o.optDouble("cost", 0.0), o.optLong("in"), o.optLong("out")) else null,
)
else -> null
}
@@ -21,8 +21,6 @@ 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. */
@@ -31,12 +29,10 @@ interface AgentHarness {
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, val effort: String? = null)
data class Options(val model: String? = null, val plan: Boolean = false, val brief: String? = null)
companion object {
val all: List<AgentHarness> = listOf(ClaudeCode, Codex)
@@ -52,9 +48,6 @@ 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,
)
@@ -67,7 +60,6 @@ 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
@@ -100,7 +92,6 @@ 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))
}
@@ -144,12 +135,10 @@ 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,
@@ -160,24 +149,6 @@ 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 ->
@@ -205,8 +176,8 @@ object ClaudeCode : AgentHarness {
input ?: return ""
return when {
tool == "Bash" -> input.optString("command")
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 == "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 == "TodoWrite" -> todos(input.optJSONArray("todos"))
else -> input.toString(2)
}
@@ -241,7 +212,6 @@ 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 {
@@ -261,7 +231,6 @@ 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)
}
@@ -312,33 +281,6 @@ 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 ->
@@ -357,28 +299,6 @@ 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,7 +14,6 @@ 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
@@ -32,18 +31,10 @@ 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
/** [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 Finished(val error: String?, val stopped: Boolean = false, val usage: Usage? = null) : Entry
}
/** [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)
data class Usage(val durationMs: Long, val costUsd: Double, val inputTokens: Long, val outputTokens: Long)
/** A message typed while the agent was working, sent when the turn ends. */
data class Queued(val text: String, val files: List<String>)
@@ -59,12 +50,7 @@ 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 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. " +
"droiddeckctl (in the /root/DroidDeck checkout, tools/droiddeckctl) inspects and drives the app over loopback adb (\$ADB_SERIAL). " +
"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. " +
@@ -86,9 +72,6 @@ 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)
@@ -111,12 +94,6 @@ 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
@@ -133,7 +110,6 @@ 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
@@ -149,9 +125,7 @@ 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
@@ -174,9 +148,7 @@ object AgentHost {
conversation = loaded.conversation
entries.clear()
entries.addAll(loaded.entries)
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
context = 0
}
/** Opens a kept conversation, switching to the CLI it belongs to. */
@@ -242,11 +214,6 @@ 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()
@@ -281,15 +248,10 @@ object AgentHost {
AgentHostService.start(app)
val current = harness
val prompt = AgentAttachments.prompt(message, attached)
turnPlanned = plan && current.plans
val command = current.turn(prompt, conversation, AgentHarness.Options(model, turnPlanned, BRIEF, effort))
val command = current.turn(prompt, conversation, AgentHarness.Options(model, plan && current.plans, BRIEF))
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) {
@@ -298,7 +260,6 @@ 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
@@ -310,18 +271,13 @@ object AgentHost {
runCatching {
child.inputStream.bufferedReader().forEachLine { line ->
runCatching { raw?.apply { write(line); newLine(); flush() } }
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
val event = current.parse(line) ?: return@forEachLine
if (event.entries.any { it is Entry.Finished }) ended = true
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
@@ -349,16 +305,6 @@ 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)
@@ -367,7 +313,6 @@ 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
}
@@ -417,11 +362,6 @@ 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 -> {
@@ -439,8 +379,7 @@ object AgentHost {
if (!stopped) labFromTurn = false
live = ""
liveThinking = ""
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))
record(app, Entry.Finished(error, stopped, usage))
state = State.IDLE
unseen = true
failed = error != null
@@ -561,15 +500,9 @@ 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 }
val pid = AgentProcesses.pidOf(child)
OrphanReaper.keep(pid)
try {
child.outputStream.close()
child.inputStream.readBytes()
child.waitFor()
} finally {
OrphanReaper.release(pid)
}
child.outputStream.close()
child.inputStream.readBytes()
child.waitFor()
}.onFailure { Log.w(TAG, "could not run a Lab build", it) }
main.post {
labProcess = null
@@ -598,19 +531,6 @@ 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)
}
@@ -8,7 +8,6 @@ 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
@@ -40,8 +39,7 @@ 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", "droiddeckctl")
internal const val CTL = "/root/.local/share/droiddeck/ctl"
private val HELPERS = listOf("android-open", "dd-gh-login")
private const val PROBE_TIMEOUT_S = 60L
fun check(context: Context) {
@@ -81,8 +79,7 @@ object AgentSetup {
Step.CONNECTION -> return
Step.INSTALL -> {
listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " +
"dpkg --configure -a; apt-get update; apt-get -f install -y; " +
"apt-get install -y --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}")
"apt-get update; 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")
@@ -98,21 +95,12 @@ object AgentSetup {
installHelpers(app)
runCatching { harness.prepare(LinuxRuntime.rootDir(app)) }
val child = AgentHost.guest(app, command).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) }
}
child.waitFor().also { log.appendLine("exit $it") }
}
} finally {
OrphanReaper.release(pid)
child.outputStream.close()
child.inputStream.bufferedReader().forEachLine { line ->
val text = line.trim()
if (text.isNotEmpty() && !noise(text)) main.post { detail[step] = text.take(160) }
}
child.waitFor()
}
main.post {
AgentHostService.setupEnded(app)
@@ -128,9 +116,6 @@ 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. */
@@ -180,16 +165,12 @@ object AgentSetup {
}
/** Written before every step, so the helpers a step relies on are there and match this DroidDeck version. */
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)
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)
}
}
}
@@ -1,23 +0,0 @@
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(false)
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,7 +3,6 @@ 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
@@ -17,7 +16,6 @@ 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 {
@@ -44,8 +42,7 @@ internal class AddonPack(
fun installed(context: Context): Boolean = version(context).isNotEmpty() && File(dir(context), COMPLETE).isFile
private fun version(context: Context): String =
if (reuseDeviceCopy || labBuild) deviceCopy(context) ?: sha256 else sha256
private fun version(context: Context): String = if (!reuseDeviceCopy) sha256 else deviceCopy(context).orEmpty()
private fun deviceCopy(context: Context): String? = root(context).listFiles().orEmpty()
.filter { dir ->
@@ -27,25 +27,6 @@ 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(
@@ -13,11 +13,6 @@ 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 {
@@ -40,8 +35,6 @@ 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,9 +5,6 @@ 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"
@@ -107,53 +104,4 @@ 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, reuse: Boolean = false): List<File> = rank(folder, reuse).exes
fun candidates(folder: File): List<File> = rank(folder).exes
fun rank(folder: File, reuse: Boolean = false): GameExePicker.Ranking {
val key = "${folder.path}|${folder.lastModified()}"
@@ -418,7 +418,6 @@ 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 && (!com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(sidecar.id) || 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
@@ -434,7 +433,6 @@ 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
@@ -126,7 +126,6 @@ object Library {
fun steamGames(
context: Context, strictRead: Boolean = false, arch: String = SessionPrefs.activeSteamClientArch(context),
withShared: Boolean = true,
onlyAppIds: Set<Int>? = null,
): List<SteamGame> {
val root = SessionPrefs.steamRoot(context, arch)
val cache = File(root, "appcache/librarycache")
@@ -139,9 +138,7 @@ 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) ||
(onlyAppIds != null && appId !in onlyAppIds)
) return@forEach
if (appId in NOT_GAMES || out.containsKey(appId)) 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
@@ -164,41 +161,16 @@ object Library {
}
if (withShared) {
val other = if (arch == "x86_64") "arm64" else "x86_64"
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,
onlyAppIds = shared,
)
} catch (e: Exception) {
if (strictRead) throw e
emptyList()
}
otherGames.forEach { out[it.appId] = it }
}
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 }
}
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")
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()
return view.list().orEmpty().mapNotNull { Regex("appmanifest_(\\d+)\\.acf").matchEntire(it)?.groupValues?.get(1)?.toIntOrNull() }.toSet()
}
fun steamLibraryArt(context: Context): List<Pair<Int, File>> {
@@ -28,38 +28,12 @@ object FrameGen {
fun engine(context: Context): String = mode(context).engine
fun mode(context: Context): Mode = mode(context, null)
fun mode(context: Context, appId: String?): Mode {
fun mode(context: Context): Mode {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
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)
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)
if (engine == ENGINE_LSFG && target in ADAPTIVE_TARGETS) return Mode(engine, target = target)
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()
return Mode(engine, prefs.getInt("multiplier", 2).coerceIn(2, 4))
}
fun set(context: Context, mode: Mode) {
@@ -67,11 +41,6 @@ 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 {
@@ -81,32 +50,14 @@ object FrameGen {
else -> context.getString(R.string.frame_gen_off)
}
data class PreparedApply internal constructor(
val mode: Mode,
internal val lsfgStatus: Int? = null,
internal val lsfgCachePath: String? = null,
)
fun apply(context: Context, refreshHz: Float): String? = apply(context, mode(context), refreshHz)
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
fun apply(context: Context, mode: Mode, refreshHz: Float): String? {
when (mode.engine) {
ENGINE_LSFG -> {
val status = prepared.lsfgStatus ?: LsfgNative.STATUS_NOT_INSTALLED
val cachePath = prepared.lsfgCachePath
if (status != LsfgNative.STATUS_OK || cachePath == null) {
val status = Lossless.sync(context)
val cache = Lossless.cacheFile(context)
if (status != LsfgNative.STATUS_OK || cache == 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,
@@ -115,7 +66,7 @@ object FrameGen {
return problem
}
WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_LSFG)
WaylandCompositor.nativeSetLsfgCachePath(cachePath)
WaylandCompositor.nativeSetLsfgCachePath(cache.absolutePath)
WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_LSFG, refreshHz)
WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, mode.target)
}
@@ -10,9 +10,11 @@ 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
@@ -37,8 +39,6 @@ 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,22 +95,18 @@ class DroidDeckHudHost(context: Context) {
stopMotion(hud)
shrinkPastEdge(hud, rawX, rawY)
}
hud.setOnFlungListener { vx, vy -> flingX = vx; flingY = vy }
hud.setOnFlungListener { vx, _ -> flingX = vx }
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
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 }
dockEdgeFor(hud)?.let { edge -> setDock(hud, edge); return@setOnMovedListener }
stopMotion(hud)
fadeDockPreview(hud)
if (snaps && !hud.isStrip) { snapToAnchor(hud, vx, vy); return@setOnMovedListener }
if (snaps && !hud.isStrip) { snapToAnchor(hud, vx); return@setOnMovedListener }
val fromX = hud.x; val fromY = hud.y
keepOnScreen(hud)
wantX = hud.x; wantY = hud.y
@@ -183,8 +179,9 @@ class DroidDeckHudHost(context: Context) {
private fun applyShown() {
if (!running) return
val show = !hidden && !backgrounded
view?.visibility = if (show) View.VISIBLE else View.GONE
showing = show
val visible = show && SessionState.mode != SessionService.MODE_DESKTOP
view?.visibility = if (visible) View.VISIBLE else View.GONE
showing = visible
if (show != polling) {
polling = show
if (show) Choreographer.getInstance().postFrameCallback(frameCallback)
@@ -241,36 +238,28 @@ class DroidDeckHudHost(context: Context) {
}
private fun presentedFps(): Float {
if (!runCatching { WaylandCompositor.nativeFrameGenActive() }
.getOrDefault(false)) return 0f
val stats = runCatching {
WaylandCompositor.nativeFrameGenStats()
}.getOrNull() ?: return 0f
if (FrameGen.mode(context).engine == FrameGen.ENGINE_OFF) return 0f
val stats = runCatching { WaylandCompositor.nativeFrameGenStats() }.getOrNull() ?: return 0f
return if (stats.size > 3 && stats[3] > 1f) stats[3] else 0f
}
/** 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
private fun dockEdgeFor(v: View): DroidDeckHudDock? {
val over = overhang(v) ?: return null
return over.key.takeIf { over.value >= DOCK_OVERHANG }
}
private fun overhang(v: View, dx: Float = 0f, dy: Float = 0f): Map.Entry<DroidDeckHudDock, Float>? {
private fun overhang(v: View): 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 -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,
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,
).maxByOrNull { it.value }
}
@@ -305,7 +294,6 @@ class DroidDeckHudHost(context: Context) {
}
private fun stopMotion(hud: DroidDeckHudView) {
throwSpring?.cancel()
hud.animate().setUpdateListener(null)
hud.animate().cancel()
}
@@ -335,21 +323,23 @@ class DroidDeckHudHost(context: Context) {
}
}
/** 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) {
private fun snapToAnchor(hud: DroidDeckHudView, vx: 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)
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
anchorX = if (hud.x + vx * FLING_REACH_S < maxX / 2f) 0f else 1f
wantX = anchorX * maxX
wantY = com.droiddeck.launcher.ui.EdgeFling.restY(hud.y, vy, 0f, maxY)
wantY = hud.y.coerceIn(0f, maxY)
SessionPrefs.setDroidDeckHudPosition(context, wantX, wantY)
stopMotion(hud)
hud.scaleX = 1f; hud.scaleY = 1f
if (Motion.scale == 0f) {
hud.scaleX = 1f; hud.scaleY = 1f
hud.x = wantX; hud.y = wantY
return
}
snapping = true
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) }
hud.animate().x(wantX).y(wantY).scaleX(1f).scaleY(1f).setDuration(Motion.ms(260).toLong()).setInterpolator(EASE)
.withEndAction { snapping = false; keepOnScreen(hud) }.start()
}
private fun shrinkPastEdge(hud: DroidDeckHudView, rawX: Float, rawY: Float) {
@@ -506,9 +496,10 @@ 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 = 360f
private const val STRIP_PULL_OFF_DP = 100f
private const val STRIP_PULL_ACROSS_DP = 600f
private const val STRIP_PULL_OFF_DP = 150f
private const val EXPAND_FADE = 0.5f
private val EASE = PathInterpolator(0.2f, 0.8f, 0.2f, 1f)
@@ -66,15 +66,6 @@ internal class FrameStats {
count++
}
@Synchronized
fun addIfNew(frametimeNs: Long, timeNs: Long, rebase: Boolean): Boolean {
if (timeNs <= lastPresentNs) return false
val elapsedNs = if (rebase && lastPresentNs != 0L) timeNs - lastPresentNs else frametimeNs
if (elapsedNs <= 0L) return false
add(elapsedNs, timeNs)
return true
}
@Synchronized
fun reset() {
graph.fill(0f)
@@ -208,11 +199,11 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
}
val n = HudFrames.nativePoll(handle, frametimes, times)
if (n > 0) {
var rebase = !fromGamescope
fromGamescope = true
for (i in 0 until n) {
if (stats.addIfNew(frametimes[i], times[i], rebase)) rebase = false
if (!fromGamescope) {
stats.reset()
fromGamescope = true
}
for (i in 0 until n) stats.add(frametimes[i], times[i])
lastRingFrameNs = times[n - 1]
} else if (lastRingFrameNs != 0L && nowNs - lastRingFrameNs > LIVE_NS) {
fromGamescope = false
@@ -50,7 +50,6 @@ 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;
@@ -87,18 +86,8 @@ 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;
}
@@ -135,6 +124,12 @@ 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;
@@ -56,7 +56,6 @@ 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();
@@ -290,10 +289,7 @@ public final class PadBridge {
}
public static boolean isControllerKeyEvent(KeyEvent event) {
return isControllerKeyEvent(event, event.getDevice());
}
static boolean isControllerKeyEvent(KeyEvent event, InputDevice device) {
InputDevice device = event.getDevice();
if (device == null || device.isVirtual() || isSystemVirtualInputName(device.getName())) return false;
if (KeyEvent.isGamepadButton(event.getKeyCode())) {
return device.supportsSource(InputDevice.SOURCE_GAMEPAD)
@@ -318,10 +314,7 @@ public final class PadBridge {
}
public static boolean isControllerMotionEvent(MotionEvent event) {
return isControllerMotionEvent(event, event.getDevice());
}
static boolean isControllerMotionEvent(MotionEvent event, InputDevice device) {
InputDevice device = event.getDevice();
return event.isFromSource(InputDevice.SOURCE_JOYSTICK) && device != null && !device.isVirtual()
&& !isSystemVirtualInputName(device.getName())
&& (device.supportsSource(InputDevice.SOURCE_GAMEPAD)
@@ -382,11 +375,10 @@ public final class PadBridge {
}
public synchronized boolean onKeyEvent(KeyEvent event) {
InputDevice device = event.getDevice();
if (!isControllerKeyEvent(event, device) || excluded.test(event.getDeviceId())) return false;
int slot = slotFor(device);
if (!isControllerKeyEvent(event) || excluded.test(event.getDeviceId())) return false;
int slot = slotFor(event.getDevice());
if (slot < 0) return false;
int side = JoyCon.side(device);
int side = JoyCon.side(event.getDevice());
if (side >= 0 && partners[slot] != NO_CONTROLLER && JoyCon.isRail(side, event.getScanCode())) return true;
long timing = InputTiming.begin();
PadState pad = stateFor(slot);
@@ -408,18 +400,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(device) ? DeckControls.R4 : DeckControls.L4, pressed);
if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(event.getDevice()) ? DeckControls.R4 : DeckControls.L4, pressed);
break;
case KeyEvent.KEYCODE_BUTTON_C:
if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(device) ? DeckControls.L4 : DeckControls.R4, pressed);
if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(event.getDevice()) ? DeckControls.L4 : DeckControls.R4, pressed);
break;
case KeyEvent.KEYCODE_BUTTON_L2:
pad.leftTrigger = keyTrigger(pad.leftTrigger, pressed, event.getRepeatCount(),
analogTrigger(device, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE), keyTriggers[slot], 0);
analogTrigger(event.getDevice(), MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE));
break;
case KeyEvent.KEYCODE_BUTTON_R2:
pad.rightTrigger = keyTrigger(pad.rightTrigger, pressed, event.getRepeatCount(),
analogTrigger(device, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS), keyTriggers[slot], 1);
analogTrigger(event.getDevice(), MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS));
break;
case KeyEvent.KEYCODE_DPAD_UP: pad.up = pressed; break;
case KeyEvent.KEYCODE_DPAD_RIGHT: pad.right = pressed; break;
@@ -427,7 +419,7 @@ public final class PadBridge {
case KeyEvent.KEYCODE_DPAD_LEFT: pad.left = pressed; break;
default: return false;
}
noteDevice(device, slot);
noteDevice(event.getDevice(), slot);
if (pressed && event.getRepeatCount() == 0 && !event.isCanceled()) noteChordInput(slot);
if (pressed) notePlayerInput();
statButtons++;
@@ -479,7 +471,6 @@ 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) {
@@ -498,16 +489,16 @@ public final class PadBridge {
}
public synchronized boolean onMotionEvent(MotionEvent event) {
InputDevice device = event.getDevice();
if (!isControllerMotionEvent(event, device) || excluded.test(event.getDeviceId())) return false;
if (!isControllerMotionEvent(event) || excluded.test(event.getDeviceId())) return false;
if (event.getAction() != MotionEvent.ACTION_MOVE) return false;
int slot = slotFor(device);
int slot = slotFor(event.getDevice());
if (slot < 0) return false;
long timing = InputTiming.begin();
PadState pad = stateFor(slot);
noteDevice(device, slot);
noteDevice(event.getDevice(), slot);
statAxes++;
scheduleStats();
InputDevice device = event.getDevice();
int side = JoyCon.side(device);
if (side >= 0) {
int[] stick = JoyCon.stickAxes(side, device, event.getSource());
@@ -524,7 +515,7 @@ public final class PadBridge {
}
float lx = event.getAxisValue(MotionEvent.AXIS_X);
float ly = event.getAxisValue(MotionEvent.AXIS_Y);
boolean wired = wiredXboxLayout(device, event.getSource());
boolean wired = wiredXboxLayout(event);
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);
@@ -534,11 +525,11 @@ public final class PadBridge {
float lt = 0f;
float rt = 0f;
if (wired || hasAxis(device, source, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE)) {
lt = axisTrigger(leftTrigger(event, wired), keyTriggers[slot], 0);
lt = leftTrigger(event, wired);
pad.leftTrigger = lt;
}
if (wired || hasAxis(device, source, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS)) {
rt = axisTrigger(rightTrigger(event, wired), keyTriggers[slot], 1);
rt = rightTrigger(event, wired);
pad.rightTrigger = rt;
}
if (hasAxis(device, source, MotionEvent.AXIS_HAT_X)) {
@@ -562,27 +553,9 @@ public final class PadBridge {
return true;
}
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 float keyTrigger(float current, boolean pressed, int repeatCount, boolean analog) {
if (analog || repeatCount > 0) return current;
return pressed ? 1f : 0f;
}
static boolean analogTrigger(InputDevice device, int... axes) {
@@ -1014,7 +987,7 @@ public final class PadBridge {
}
private boolean isPrimary(KeyEvent event) {
int id = event.getDeviceId();
int id = event.getDevice().getId();
int first = firstPlayerSlot();
return owners[first] == id || partners[first] == id;
}
@@ -232,24 +232,11 @@ object BattleNet {
}
internal fun hostFolder(context: Context, path: String): File? {
val drive = Regex("""^([A-Za-z]):[\\/](.*)$""").matchEntire(path.trim()) ?: return null
val drive = Regex("""^([CcZz]):[\\/](.*)$""").matchEntire(path.trim()) ?: return null
val relative = drive.groupValues[2].replace('\\', '/').trim('/')
if (relative.isEmpty() || relative.split('/').any { it == ".." }) return null
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")
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")
}
private val KEY = Regex("""^\[(.+)\](?:\s+\d+)?\s*$""")
@@ -374,7 +361,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, reuse = true).firstOrNull() ?: client
val exe = added.candidates(game.folder).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,7 +157,9 @@ class LinuxNetworkLinkComponent(
synchronized(lock) {
try {
file.parentFile?.mkdirs()
replace(file, describe(properties, capabilities))
val staged = File(file.path + ".staged")
staged.writeText(describe(properties, capabilities))
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
} catch (e: IOException) {
Log.w(TAG, "Could not publish the network link", e)
}
@@ -239,7 +241,9 @@ class LinuxNetworkLinkComponent(
}
try {
val file = File(rootDir, "etc/droiddeck-network.json")
replace(file, state.toString())
val staged = File(file.path + ".staged")
staged.writeText(state.toString())
if (!staged.renameTo(file)) throw IOException("Could not replace network state")
} catch (e: IOException) {
Log.w(TAG, "Could not publish the network state", e)
}
@@ -268,19 +272,6 @@ 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 }
@@ -295,7 +286,9 @@ class LinuxNetworkLinkComponent(
}
try {
val etc = File(rootDir, "etc")
replace(File(etc, "resolv.conf"), text)
val staged = File(etc, "resolv.conf.staged")
staged.writeText(text)
if (!staged.renameTo(File(etc, "resolv.conf"))) throw IOException("Could not replace resolv.conf")
val hosts = File(etc, "hosts")
if (!hosts.isFile || !hosts.readText().contains("localhost")) {
hosts.writeText("127.0.0.1 localhost\n::1 localhost\n")
@@ -1,44 +0,0 @@
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))
}
}
@@ -90,11 +90,11 @@ object GameStorage {
fun gamesFolderLibraries(context: Context): List<Library> {
if (SessionPrefs.gameStorage(context).isNotEmpty()) return emptyList()
val card = effective(context)?.let { SteamLibraries.canonical(File(it.path)) }
val added = SteamLibraries.list(context).map { SteamLibraries.canonical(it.host) }
val card = effective(context)?.let { canonical(File(it.path)) }
val added = SteamLibraries.list(context).map { canonical(it.host) }
val sm = context.getSystemService(StorageManager::class.java)
return AddedGames.roots(context).mapNotNull { root ->
val host = SteamLibraries.canonical(root.host)
val host = 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,6 +109,8 @@ 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) }
@@ -11,9 +11,6 @@ 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 ->
@@ -33,7 +30,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 = spared()
val spared = descendants(kept)
var killed = 0
File("/proc").listFiles()?.forEach { entry ->
val pid = entry.name.toIntOrNull() ?: return@forEach
@@ -3,7 +3,6 @@ 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)
@@ -18,8 +17,6 @@ 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 ||
@@ -27,8 +24,7 @@ data class SelectedGameProfile(
components.values.any { !it.inherited } ||
environmentOverrides > 0 ||
windowsComponentNames.isNotEmpty() ||
startWithoutSteam ||
!frameGenInherited
startWithoutSteam
companion object {
fun resolve(
@@ -42,8 +38,6 @@ 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)
@@ -74,8 +68,6 @@ data class SelectedGameProfile(
environmentOverrides = otherEnvironment.size,
windowsComponentNames = gameWindowsComponents.map(WinComponentNames::of),
startWithoutSteam = GameEnvironment.gameNoSteam(environment, game.profileKey),
frameGen = frameGenMode,
frameGenInherited = frameGenInherited,
)
}
}
@@ -77,7 +77,6 @@ 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")
@@ -595,10 +594,6 @@ 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,8 +70,6 @@ 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",
@@ -243,7 +241,7 @@ object SessionFiles {
var installed = false
try {
target.parentFile?.mkdirs()
(if (asset.startsWith("rockstar/")) requireNotNull(javaClass.getResourceAsStream("/$asset")) else context.assets.open("linuxfs/$asset")).use { input ->
context.assets.open("linuxfs/$asset").use { input ->
staged.outputStream().use { output -> FileUtils.copy(input, output) }
}
installed = staged.setExecutable(true, false) && staged.renameTo(target)
@@ -253,12 +253,6 @@ object SessionPrefs {
prefs(context).edit().putBoolean("railLabels", show).apply()
}
fun agentTab(context: Context): Boolean = prefs(context).getBoolean("agentTab", false)
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) {
@@ -1054,13 +1048,6 @@ 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 =
@@ -822,7 +822,6 @@ 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")
@@ -1607,11 +1606,10 @@ 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 || pid in spared) continue
if (pid == me) continue
val exe = try { File(proc, "exe").canonicalPath } catch (e: Exception) { continue }
if (!exe.startsWith(rootfs)) continue
android.os.Process.killProcess(pid)
@@ -1623,11 +1621,10 @@ 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 || pid in spared) continue
if (pid == me) continue
val cmdline = try {
File(proc, "cmdline").readBytes().toString(Charsets.UTF_8).replace('\u0000', ' ')
} catch (e: Exception) {
@@ -23,7 +23,6 @@ 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 =
{ _, _, _, _, _, _ -> },
@@ -155,7 +154,6 @@ 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)
@@ -18,12 +18,12 @@ object SettingsReset {
"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", "agentTab", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"stretch16x9", "picturePosition", "railLabels", "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", "buildWatermark",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics",
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
"bootMovieApplyNext", "bootMovieSteamSeen",
@@ -43,7 +43,6 @@ 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,14 +82,13 @@ object SteamLibraries {
/** Reads storage; call off the main thread. */
fun found(context: Context): List<Found> {
val entries = list(context)
val taken = taken(context, entries) + GameStorage.gamesFolderLibraries(context).map { canonical(it.host) }
val gamesFolders = AddedGames.roots(context).map { canonical(it.host) }
val taken = taken(context, entries) + 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() && offered(taken, gamesFolders, canonical(dir))) hits += dir to games
if (games > 0 && File(dir, "steamapps").canWrite() && taken.none { overlaps(it, canonical(dir)) }) hits += dir to games
}
}
val picked = ArrayList<Pair<File, Int>>()
@@ -102,9 +101,6 @@ 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
@@ -175,7 +171,7 @@ object SteamLibraries {
internal fun overlaps(a: String, b: String): Boolean = a == b || a.startsWith("$b/") || b.startsWith("$a/")
internal fun canonical(file: File): String = UsbLink.storagePath(runCatching { file.canonicalPath }.getOrDefault(file.absolutePath))
private 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,8 +11,6 @@ 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"
@@ -20,7 +18,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, EAC_RUNTIME, BATTLEYE_RUNTIME,
SCOUT, SOLDIER, SNIPER, ARM_RUNTIME, PROTON_ARM, PROTON_11_ARM, REDISTRIBUTABLES, FEX,
)
private val APP_ID = Regex("^\\s*\"appid\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
@@ -95,7 +93,6 @@ 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, ANTICHEAT_RUNTIME, STEAM_TOOL, OLD_RUNTIME, X86_PROTON, CUSTOM, CUSTOM_UNKNOWN, X64_CLIENT }
enum class ToolReason { DEFAULT_PROTON, PROTON, FEX_RUNTIME, ARM_RUNTIME, REDISTRIBUTABLES, FEX, 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,7 +153,6 @@ 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.ROCKSTAR -> ""
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT -> ""
} ?: 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, Store.ROCKSTAR -> null
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT -> 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, Store.ROCKSTAR -> null
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT -> null
}
private fun gogScopedToken(context: Context, id: String, clientId: String): String? {
@@ -15,7 +15,6 @@ 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
}
@@ -23,7 +22,6 @@ 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,8 +9,7 @@ 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"),
ROCKSTAR("rockstar", "Rockstar Games", "Rockstar");
EA("ea", "EA", "EA");
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 || store == Store.ROCKSTAR) == null) {
check(store != Store.XBOX && store != Store.ROCKSTAR) { "Android Keystore is unavailable for ${store.label} credentials" }
if (seal(f, json, retry = store == Store.XBOX) == null) {
check(store != Store.XBOX) { "Android Keystore is unavailable for Xbox credentials" }
put(f, json.toString())
}
}
@@ -106,7 +106,6 @@ 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
@@ -1,119 +0,0 @@
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,13 +18,8 @@ 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 || sidecar.store == Store.ROCKSTAR
val needs = sidecar.args.isNotEmpty() || sidecar.env.isNotEmpty() || sidecar.store == Store.EPIC || sidecar.store == Store.EA || sidecar.store == Store.UBISOFT
val file = File(folder, LAUNCHER)
if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(file.toPath())) return sidecar.copy(launcher = null)
if (sidecar.store == Store.ROCKSTAR && !com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(sidecar.id)) {
file.delete()
return sidecar.copy(launcher = null)
}
if (!needs) { file.delete(); return sidecar.copy(launcher = null) }
file.writeText(launcherText(sidecar))
return sidecar.copy(launcher = LAUNCHER)
@@ -37,7 +32,7 @@ object StoreLaunch {
val lines = ArrayList<String>()
lines += "@echo off"
lines += "setlocal"
if (sidecar.store != Store.ROCKSTAR) lines += "rem Written by DroidDeck for ${sidecar.store.label}: ${sidecar.title}. Steam's shortcut runs this file."
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) }
@@ -59,9 +54,6 @@ 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 += "\"C:\\Program Files\\Rockstar Games\\Launcher\\Launcher.exe\""
lines += "exit /b %errorlevel%"
} else if (sidecar.store == Store.UBISOFT) {
lines += "if not exist \"%~dp0$UBISOFT_LAUNCH\" goto direct"
lines += "if not exist \"$UBISOFT_SERVICE\" goto direct"
@@ -101,12 +93,11 @@ 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 !in listOf(Store.UBISOFT, Store.ROCKSTAR) || !sidecar.isInstalled) return sidecar
if (sidecar.store == Store.ROCKSTAR && !com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(sidecar.id)) return sidecar
if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(File(folder, LAUNCHER).toPath())) return sidecar.copy(launcher = null)
if (sidecar.store != Store.UBISOFT || !sidecar.isInstalled) return sidecar
val wrongExe = !sidecar.exeFile(folder).isFile || sidecar.exe.contains("installer", ignoreCase = true) || sidecar.exe.contains("autorun", ignoreCase = true)
if (sidecar.store == Store.UBISOFT && sidecar.launcher == LAUNCHER && !wrongExe) return sidecar
if (sidecar.launcher == LAUNCHER && !wrongExe) return sidecar
val exe = 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
@@ -76,14 +76,6 @@ 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,7 +66,6 @@ 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
@@ -284,7 +283,6 @@ 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 shared(sizeRequests, item.key) {
return sizeRequests.computeIfAbsent(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.ROCKSTAR -> {}
Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT -> {}
}
}
}, pool).exceptionally { error ->
@@ -66,25 +66,6 @@ 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) {
@@ -97,7 +78,7 @@ object StoreSizes {
onDisk[key]?.let { return CompletableFuture.completedFuture(it) }
val app = context.applicationContext
val version = "disk:${game.sidecar.installedAt}:${game.sidecar.installVersion}"
return shared(diskRequests, key) {
return diskRequests.computeIfAbsent(key) {
CompletableFuture.supplyAsync({
val c = cache(app, game.sidecar.store)
c.get("disk:${game.sidecar.id}", version)
@@ -132,7 +113,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, Store.ROCKSTAR -> 0L
Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT -> 0L
Store.ITCH -> com.droiddeck.launcher.stores.itch.ItchLibrary.size(context, item)
Store.GAMEJOLT -> com.droiddeck.launcher.stores.gamejolt.GameJoltBuilds.size(context, item)
} }
@@ -236,27 +236,6 @@ 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 }
@@ -380,12 +359,6 @@ 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,7 +22,6 @@ object EaApi {
val downloadable: Boolean,
val trial: Boolean,
val ownership: List<String>,
val productName: String = "",
)
class Offer(
@@ -110,7 +109,6 @@ 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" }
@@ -199,18 +197,6 @@ 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,7 +11,6 @@ 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
@@ -41,8 +40,6 @@ 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("/")) {} }
}
@@ -53,32 +50,7 @@ object EaBackend : StoreBackend {
Thread({ EaLibrary.sync(app, force) }, "ea-sync").start()
}
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 loadShelves(context: Context, force: Boolean) {}
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,14 +36,13 @@ 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("productName", productName)
.put("locales", JSONArray(locales))
companion object {
fun fromJson(o: JSONObject): EaGame? {
@@ -64,15 +63,14 @@ 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_v3"
private const val KEY_SYNCED_AT = "library_synced_at_v3"
private const val KEY_CACHE = "library_cache"
private const val KEY_SYNCED_AT = "library_synced_at"
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
@@ -120,7 +118,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, "productName" to g.productName),
extra = mapOf("contentId" to g.contentId, "slug" to g.slug, "version" to g.version),
logoUrl = g.logo.ifEmpty { null },
)
}
@@ -139,16 +137,6 @@ 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()
@@ -201,7 +189,8 @@ object EaLibrary {
StoresState.post {
if (gen != generation.get()) return@post
StoresState.library[store] = mergeItems(StoresState.library[store], items)
StoresState.shelves[store]?.let { StoresState.shelves[store] = StoreFront.markOwned(it, items, EaStore::sameGame) }
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())
}
}
@@ -240,28 +229,13 @@ 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 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 owned = withToken(app, token) { EaApi.owned(it) }
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()) {
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 (picked.isEmpty()) return problem(if (cache.isEmpty()) app.getString(R.string.stores_sync_no_games, store.label) else null)
if (gen != generation.get()) return
status(R.string.stores_sync_cover_art)
val images = art(app, token, picked.map { it.first.slug }, gen)
@@ -272,7 +246,6 @@ 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,29 +175,13 @@ 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 headers = mapOf("X-Requester-Id" to "Origin Online Activation", "User-Agent" to "EACTransaction")
val reply = retryTokenRejected { EaHttp.request(url, headers = headers) }
val reply = EaHttp.request(url, headers = mapOf("X-Requester-Id" to "Origin Online Activation", "User-Agent" to "EACTransaction"))
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)
@@ -1,120 +0,0 @@
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,19 +65,13 @@ internal object GogFiles {
fun dir(folder: File): File = inside(folder, ".droiddeck-gog").apply { mkdirs() }
fun journal(folder: File): File = File(dir(folder), "operation.json")
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 &&
parts.none { it.isEmpty() || it == "." || it == ".." }) { "Invalid GOG path: $raw" }
return parts
}
fun inside(root: File, raw: String): File {
val parts = parts(raw)
val path = raw.replace('\\', '/')
require(path.isNotBlank() && !path.startsWith('/') && ':' !in path && '\u0000' !in path &&
path.split('/').none { it.isEmpty() || it == "." || it == ".." }) { "Invalid GOG path: $raw" }
val base = root.canonicalFile
var out = base
for (part in parts) {
for (part in path.split('/')) {
out = File(out, part)
require(!Files.isSymbolicLink(out.toPath())) { "GOG path is a symbolic link: $raw" }
}
@@ -128,28 +122,21 @@ 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('\\', '/')
val parts = parts(path)
inside(folder, 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 = base
var parent = folder
var relative = ""
for (part in parts) {
for (part in path.split('/')) {
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" }
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
require(parent.list()?.none { it != part && it.equals(part, true) } != false) { "An existing path differs only by case: $path" }
parent = File(parent, part)
}
}
}
@@ -1,198 +0,0 @@
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)
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"))
}
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)
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,
)
}
fun signOut(context: Context) = synchronized(lock) { StoreAccounts.clear(context.applicationContext, Store.ROCKSTAR) }
}
@@ -1,206 +0,0 @@
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 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
}
@@ -1,263 +0,0 @@
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
}
}
}
@@ -1,56 +0,0 @@
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")
fun supports(id: String?) = id != null && 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 pipe = pipes[id] ?: return failure("unsupported-title")
val title = RockstarTitles.byId(id) ?: return failure("unknown-title")
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 ||
!java.io.File(folder, "MTLX.dll").isFile) return failure("missing-game-files")
var ticket = RockstarAuth.ticket(app) ?: 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 (RockstarLibrary.owned(account).none { it.id == id } || RockstarApps.deliverer(account.apps, title) == null) return failure("not-owned")
val tokenRoot = RockstarRos.result("app.asmx/GetTitleAccessToken2", listOf("ticket" to ticket.ticket, "titleId" to title.rosTitleId.toString(), "platformId" to "8"))
val token = RockstarRos.text(tokenRoot, "Result")?.takeIf { it.isNotEmpty() } ?: return failure("no-title-token")
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 JSONObject().put("ok", true).put("pipe", pipe).put("material", material).put("expiresAt", System.currentTimeMillis() + 90_000)
}
private fun failure(reason: String) = JSONObject().put("ok", false).put("reason", reason)
}
@@ -1,66 +0,0 @@
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) }
}
}
@@ -1,96 +0,0 @@
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
}
}
@@ -1,84 +0,0 @@
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,
)
}
@@ -10,7 +10,6 @@ import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.LoginFlows
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreBackend
import com.droiddeck.launcher.stores.StoreFront
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
@@ -45,21 +44,15 @@ object UbisoftBackend : StoreBackend {
Thread({ UbisoftLibrary.sync(app, force) }, "ubisoft-sync").start()
}
override fun loadShelves(context: Context, force: Boolean) {
val app = context.applicationContext
val account = UbisoftLibrary.account()
UbisoftStore.cached(app)?.let { s -> StoresState.post { StoresState.shelves[store] = StoreFront.markOwned(s, StoresState.library[store], UbisoftStore::sameGame) } }
Thread({
val shelves = UbisoftStore.featured(app, force) ?: return@Thread
StoresState.post { if (UbisoftLibrary.account() == account) StoresState.shelves[store] = StoreFront.markOwned(shelves, StoresState.library[store], UbisoftStore::sameGame) }
}, "ubisoft-shelves").start()
}
override fun search(context: Context, query: String): List<CatalogItem> =
StoreFront.markOwned(UbisoftStore.search(query), StoresState.library[store], UbisoftStore::sameGame)
override fun loadShelves(context: Context, force: Boolean) {}
override fun install(context: Context, item: CatalogItem, root: java.io.File) {
val app = context.applicationContext
item.extra[STEAM_APP]?.takeIf { item.extra["productId"] == null }?.let { steam ->
StoresState.logLine("Ubisoft: ${item.title} is owned on Steam; installing Steam app $steam")
installInSteam(app, steam)
return
}
if (!UbisoftNative.ready()) {
StoresState.logLine(UbisoftNative.ENGINE_MISSING)
StoresState.post { StoresState.problems[store] = UbisoftNative.ENGINE_MISSING }
@@ -72,6 +65,19 @@ object UbisoftBackend : StoreBackend {
}
override fun uninstall(context: Context, game: InstalledStoreGame) {}
const val STEAM_APP = "steamAppId"
/** Steam asks to install a game it does not have when told to run it. */
private fun installInSteam(app: Context, steamAppId: String) {
if (com.droiddeck.launcher.session.SessionState.running) {
if (!com.droiddeck.launcher.session.SessionService.launchGame(app, steamAppId)) StoresState.logLine("Ubisoft: Steam is busy; install Steam app $steamAppId there")
return
}
app.startActivity(Intent(app, com.droiddeck.launcher.SessionActivity::class.java)
.putExtra(com.droiddeck.launcher.session.SessionService.EXTRA_STEAM_URL, com.droiddeck.launcher.frontend.GameLaunchLink.steamUrl(steamAppId))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
}
internal class UbisoftLogin(override val userAgent: String) : StoreLoginActivity.Flow {
@@ -109,9 +115,6 @@ object UbisoftLibrary {
StoresState.post { StoresState.shelves.remove(Store.UBISOFT) }
}
/** Changes on every sign-out, so work begun for the old account can tell. */
fun account(): Int = generation.get()
private fun post(gen: Int, block: () -> Unit) = StoresState.post { if (generation.get() == gen) block() }
internal fun parsePage(body: String): Pair<List<CatalogItem>, Int> {
@@ -131,20 +134,11 @@ object UbisoftLibrary {
return items to games.optInt("totalCount", items.size)
}
private val THIRD_PARTY = Regex("""^\s*third_party_platform:\s*\r?\n\s+name:\s*['"]?([^'"\r\n]+?)['"]?\s*$""", RegexOption.MULTILINE)
/** The store a product's configuration says delivers it, such as Steam, when not Ubisoft itself. */
internal fun thirdParty(configuration: String): String? = THIRD_PARTY.find(configuration)?.groupValues?.get(1)?.trim()?.takeIf { it.isNotEmpty() }
/**
* Owned base games Ubisoft delivers itself, by UbiServices space; add-ons and bundles share spaces with their
* game. A game whose manifest Ubisoft did not send stays: the manifest only names the build to download.
*/
/** Base games with a manifest, by UbiServices space; add-ons and bundles share spaces with their game. */
internal fun ownedBySpace(owned: JSONObject?): Map<String, JSONObject> {
val list = owned?.optJSONArray("games") ?: return emptyMap()
val games = (0 until list.length()).mapNotNull { list.optJSONObject(it) }
.filter { it.optInt("productType") == 0 && it.optBoolean("owned", true) && thirdParty(it.optString("configuration")) == null }
.sortedByDescending { it.optString("manifest").isNotEmpty() }
.filter { it.optString("manifest").isNotEmpty() && it.optInt("productType") == 0 && it.optBoolean("owned", true) }
val out = LinkedHashMap<String, JSONObject>()
for (key in listOf("spaceId")) for (g in games) {
val space = g.optString(key).takeIf { it.isNotEmpty() } ?: continue
@@ -153,30 +147,19 @@ object UbisoftLibrary {
return out
}
private fun download(o: JSONObject) = listOfNotNull(
"productId" to o.optLong("productId").toString(),
o.optString("manifest").takeIf { it.isNotEmpty() }?.let { "manifest" to it },
o.optString("appId").takeIf { it.isNotEmpty() }?.let { "appId" to it },
executable(o.optString("configuration"))?.let { "exe" to it },
)
private val STEAM_ID = Regex("""^\s*steam_app_id:\s*['"]?(\d+)""", RegexOption.MULTILINE)
private val THIRD_PARTY = Regex("""^\s*third_party_platform:\s*\r?\n\s+name:\s*['"]?Steam\b""", setOf(RegexOption.MULTILINE, RegexOption.IGNORE_CASE))
/**
* Games Connect owns and delivers itself. The profile's game list also names games only played through
* Ubisoft+, free weekends or another store; without an ownership answer that list is all there is.
*/
internal fun assemble(listed: List<CatalogItem>, owned: JSONObject?): List<CatalogItem> {
val known = owned?.optJSONArray("games") != null && owned.optString("error").isEmpty()
val bySpace = ownedBySpace(owned)
val matched = listed.map { g -> bySpace[g.id]?.let { g.copy(extra = g.extra + download(it)) } ?: g }
.filter { !known || it.extra["productId"] != null }
.let { games -> games.filter { g -> g.extra["productId"] == null || games.first { it.extra["productId"] == g.extra["productId"] } === g } }
.let { games -> games.filter { g -> g.extra["productId"] != null || games.none { it !== g && it.title == g.title && it.extra["productId"] != null } } }
val products = matched.mapNotNull { it.extra["productId"] }.toSet()
val unlisted = bySpace.filterKeys { space -> listed.none { it.id == space } }.filterValues { it.optLong("productId").toString() !in products }.mapNotNull { (space, o) ->
val title = title(o.optString("configuration")) ?: return@mapNotNull null
CatalogItem(Store.UBISOFT, space, title, null, owned = true, extra = mapOf("spaceId" to space) + download(o))
}
return (matched + unlisted).sortedBy { it.title.lowercase() }
/** The Steam app of a product Ubisoft says is owned and installed through Steam. */
internal fun steamApp(configuration: String): String? =
if (THIRD_PARTY.containsMatchIn(configuration)) STEAM_ID.find(configuration)?.groupValues?.get(1) else null
/** Owned games Ubisoft delivers through Steam, by UbiServices space. */
internal fun steamBySpace(owned: JSONObject?): Map<String, String> {
val list = owned?.optJSONArray("games") ?: return emptyMap()
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }
.filter { it.optInt("productType") == 0 && it.optBoolean("owned", true) && it.optString("spaceId").isNotEmpty() }
.mapNotNull { o -> steamApp(o.optString("configuration"))?.let { o.optString("spaceId") to it } }.toMap()
}
private val RELATIVE = Regex("""relative:\s*['"]?([^'"\r\n]+?)['"]?\s*$""", RegexOption.MULTILINE)
@@ -222,26 +205,37 @@ object UbisoftLibrary {
}
val owned = UbisoftNative.call("owned", JSONObject().put("ticket", s.ticket).put("sessionId", s.sessionId))
owned?.optString("error")?.takeIf { it.isNotEmpty() }?.let { StoresState.logLine("Ubisoft: ownership: $it") }
val bySpace = ownedBySpace(owned)
owned?.takeIf { it.optInt("manifestsAsked") > 0 }?.let {
StoresState.logLine("Ubisoft: latest manifests: ${it.optInt("manifestsFound")} of ${it.optInt("manifestsAsked")} ${it.optString("manifestError")}".trim())
}
fun download(o: JSONObject) = listOfNotNull(
"productId" to o.optLong("productId").toString(),
o.optString("manifest").takeIf { it.isNotEmpty() }?.let { "manifest" to it },
o.optString("appId").takeIf { it.isNotEmpty() }?.let { "appId" to it },
executable(o.optString("configuration"))?.let { "exe" to it },
)
val listed = all.distinctBy { it.id }
val games = assemble(listed, owned)
ownedBySpace(owned).values.filter { it.optString("manifest").isEmpty() }.takeIf { it.isNotEmpty() }?.let { bare ->
StoresState.logLine("Ubisoft: owned without a manifest: " + bare.joinToString(", ") { (title(it.optString("configuration")) ?: "?") + "=" + it.optLong("productId") })
val onSteam = steamBySpace(owned)
val matched = listed.map { g -> bySpace[g.id]?.let { g.copy(extra = g.extra + download(it)) } ?: onSteam[g.id]?.let { g.copy(extra = g.extra + (UbisoftBackend.STEAM_APP to it)) } ?: g }
.let { games -> games.filter { g -> g.extra["productId"] == null || games.first { it.extra["productId"] == g.extra["productId"] } === g } }
.let { games -> games.filter { g -> g.extra["productId"] != null || games.none { it !== g && it.title == g.title && it.extra["productId"] != null } } }
val products = matched.mapNotNull { it.extra["productId"] }.toSet()
val unlisted = bySpace.filterKeys { space -> listed.none { it.id == space } }.filterValues { it.optLong("productId").toString() !in products }.mapNotNull { (space, o) ->
val title = title(o.optString("configuration")) ?: return@mapNotNull null
CatalogItem(Store.UBISOFT, space, title, null, owned = true, extra = mapOf("spaceId" to space) + download(o))
}
StoresState.logLine("Ubisoft: ${ownedBySpace(owned).size} owned products; " +
val games = (matched + unlisted).sortedBy { it.title.lowercase() }
StoresState.logLine("Ubisoft: ${bySpace.size} downloadable products; " +
games.filter { it.extra.containsKey("productId") }.joinToString(", ") { "${it.title}=${it.extra["productId"]}" })
listed.filter { g -> games.none { it.id == g.id } }.takeIf { it.isNotEmpty() }?.let { left ->
StoresState.logLine("Ubisoft: left out ${left.size} games Connect does not deliver to this account: " + left.joinToString(", ") { it.title })
}
post(gen) {
StoresState.status.remove(Store.UBISOFT)
StoresState.problems.remove(Store.UBISOFT)
StoresState.library[Store.UBISOFT] = games
StoresState.shelves[Store.UBISOFT]?.let { StoresState.shelves[Store.UBISOFT] = StoreFront.markOwned(it, games, UbisoftStore::sameGame) }
StoresState.shelves[Store.UBISOFT] = com.droiddeck.launcher.stores.StoreShelves(
trending = games.sortedByDescending { it.extra.containsKey("productId") }, art = games.mapNotNull { it.imageUrl })
}
StoresState.logLine("Ubisoft: ${games.size} owned games")
StoresState.logLine("Ubisoft: ${games.size} owned games; on Steam: " + games.filter { it.extra.containsKey(UbisoftBackend.STEAM_APP) }.joinToString(", ") { "${it.title}=${it.extra[UbisoftBackend.STEAM_APP]}" })
} catch (e: Exception) {
StoresState.logLine("Ubisoft: library sync failed: ${e.javaClass.simpleName} ${e.message.orEmpty().take(200)}")
post(gen) { StoresState.status.remove(Store.UBISOFT); StoresState.problems[Store.UBISOFT] = app.getString(R.string.stores_sync_failed) }
@@ -1,129 +0,0 @@
package com.droiddeck.launcher.stores.ubisoft
import android.content.Context
import android.net.Uri
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreFront
import com.droiddeck.launcher.stores.StoreNet
import com.droiddeck.launcher.stores.StoreShelves
import com.droiddeck.launcher.stores.cleanStoreText
import com.droiddeck.launcher.stores.matureByAge
import org.json.JSONArray
import org.json.JSONObject
import java.text.NumberFormat
import java.time.Instant
import java.util.Currency
import java.util.Locale
/** Ubisoft's PC catalog, from the product search the Ubisoft Store website uses. */
object UbisoftStore {
/** The Ubisoft Store website's own read-only search key, sent by every store page. */
private const val APP = "XELY3U4LOD"
private const val KEY = "5638539fd9edb8f2c6b024b49ec375bd"
private const val SHELF = 24
private val RATING_AGE = mapOf("esrb-m" to 17, "esrb-ao" to 18, "pegi-18" to 18, "pegi-16" to 16, "usk-18" to 18)
/** The store sites with an English catalog: site, index locale, currency. */
private val SITES = mapOf(
"US" to Triple("us", "en_US", "USD"), "GB" to Triple("uk", "en_GB", "GBP"),
"CA" to Triple("ca", "en_CA", "CAD"), "AU" to Triple("anz", "en_AU", "AUD"), "NZ" to Triple("anz", "en_AU", "NZD"),
)
private fun site() = SITES[Locale.getDefault().country.uppercase(Locale.ROOT)] ?: SITES.getValue("US")
private fun index(site: Triple<String, String, String>, order: String) = "production__${site.first}_ubisoft__products__${site.second}__$order"
private val fronts = HashMap<Triple<String, String, String>, StoreFront>()
/** Each store site keeps its own shelves, so a region change never shows another region's prices. */
private fun front(context: Context): StoreFront = synchronized(fronts) {
val site = site()
fronts.getOrPut(site) {
StoreFront(Store.UBISOFT, { context.applicationContext.getSharedPreferences("stores.ubisoft", Context.MODE_PRIVATE) },
{ fetch(site) }, key = "store_front_${site.first}_${site.third}")
}
}
fun cached(context: Context): StoreShelves? = front(context).cached()
fun featured(context: Context, force: Boolean): StoreShelves? = front(context).shelves(force)
fun search(query: String): List<CatalogItem> {
val term = query.trim()
if (term.length < 2) return emptyList()
return query(site(), "best_sellers", 40, query = term).orEmpty()
}
/** Whether a store card and a library entry are the same game. */
fun sameGame(shelf: CatalogItem, owned: CatalogItem): Boolean {
val product = shelf.extra["productId"].orEmpty()
if (product.isNotEmpty() && product == owned.extra["productId"]) return true
val key = StoreFront.titleKey(owned.title)
return key.isNotEmpty() && key == baseTitle(shelf.title)
}
/** A product title without its edition, so "Far Cry® 6 - Gold Edition" is "far cry 6". */
internal fun baseTitle(title: String): String = StoreFront.titleKey(title.substringBefore(" - "))
/** One page of the index, or null when Ubisoft did not answer. */
private fun query(site: Triple<String, String, String>, order: String, hits: Int, query: String = "", filters: String = "", facets: List<String> = emptyList()): List<CatalogItem>? {
val facetFilters = JSONArray().put("product_type:Games").put("Platform:PC (Digital)").apply { facets.forEach { put(it) } }
val url = Uri.parse("https://$APP-dsn.algolia.net/1/indexes/${index(site, order)}").buildUpon()
.appendQueryParameter("query", query)
.appendQueryParameter("hitsPerPage", (hits * 2).toString())
.appendQueryParameter("facetFilters", facetFilters.toString())
.apply { if (filters.isNotEmpty()) appendQueryParameter("filters", filters) }
.build().toString()
val body = StoreNet.get(url, headers = mapOf("X-Algolia-Application-Id" to APP, "X-Algolia-API-Key" to KEY)) ?: return null
return parse(JSONObject(body), site.third).take(hits)
}
internal fun parse(answer: JSONObject, currency: String, now: Instant = Instant.now()): List<CatalogItem> {
val hits = answer.optJSONArray("hits") ?: return emptyList()
val items = (0 until hits.length()).mapNotNull { hits.optJSONObject(it) }.mapNotNull { item(it, currency, now) }
return items.groupBy { baseTitle(it.title) }.values.map { editions -> editions.firstOrNull { " - " !in it.title } ?: editions.first() }
}
private fun money(amount: Double, currency: String): String = NumberFormat.getCurrencyInstance(Locale.US).apply {
this.currency = Currency.getInstance(currency)
}.format(amount)
internal fun item(h: JSONObject, currency: String, now: Instant): CatalogItem? {
fun s(k: String) = h.optString(k).takeIf { it.isNotBlank() && it != "null" }
val id = s("objectID") ?: s("id") ?: return null
val title = s("title") ?: s("name") ?: return null
if (s("Free_offer") == "demo") return null
val price = h.optJSONObject("price")?.optDouble(currency)?.takeUnless { it.isNaN() }
val base = h.optJSONObject("default_price")?.optDouble(currency)?.takeUnless { it.isNaN() }
val discount = s("promotion_percentage")?.toDoubleOrNull()?.toInt() ?: 0
val released = s("release_date")?.let { runCatching { Instant.parse(it) }.getOrNull() }
if (released != null && released.isAfter(now) && s("preorder") != "true") return null
val free = s("Free_offer") == "freeplay" || price == 0.0
val image = s("image_link")?.substringBefore("?")
return CatalogItem(
store = Store.UBISOFT, id = "ubisoft-store:$id", title = title.trim(),
imageUrl = image, tallImageUrl = image, tags = listOfNotNull(s("Genre"), s("Edition")).joinToString(", "),
isFree = free, hasPrice = price != null, finalPrice = price?.let { money(it, currency) }.orEmpty(),
originalPrice = if (discount > 0 && base != null) money(base, currency) else "", discountPercent = if (discount > 0 && base != null) discount else 0,
storeUrl = s("link") ?: s("linkWeb").orEmpty(), publisher = "Ubisoft", releaseDate = released?.toString()?.take(10).orEmpty(),
description = cleanStoreText(s("longDescription")),
mature = s("adult").equals("TRUE", true) || matureByAge(listOfNotNull(s("Rating")?.let(RATING_AGE::get))),
extra = buildMap {
s("productLauncherIDString")?.let { put("productId", it) }
if (s("partOfUbisoftPlus").equals("true", true)) put("ubisoftPlus", "true")
},
)
}
/** All four rows, or a failure when any of them failed, so a partial refresh never replaces a good one. */
private fun fetch(site: Triple<String, String, String>): StoreFront.Catalog {
fun row(order: String, filters: String = "", facets: List<String> = emptyList()) =
query(site, order, SHELF, filters = filters, facets = facets) ?: throw java.io.IOException("Ubisoft store $order $filters$facets failed")
val trending = row("best_sellers")
val newest = row("release_date")
val deals = row("best_sellers", filters = "promotion_percentage > 0")
val free = row("best_sellers", facets = listOf("Free_offer:freeplay"))
return StoreFront.Catalog(StoreShelves(whatsNew = newest, deals = deals, free = free, trending = trending, art = trending.mapNotNull { it.imageUrl }))
}
}
@@ -29,7 +29,6 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
@@ -40,12 +39,15 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
@@ -55,7 +57,7 @@ import com.droiddeck.launcher.agent.AgentHost
import com.droiddeck.launcher.agent.AgentHost.Entry
@Composable
internal fun AgentEntry(entry: Entry, running: Boolean, last: Boolean = false, changes: Changes? = null, onRevise: () -> Unit = {}) {
internal fun AgentEntry(entry: Entry, running: Boolean, last: Boolean = false) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
when (entry) {
@@ -70,66 +72,12 @@ internal fun AgentEntry(entry: Entry, running: Boolean, last: Boolean = false, c
is Entry.Thought -> AgentThought(entry.text, live = false)
is Entry.Used -> if (entry.tool == "TodoWrite") AgentTodos(entry.input) else AgentToolCall(entry, running)
is Entry.Result -> Unit
is Entry.Finished -> when {
last && AgentHost.answerless(AgentHost.entries) -> AgentNoReply()
last && entry.planned -> Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
AgentTurnEnd(entry, changes)
AgentPlanActions(onRevise)
}
else -> AgentTurnEnd(entry, changes)
}
is Entry.Finished -> if (last && AgentHost.answerless(AgentHost.entries)) AgentNoReply() else AgentTurnEnd(entry)
}
}
/** A plan turn changed nothing; Go carries the plan out with plan mode off, Revise asks for another. */
@Composable
private fun AgentPlanActions(onRevise: () -> Unit) {
val context = LocalContext.current
val pal = LocalPalette.current
val go = stringResource(R.string.agent_plan_go_message)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(horizontal = 4.dp)) {
PrimaryButton(stringResource(R.string.agent_plan_go), compact = true, modifier = Modifier.testTag("agent-plan-go")) {
AgentHost.choosePlan(context, false)
AgentHost.send(context, go)
}
SecondaryButton(stringResource(R.string.agent_plan_revise), compact = true, modifier = Modifier.testTag("agent-plan-revise")) {
AgentHost.choosePlan(context, true)
onRevise()
}
Text(stringResource(R.string.agent_plan_untouched), fontSize = 12.sp, color = pal.onSurfaceVariant)
}
}
/** What a turn's edits added up to: files touched and lines added and removed. */
internal data class Changes(val files: Int, val added: Int, val removed: Int)
/** The edits of the turn that ends at [end], or null when it changed no file. */
internal fun turnChanges(entries: List<Entry>, end: Int): Changes? {
val start = entries.subList(0, end).indexOfLast { it is Entry.Asked }
// Plan mode saves its plan as a file of its own, which is not a change to anything.
val edits = entries.subList(start + 1, end).filterIsInstance<Entry.Used>().filter { !it.failed }.mapNotNull { diffOf(it) }
.filter { !it.path.contains("/.claude/plans/") }
if (edits.isEmpty()) return null
return Changes(edits.map { it.path }.distinct().size, edits.sumOf { it.added }, edits.sumOf { it.removed })
}
internal class Diff(val path: String, val lines: List<String>) {
val added = lines.count { it.startsWith("+") }
val removed = lines.count { it.startsWith("-") }
}
/** The diff an Edit or Write carries: its path, then lines led by ' ', '-' or '+'. */
internal fun diffOf(entry: Entry.Used): Diff? {
if (entry.tool != "Edit" && entry.tool != "Write") return null
val lines = entry.input.lines()
val body = lines.drop(1).filter { it.isNotEmpty() }
if (lines.first().isBlank() || body.isEmpty() || body.any { it[0] != ' ' && it[0] != '-' && it[0] != '+' }) return null
if (body.none { it[0] != ' ' }) return null
return Diff(lines.first(), body)
}
@Composable
private fun AgentTurnEnd(entry: Entry.Finished, changes: Changes?) {
private fun AgentTurnEnd(entry: Entry.Finished) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val text = when {
@@ -142,19 +90,10 @@ private fun AgentTurnEnd(entry: Entry.Finished, changes: Changes?) {
if (u.inputTokens > 0 || u.outputTokens > 0) add(stringResource(R.string.agent_tokens, tokens(u.inputTokens), tokens(u.outputTokens)))
}.joinToString(" · ")
}
}
if (text.isNullOrEmpty() && changes == null) return
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(horizontal = 4.dp)) {
if (changes != null) Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 9.dp, vertical = 4.dp).testTag("agent-changes"),
) {
Text(pluralStringResource(R.plurals.agent_files_changed, changes.files, changes.files), fontSize = 12.sp, color = pal.onSurfaceVariant)
Text("+${changes.added}", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.good)
Text("−${changes.removed}", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.error)
}
if (!text.isNullOrEmpty()) Text(text, fontSize = 12.sp, color = if (entry.error != null && !entry.stopped) colors.error else pal.onSurfaceVariant)
}
} ?: return
if (text.isEmpty()) return
Text(text, fontSize = 12.sp, color = if (entry.error != null && !entry.stopped) colors.error else pal.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 4.dp))
}
@Composable
@@ -166,11 +105,7 @@ private fun AgentNoReply() {
}
}
internal fun tokens(n: Long) = when {
n >= 1_000_000 -> if (n % 1_000_000 == 0L) "${n / 1_000_000}M" else String.format(java.util.Locale.US, "%.1fM", n / 1_000_000.0)
n >= 1000 -> "${n / 1000}k"
else -> n.toString()
}
internal fun tokens(n: Long) = if (n >= 1000) "${n / 1000}k" else n.toString()
@Composable
internal fun AgentThought(text: String, live: Boolean) {
@@ -214,13 +149,12 @@ private fun AgentTodos(list: String) {
}
}
/** A tool call: one line with its status, opening to the full input and output, or to the diff of an edit. */
/** A tool call: one line with its status, opening to the full input and output. */
@Composable
private fun AgentToolCall(entry: Entry.Used, running: Boolean) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var open by rememberSaveable(entry.id.ifEmpty { entry.detail }) { mutableStateOf(false) }
val diff = remember(entry.input) { diffOf(entry) }
Column(
Modifier.fillMaxWidth().padding(horizontal = 4.dp).clip(Shape12).background(pal.surfaceVariant).animateContentSize(),
) {
@@ -237,19 +171,11 @@ private fun AgentToolCall(entry: Entry.Used, running: Boolean) {
}
}
Text(entry.tool, fontSize = 12.5.sp, fontWeight = FontWeight.SemiBold, color = pal.primary, modifier = Modifier.padding(start = 8.dp))
Text(diff?.path?.substringAfterLast('/') ?: entry.detail, fontSize = 12.5.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant,
Text(entry.detail, fontSize = 12.5.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f).padding(start = 8.dp))
if (diff != null) {
Text("+${diff.added}", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.good, modifier = Modifier.padding(start = 8.dp))
Text("\u2212${diff.removed}", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.error, modifier = Modifier.padding(start = 6.dp, end = 4.dp))
}
Icon(if (open) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(18.dp))
}
if (open && diff != null) Column(Modifier.padding(start = 10.dp, end = 10.dp, bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
if (diff.path.contains('/')) Text(diff.path, fontSize = 11.5.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
DiffBox(diff)
if (entry.failed && !entry.output.isNullOrBlank()) CodeBox(stringResource(R.string.agent_tool_output), entry.output, colors.error)
} else if (open) Column(Modifier.padding(start = 10.dp, end = 10.dp, bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
if (open) Column(Modifier.padding(start = 10.dp, end = 10.dp, bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
if (entry.input.isNotBlank()) CodeBox(stringResource(R.string.agent_tool_input), entry.input, colors.onSurface)
when {
entry.output == null && running -> Text(stringResource(R.string.agent_tool_running), fontSize = 12.sp, color = pal.onSurfaceVariant)
@@ -261,30 +187,6 @@ private fun AgentToolCall(entry: Entry.Used, running: Boolean) {
}
}
@Composable
private fun DiffBox(diff: Diff) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(
Modifier.fillMaxWidth().heightIn(max = 360.dp).clip(Shape12).background(colors.surface)
.verticalScroll(rememberScrollState()).padding(vertical = 6.dp),
) {
for (line in diff.lines) {
val tint = when (line[0]) {
'+' -> pal.good
'-' -> colors.error
else -> null
}
Text(
line[0] + " " + line.substring(1),
fontSize = 12.sp, fontFamily = FontFamily.Monospace, lineHeight = 17.sp,
color = tint ?: pal.onSurfaceVariant,
modifier = Modifier.fillMaxWidth().background(tint?.copy(alpha = 0.12f) ?: Color.Transparent).padding(horizontal = 10.dp),
)
}
}
}
@Composable
private fun CodeBox(label: String, text: String, color: Color) {
val pal = LocalPalette.current
@@ -325,3 +227,81 @@ internal fun AttachmentChip(path: String, onRemove: (() -> Unit)?) {
}
}
}
/** The Markdown agents write: headings, lists, fenced code, `code` and **bold**. */
@Composable
internal fun AgentMarkdown(text: String, modifier: Modifier) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(modifier, verticalArrangement = Arrangement.spacedBy(6.dp)) {
for (block in markdownBlocks(text)) when (block) {
is MdBlock.Code -> Text(block.text, fontSize = 13.sp, fontFamily = FontFamily.Monospace, color = colors.onSurface,
modifier = Modifier.fillMaxWidth().clip(Shape12).background(pal.surfaceVariant).padding(12.dp))
is MdBlock.Line -> Text(
inlineMarkdown(block.text, pal.primary2, pal.surfaceVariant),
fontSize = if (block.heading) 17.sp else 15.sp,
fontWeight = if (block.heading) FontWeight.Bold else null,
lineHeight = 22.sp, color = colors.onSurface,
modifier = if (block.bullet) Modifier.padding(start = 12.dp) else Modifier,
)
}
}
}
internal sealed interface MdBlock {
data class Line(val text: String, val heading: Boolean = false, val bullet: Boolean = false) : MdBlock
data class Code(val text: String) : MdBlock
}
private val HEADING = Regex("^#{1,6}\\s+")
private val BULLET = Regex("^\\s*[-*+]\\s+")
internal fun markdownBlocks(text: String): List<MdBlock> {
val out = mutableListOf<MdBlock>()
val code = StringBuilder()
var inCode = false
for (raw in text.lines()) {
if (raw.trimStart().startsWith("```")) {
if (inCode) {
out += MdBlock.Code(code.toString().trimEnd('\n'))
code.clear()
}
inCode = !inCode
continue
}
if (inCode) {
code.append(raw).append('\n')
continue
}
val line = raw.trimEnd()
if (line.isBlank()) continue
val heading = HEADING.find(line)
val bullet = BULLET.find(line)
out += when {
heading != null -> MdBlock.Line(line.substring(heading.range.last + 1), heading = true)
bullet != null -> MdBlock.Line("• " + line.substring(bullet.range.last + 1), bullet = true)
else -> MdBlock.Line(line)
}
}
if (inCode && code.isNotEmpty()) out += MdBlock.Code(code.toString().trimEnd('\n'))
return out
}
internal fun inlineMarkdown(text: String, codeColor: Color, codeBackground: Color): AnnotatedString = buildAnnotatedString {
var i = 0
while (i < text.length) {
val boldEnd = if (text.startsWith("**", i)) text.indexOf("**", i + 2) else -1
val tickEnd = if (text[i] == '`') text.indexOf('`', i + 1) else -1
when {
boldEnd > i + 2 -> {
withStyle(SpanStyle(fontWeight = FontWeight.Bold)) { append(text, i + 2, boldEnd) }
i = boldEnd + 2
}
tickEnd > i + 1 -> {
withStyle(SpanStyle(fontFamily = FontFamily.Monospace, color = codeColor, background = codeBackground)) { append(text, i + 1, tickEnd) }
i = tickEnd + 1
}
else -> append(text[i++])
}
}
}
@@ -1,154 +0,0 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.text.Selection
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.widget.TextView
import android.widget.Toast
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import com.droiddeck.launcher.R
import io.noties.markwon.AbstractMarkwonPlugin
import io.noties.markwon.Markwon
import io.noties.markwon.MarkwonConfiguration
import io.noties.markwon.MarkwonVisitor
import io.noties.markwon.core.MarkwonTheme
import io.noties.markwon.ext.strikethrough.StrikethroughPlugin
import io.noties.markwon.ext.tables.TableAwareMovementMethod
import io.noties.markwon.ext.tables.TablePlugin
import io.noties.markwon.ext.tables.TableRowSpan
import io.noties.markwon.ext.tasklist.TaskListPlugin
import org.commonmark.ext.autolink.AutolinkExtension
import org.commonmark.parser.Parser
import org.commonmark.ext.gfm.tables.TableCell
import org.commonmark.ext.gfm.tables.TableHead
import org.commonmark.ext.gfm.tables.TableRow
import org.commonmark.node.AbstractVisitor
import org.commonmark.node.CustomNode
import org.commonmark.node.Node
@Composable
internal fun AgentMarkdown(text: String, modifier: Modifier) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val density = LocalDensity.current
val textSize = with(density) { 15.sp.toPx() }
val lineSpacing = with(density) { 3.sp.toPx() }
val renderer = remember(context, pal.primary2, pal.surfaceVariant, density) {
agentMarkdownRenderer(context, pal.primary2.toArgb(), pal.surfaceVariant.toArgb())
}
val rendered = remember(renderer, text) { renderer.toMarkdown(text) }
AndroidView(
modifier = modifier,
factory = { TextView(it).apply {
setTextIsSelectable(true)
movementMethod = TableAwareMovementMethod.create()
includeFontPadding = false
} },
update = { view ->
view.setTextColor(colors.onSurface.toArgb())
view.setLinkTextColor(pal.primary2.toArgb())
view.setTextSize(android.util.TypedValue.COMPLEX_UNIT_PX, textSize)
view.setLineSpacing(lineSpacing, 1f)
setAgentMarkdown(view, renderer, rendered)
},
)
}
internal fun agentMarkdownRenderer(context: Context, linkColor: Int, codeBackground: Int): Markwon =
Markwon.builder(context)
.usePlugin(StrikethroughPlugin.create())
.usePlugin(TablePlugin.create(context))
.usePlugin(TaskListPlugin.create(context))
.usePlugin(object : AbstractMarkwonPlugin() {
override fun configureParser(builder: Parser.Builder) {
builder.extensions(listOf(AutolinkExtension.create()))
}
override fun afterRender(node: Node, visitor: MarkwonVisitor) {
val rows = mutableListOf<String>()
node.accept(object : AbstractVisitor() {
override fun visit(customNode: CustomNode) {
if (customNode is TableHead || customNode is TableRow) {
val cells = generateSequence(customNode.firstChild) { it.next }.filterIsInstance<TableCell>().toList()
if (cells.isNotEmpty()) rows += cells.joinToString(" | ") { markdownCellText(it) }
else visitChildren(customNode)
} else visitChildren(customNode)
}
})
if (rows.isEmpty()) return
// Markwon keeps table cells outside the text buffer; expose them for copy and accessibility.
val builder = visitor.builder()
val text = SpannableStringBuilder(builder.removeFromEnd(0))
val spans = text.getSpans(0, text.length, TableRowSpan::class.java).sortedBy { text.getSpanStart(it) }
for ((row, span) in spans.withIndex().reversed()) {
val start = text.getSpanStart(span)
val end = text.getSpanEnd(span)
val content = rows[row].ifEmpty { "\u00a0" }
text.removeSpan(span)
text.replace(start, end, content)
text.setSpan(span, start, start + content.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
builder.append(text)
}
override fun configureTheme(builder: MarkwonTheme.Builder) {
builder.linkColor(linkColor).codeBackgroundColor(codeBackground)
}
override fun configureConfiguration(builder: MarkwonConfiguration.Builder) {
builder.linkResolver { view, link ->
val intent = agentBrowserIntent(link) ?: return@linkResolver
try {
view.context.startActivity(intent)
} catch (_: android.content.ActivityNotFoundException) {
Toast.makeText(view.context, R.string.agent_browser_unavailable, Toast.LENGTH_SHORT).show()
}
}
}
})
.build()
private fun markdownCellText(node: Node): String = buildString {
node.accept(object : AbstractVisitor() {
override fun visit(text: org.commonmark.node.Text) { append(text.literal) }
override fun visit(code: org.commonmark.node.Code) { append(code.literal) }
override fun visit(lineBreak: org.commonmark.node.SoftLineBreak) { append(' ') }
override fun visit(lineBreak: org.commonmark.node.HardLineBreak) { append('\n') }
override fun visit(html: org.commonmark.node.HtmlInline) { append(html.literal) }
})
}
internal fun setAgentMarkdown(view: TextView, renderer: Markwon, rendered: Spanned) {
if (view.tag === rendered) return
val start = view.selectionStart
val end = view.selectionEnd
val sameText = view.text.toString() == rendered.toString()
renderer.setParsedMarkdown(view, rendered)
view.tag = rendered
if (sameText && start in 0..rendered.length && end in 0..rendered.length) {
(view.text as? Spannable)?.let { Selection.setSelection(it, start, end) }
}
}
internal fun agentBrowserIntent(link: String): Intent? {
val uri = Uri.parse(link)
if (uri.scheme?.lowercase() !in listOf("http", "https") || uri.host.isNullOrBlank()) return null
return Intent(Intent.ACTION_VIEW, uri).apply {
addCategory(Intent.CATEGORY_BROWSABLE)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
selector = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_BROWSER)
}
}
@@ -1,38 +1,24 @@
package com.droiddeck.launcher.ui
import android.app.Activity
import android.content.ContextWrapper
import android.view.KeyEvent
import android.view.WindowManager
import androidx.activity.compose.LocalActivityResultRegistryOwner
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
@@ -42,16 +28,12 @@ import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Send
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.ArrowDownward
import androidx.compose.material.icons.outlined.AttachFile
import androidx.compose.material.icons.outlined.AutoAwesome
import androidx.compose.material.icons.outlined.Build
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.material.icons.outlined.History
import androidx.compose.material.icons.outlined.Memory
import androidx.compose.material.icons.outlined.MoreHoriz
import androidx.compose.material.icons.outlined.Pets
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.Stop
import androidx.compose.material3.CircularProgressIndicator
@@ -60,41 +42,21 @@ import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.Stable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
@@ -103,52 +65,25 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogWindowProvider
import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentAttachments
import com.droiddeck.launcher.agent.AgentHost
import com.droiddeck.launcher.agent.AgentHost.Entry
import com.droiddeck.launcher.agent.AgentSetup
import kotlinx.coroutines.launch
internal enum class AgentPanel { NONE, MODEL, USAGE, HISTORY, PROCESSES }
internal enum class AgentPanel { NONE, MODEL, HISTORY, PROCESSES }
/** Slash commands the app handles itself; others go to the CLI, which has its own. */
private val LOCAL_COMMANDS = listOf("/new", "/model", "/plan", "/history", "/processes", "/stop")
private val CLI_COMMANDS = listOf("/compact", "/cost", "/review", "/init")
private const val COMPOSER_SLIDE_MS = 350L
/**
* The chat with the composer at the bottom. The composer is the full editor only while it is
* being typed in; reading shrinks it to one line, and scrolling back through older messages
* hides it behind a small pill. [startTyping] opens an empty conversation ready to type.
*/
@Composable
internal fun AgentPage(
modifier: Modifier, inputModifier: Modifier = Modifier, visible: Boolean = true, startTyping: Boolean = true, hidesPet: Boolean = true,
) {
internal fun AgentPage(modifier: Modifier, inputModifier: Modifier = Modifier, visible: Boolean = true) {
val context = LocalContext.current
val view = LocalView.current
DisposableEffect(view, visible) {
val window = (view.parent as? DialogWindowProvider)?.window
?: generateSequence(view.context) { (it as? ContextWrapper)?.baseContext }
.filterIsInstance<Activity>().firstOrNull()?.window
val previousMode = window?.attributes?.softInputMode
if (visible) window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
onDispose {
if (visible && previousMode != null) window?.setSoftInputMode(previousMode)
}
}
remember { AgentHost.refresh(context) }
LaunchedEffect(AgentHost.unseen, visible) { if (visible) AgentHost.seen() }
DisposableEffect(visible, hidesPet) {
val counts = visible && hidesPet
if (counts) AgentPet.agentOnScreen++
onDispose { if (counts) AgentPet.agentOnScreen-- }
}
remember { AgentSetup.check(context) }
var setup by rememberSaveable { mutableStateOf(false) }
val draft = rememberSaveable { mutableStateOf("") }
@@ -157,115 +92,56 @@ internal fun AgentPage(
return
}
var panel by rememberSaveable { mutableStateOf(AgentPanel.NONE) }
val composer = remember { ComposerState(startTyping && AgentHost.entries.isEmpty()) }
val focusManager = LocalFocusManager.current
val togglePanel: (AgentPanel) -> Unit = { panel = if (panel == it) AgentPanel.NONE else it }
// The keyboard leaves too little height for a panel and the editor together, so typing closes the panel.
val keyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0
LaunchedEffect(keyboardOpen) { if (keyboardOpen && (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE)) panel = AgentPanel.NONE }
Column(
modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e ->
val k = e.nativeKeyEvent
if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y || composer.typing) return@onPreviewKeyEvent false
if (k.action == KeyEvent.ACTION_UP) composer.open()
true
},
) {
Column(modifier.fillMaxSize()) {
AgentHeader(panel, { panel = if (panel == it) AgentPanel.NONE else it }, onSetup = { setup = true })
when (panel) {
AgentPanel.HISTORY -> {
AgentPanelBar(stringResource(R.string.agent_history)) { panel = AgentPanel.NONE }
AgentHistory(Modifier.weight(1f)) { panel = AgentPanel.NONE }
}
AgentPanel.PROCESSES -> {
AgentPanelBar(stringResource(R.string.agent_processes)) { panel = AgentPanel.NONE }
AgentProcessList(Modifier.weight(1f))
}
AgentPanel.HISTORY -> AgentHistory(Modifier.weight(1f)) { panel = AgentPanel.NONE }
AgentPanel.PROCESSES -> AgentProcessList(Modifier.weight(1f))
else -> {
val list = rememberLazyListState()
val scope = rememberCoroutineScope()
// Only dragging back through older messages hides the composer; showing it again shrinks the list, which must not hide it once more.
var readingBack by remember { mutableStateOf(false) }
LaunchedEffect(list) { snapshotFlow { list.canScrollForward }.collect { if (!it) readingBack = false } }
val dragBack = remember {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
if (source == NestedScrollSource.Drag && available.y > 1f && list.canScrollBackward) readingBack = true
return Offset.Zero
}
}
}
val toLatest: () -> Unit = {
readingBack = false
scope.launch { list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2) }
}
val hidden = !composer.typing && readingBack && AgentHost.entries.isNotEmpty()
var wasHidden by remember { mutableStateOf(false) }
LaunchedEffect(hidden) {
if (hidden) wasHidden = true
else if (wasHidden) {
wasHidden = false
// The composer takes its height back as it slides in; the latest message stays above it.
kotlinx.coroutines.delay(COMPOSER_SLIDE_MS)
list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2)
}
}
Box(Modifier.weight(1f).fillMaxWidth().clipToBounds().nestedScroll(dragBack)) {
AgentConversation(
Modifier.fillMaxSize().pointerInput(Unit) {
awaitEachGesture {
awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
if (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE) panel = AgentPanel.NONE
if (composer.typing) focusManager.clearFocus()
}
},
list, onRevise = { composer.open() },
)
androidx.compose.animation.AnimatedVisibility(
hidden, enter = fadeIn(), exit = fadeOut(), modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 8.dp),
) {
AgentJumpPill(toLatest)
}
}
androidx.compose.animation.AnimatedVisibility(!hidden, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
AgentComposer(composer, draft, inputModifier, panel, togglePanel) { setup = true }
}
if (panel == AgentPanel.MODEL) AgentModelPicker()
AgentConversation(Modifier.weight(1f))
AgentStatus()
AgentComposer(draft, inputModifier) { panel = it }
}
}
}
}
/** Whether the composer is the full editor; [open] also puts the cursor in it. */
@Stable
private class ComposerState(typing: Boolean) {
var typing by mutableStateOf(typing)
var focusRequests by mutableIntStateOf(0)
private set
/** Opened and waiting for the text field to take focus; focus passes through nothing on the way. */
var opening = false
fun open() {
typing = true
opening = true
focusRequests++
@Composable
private fun AgentHeader(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, onSetup: () -> Unit) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val working = AgentHost.state == AgentHost.State.WORKING
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.rail_agent), fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
val model = AgentHost.models(context).firstOrNull { it.id == AgentHost.model }?.label ?: AgentHost.model ?: stringResource(R.string.agent_model_default)
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.clip(Shape12).clickable { onPanel(AgentPanel.MODEL) }.padding(vertical = 2.dp).testTag("agent-model"),
) {
val parts = listOfNotNull(AgentHost.harness.name, model, stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans })
Text(parts.joinToString(" · "), fontSize = 13.sp, color = if (panel == AgentPanel.MODEL) pal.primary else pal.onSurfaceVariant)
Icon(Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
}
HeaderAction(Icons.Outlined.History, stringResource(R.string.agent_history), selected = panel == AgentPanel.HISTORY, tag = "agent-history") { onPanel(AgentPanel.HISTORY) }
HeaderAction(Icons.Outlined.Memory, stringResource(R.string.agent_processes), selected = panel == AgentPanel.PROCESSES, tag = "agent-processes") { onPanel(AgentPanel.PROCESSES) }
HeaderAction(Icons.Outlined.Add, stringResource(R.string.agent_new), enabled = !working && AgentHost.entries.isNotEmpty(), tag = "agent-new") {
AgentHost.forget(context)
if (panel != AgentPanel.NONE) onPanel(panel)
}
HeaderAction(Icons.Outlined.Settings, stringResource(R.string.agent_setup_title), enabled = !working, tag = "agent-settings", onClick = onSetup)
}
}
@Composable
private fun AgentPanelBar(title: String, onClose: () -> Unit) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp)) {
Text(title, fontSize = 17.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.weight(1f))
HeaderAction(Icons.Outlined.Close, stringResource(R.string.agent_close), size = 36.dp, tag = "agent-panel-close", onClick = onClose)
}
}
@Composable
internal fun HeaderAction(
icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, size: Dp = 44.dp, onClick: () -> Unit,
) {
internal fun HeaderAction(icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, onClick: () -> Unit) {
val pal = LocalPalette.current
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(start = if (size < 44.dp) 4.dp else 8.dp).size(size).clip(Shape12)
modifier = Modifier.padding(start = 8.dp).size(44.dp).clip(Shape12)
.background(if (selected) pal.primary.copy(alpha = 0.2f) else pal.surfaceVariant)
.clickable(enabled = enabled, onClick = onClick)
.then(if (tag != null) Modifier.testTag(tag) else Modifier),
@@ -274,21 +150,18 @@ internal fun HeaderAction(
selected -> pal.primary
enabled -> pal.onBackground
else -> pal.onSurfaceVariant.copy(alpha = 0.5f)
}, modifier = Modifier.size(if (size < 44.dp) 19.dp else 22.dp))
}, modifier = Modifier.size(22.dp))
}
}
@Composable
private fun AgentConversation(modifier: Modifier, list: LazyListState, onRevise: () -> Unit) {
private fun AgentConversation(modifier: Modifier) {
val pal = LocalPalette.current
val list = rememberLazyListState()
val working = AgentHost.state == AgentHost.State.WORKING
val atBottom by remember { derivedStateOf { !list.canScrollForward } }
val items = AgentHost.entries.size + (if (working) 1 else 0)
LaunchedEffect(items) {
if (items == 0) return@LaunchedEffect
list.animateScrollToItem(items - 1)
list.scrollToItem(items - 1, Int.MAX_VALUE / 2)
}
LaunchedEffect(items) { if (items > 0) list.animateScrollToItem(items - 1) }
LaunchedEffect(AgentHost.live.length / 80, AgentHost.liveThinking.length / 80) {
if (atBottom && items > 0) list.scrollToItem(items - 1, Int.MAX_VALUE / 2)
}
@@ -304,31 +177,12 @@ private fun AgentConversation(modifier: Modifier, list: LazyListState, onRevise:
LazyColumn(modifier.fillMaxWidth(), state = list, verticalArrangement = Arrangement.spacedBy(10.dp)) {
items(AgentHost.entries.size) { i ->
val entry = AgentHost.entries[i]
AgentEntry(
entry, running = working && i > start && entry is Entry.Used && entry.output == null, last = !working && i == AgentHost.entries.lastIndex,
changes = if (entry is Entry.Finished) turnChanges(AgentHost.entries, i) else null, onRevise = onRevise,
)
AgentEntry(entry, running = working && i > start && entry is Entry.Used && entry.output == null, last = !working && i == AgentHost.entries.lastIndex)
}
if (working) item { AgentLive() }
}
}
/** Where the composer was, while it is hidden for reading back: what the agent is doing, and the way to the latest message. */
@Composable
private fun AgentJumpPill(onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.clip(CircleShape).background(colors.surface).border(1.dp, pal.line, CircleShape)
.clickable(onClick = onClick).padding(horizontal = 14.dp, vertical = 8.dp).testTag("agent-latest"),
) {
if (AgentHost.state == AgentHost.State.WORKING) CircularProgressIndicator(Modifier.size(13.dp), strokeWidth = 2.dp, color = pal.primary)
Text(stringResource(if (AgentHost.state == AgentHost.State.WORKING) R.string.agent_working_short else R.string.agent_latest), fontSize = 13.sp, color = pal.onSurfaceVariant)
Icon(Icons.Outlined.ArrowDownward, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
}
/** The reply being written, and what the agent is doing right now. */
@Composable
private fun AgentLive() {
@@ -357,41 +211,65 @@ internal fun clock(seconds: Long): String {
}
}
/** Above the composer: a Lab build's progress, the todo item in progress, and queued messages. */
@Composable
private fun AgentLabCard() {
private fun AgentStatus() {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val lab = AgentHost.lab ?: return
var armed by remember(lab.pid) { mutableStateOf(false) }
Column(
Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape14).background(colors.surface).border(1.dp, if (lab.failed) AttentionAmber else pal.line, Shape14)
.padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-lab"),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text(
stringResource(if (lab.prepare) R.string.agent_lab_preparing else R.string.agent_lab_building) + " · " + labStage(lab),
fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = if (lab.failed) AttentionAmber else colors.onBackground,
)
val facts = buildList {
if (lab.running && lab.total > 0) add("${lab.done}/${lab.total}")
add(clock(lab.elapsedSeconds.toLong()))
if (lab.running && lab.etaSeconds >= 0) add(stringResource(R.string.agent_lab_left, clock(lab.etaSeconds.toLong())))
val lab = AgentHost.lab
if (lab != null) {
var armed by remember(lab.pid) { mutableStateOf(false) }
Column(
Modifier.fillMaxWidth().padding(top = 10.dp).clip(Shape14).background(colors.surface).border(1.dp, if (lab.failed) AttentionAmber else pal.line, Shape14)
.padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-lab"),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text(
stringResource(if (lab.prepare) R.string.agent_lab_preparing else R.string.agent_lab_building) + " · " + labStage(lab),
fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = if (lab.failed) AttentionAmber else colors.onBackground,
)
val facts = buildList {
if (lab.running && lab.total > 0) add("${lab.done}/${lab.total}")
add(clock(lab.elapsedSeconds.toLong()))
if (lab.running && lab.etaSeconds >= 0) add(stringResource(R.string.agent_lab_left, clock(lab.etaSeconds.toLong())))
}
Text(facts.joinToString(" · "), fontSize = 12.5.sp, color = pal.onSurfaceVariant)
}
if (lab.running) SecondaryButton(stringResource(if (armed) R.string.agent_lab_cancel_confirm else R.string.agent_lab_cancel), compact = true) {
if (armed) AgentHost.cancelLabBuild(context) else armed = true
}
Text(facts.joinToString(" · "), fontSize = 12.5.sp, color = pal.onSurfaceVariant)
}
if (lab.running) SecondaryButton(stringResource(if (armed) R.string.agent_lab_cancel_confirm else R.string.agent_lab_cancel), compact = true) {
if (armed) AgentHost.cancelLabBuild(context) else armed = true
if (lab.running) {
LinearProgressIndicator(
progress = { lab.permille / 1000f }, color = pal.primary, trackColor = pal.surfaceVariant,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(6.dp).clip(CircleShape),
)
if (lab.task.isNotEmpty()) Text(lab.task, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 4.dp))
}
}
if (lab.running) {
LinearProgressIndicator(
progress = { lab.permille / 1000f }, color = pal.primary, trackColor = pal.surfaceVariant,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(6.dp).clip(CircleShape),
)
if (lab.task.isNotEmpty()) Text(lab.task, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 4.dp))
}
val todos = AgentHost.todos()?.lines()?.filter { it.isNotBlank() }
if (AgentHost.state == AgentHost.State.WORKING && !todos.isNullOrEmpty()) {
val doing = todos.firstOrNull { it.startsWith("[~]") } ?: todos.firstOrNull { it.startsWith("[ ]") }
val done = todos.count { it.startsWith("[x]") }
if (doing != null) Text(
"${doing.drop(4)} · $done/${todos.size}", fontSize = 13.sp, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 8.dp, start = 4.dp),
)
}
for (queued in AgentHost.queue) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().clip(Shape12).background(pal.surfaceVariant).padding(start = 12.dp),
) {
Text(stringResource(R.string.agent_queued, queued.text), fontSize = 13.sp, color = pal.onSurfaceVariant, maxLines = 1,
overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(40.dp).clickable { AgentHost.unqueue(queued) }) {
Icon(Icons.Outlined.Close, stringResource(R.string.agent_unqueue), tint = pal.onSurfaceVariant, modifier = Modifier.size(18.dp))
}
}
}
}
@@ -406,99 +284,13 @@ private fun labStage(lab: com.droiddeck.launcher.agent.LabProgress) = when (lab.
else -> stringResource(R.string.agent_lab_stage_starting)
}
private fun hasActivity() = AgentHost.lab != null || AgentHost.queue.isNotEmpty() || currentTodo() != null
/** The todo item in progress and how many are done, while the agent works through a list. */
private fun currentTodo(): String? {
if (AgentHost.state != AgentHost.State.WORKING) return null
val todos = AgentHost.todos()?.lines()?.filter { it.isNotBlank() }.orEmpty()
val doing = todos.firstOrNull { it.startsWith("[~]") } ?: todos.firstOrNull { it.startsWith("[ ]") } ?: return null
return "${todos.count { it.startsWith("[x]") }}/${todos.size} · ${doing.drop(4)}"
}
/** A Lab build, the todo item in progress and queued messages, one chip each. */
@Composable
private fun AgentActivity(labOpen: Boolean, onLab: () -> Unit) {
private fun AgentComposer(draftState: MutableState<String>, inputModifier: Modifier, onPanel: (AgentPanel) -> Unit) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
AgentHost.lab?.let { lab ->
AgentChip(selected = labOpen, warn = lab.failed, tag = "agent-lab-chip", onClick = onLab) {
Icon(Icons.Outlined.Build, null, tint = if (lab.failed) AttentionAmber else pal.onSurfaceVariant, modifier = Modifier.size(14.dp))
Text(labStage(lab), fontSize = 12.5.sp, color = if (lab.failed) AttentionAmber else pal.onSurfaceVariant, maxLines = 1,
overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 160.dp))
}
}
currentTodo()?.let { todo ->
AgentChip {
Text(todo, fontSize = 12.5.sp, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 220.dp))
}
}
for (queued in AgentHost.queue) AgentChip(warn = true) {
Text(stringResource(R.string.agent_queued, queued.text), fontSize = 12.5.sp, color = AttentionAmber, maxLines = 1,
overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 180.dp))
Text(
stringResource(R.string.agent_send_now), fontSize = 12.5.sp, fontWeight = FontWeight.SemiBold, color = pal.onPrimary,
modifier = Modifier.clip(Shape12).background(pal.primary).clickable { AgentHost.sendNow(context, queued) }
.padding(horizontal = 8.dp, vertical = 3.dp).testTag("agent-send-now"),
)
Icon(Icons.Outlined.Close, stringResource(R.string.agent_unqueue), tint = pal.onSurfaceVariant,
modifier = Modifier.size(22.dp).clip(CircleShape).clickable { AgentHost.unqueue(queued) }.padding(3.dp))
}
}
@Composable
private fun AgentChip(selected: Boolean = false, warn: Boolean = false, tag: String? = null, onClick: (() -> Unit)? = null, content: @Composable () -> Unit) {
val pal = LocalPalette.current
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.height(30.dp).clip(Shape12)
.background(if (warn) AttentionAmber.copy(alpha = 0.14f) else if (selected) pal.primary.copy(alpha = 0.2f) else pal.surfaceVariant)
.then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier)
.then(if (tag != null) Modifier.testTag(tag) else Modifier)
.padding(horizontal = 9.dp),
) { content() }
}
/** How full the context is, or failing that the plan limit nearest its end; amber when little is left. */
@Composable
private fun ContextRing(tag: String, onClick: () -> Unit) {
val pal = LocalPalette.current
val percent = usagePercent() ?: return
val warn = percent >= 80
val tint = if (warn) AttentionAmber else pal.primary
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp),
modifier = Modifier.height(30.dp).clip(Shape12).clickable(onClick = onClick).padding(horizontal = 6.dp).testTag(tag),
) {
val track = pal.line
Canvas(Modifier.size(16.dp)) {
val stroke = Stroke(width = 2.5.dp.toPx(), cap = StrokeCap.Round)
drawArc(track, 0f, 360f, false, style = stroke)
drawArc(tint, -90f, 360f * percent / 100f, false, style = stroke)
}
Text("$percent%", fontSize = 12.5.sp, color = if (warn) AttentionAmber else pal.onSurfaceVariant)
}
}
/** The context's fill, unless a plan limit is nearly reached: that is the wall the user meets first. */
internal fun usagePercent(): Int? {
val limit = AgentHost.limits.maxOfOrNull { liveUsed(it) }
val context = if (AgentHost.window > 0 && AgentHost.context > 0) (AgentHost.context * 100 / AgentHost.window).toInt().coerceIn(0, 100) else null
return if (limit != null && (limit >= 90 || context == null)) maxOf(limit, context ?: 0) else context
}
/** A limit whose window has passed since it was reported is back to nothing used. */
internal fun liveUsed(limit: AgentHost.Limit) = if (limit.resetsAt > 0 && limit.resetsAt * 1000 < System.currentTimeMillis()) 0 else limit.usedPercent
@Composable
private fun AgentComposer(
composer: ComposerState, draftState: MutableState<String>, inputModifier: Modifier, panel: AgentPanel, onPanel: (AgentPanel) -> Unit, onSetup: () -> Unit,
) {
val context = LocalContext.current
var draft by draftState
var labOpen by rememberSaveable { mutableStateOf(false) }
if (AgentHost.lab == null) labOpen = false
var hadFocus by remember { mutableStateOf(false) }
val working = AgentHost.state == AgentHost.State.WORKING
val send = send@{
val text = draft.trim()
when (text.substringBefore(' ')) {
@@ -516,84 +308,11 @@ private fun AgentComposer(
}
draft = ""
}
val keyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0
// Leaving the composer for the conversation, by touch or D-pad, is reading.
Column(
Modifier.fillMaxWidth().padding(bottom = if (keyboardOpen) 4.dp else 8.dp).onFocusChanged {
if (it.hasFocus) hadFocus = true
else if (hadFocus) {
hadFocus = false
if (composer.typing && !composer.opening) composer.typing = false
}
},
) {
if (labOpen) AgentLabCard()
when (panel) {
AgentPanel.MODEL -> Box(Modifier.padding(top = 8.dp)) { AgentModelPicker() }
AgentPanel.USAGE -> Box(Modifier.padding(top = 8.dp)) { AgentUsage() }
else -> Unit
}
if (composer.typing) {
if (hasActivity()) Row(
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
) { AgentActivity(labOpen) { labOpen = !labOpen } }
AgentEditor(composer, draftState, inputModifier, panel, onPanel, onSetup, send)
} else AgentReadingBar(composer, draft, inputModifier, labOpen, onLab = { labOpen = !labOpen }) { onPanel(AgentPanel.USAGE) }
}
}
/** The composer while reading: one line holding what is going on, opened by a press or by Y. */
@Composable
private fun AgentReadingBar(
composer: ComposerState, draft: String, inputModifier: Modifier, labOpen: Boolean, onLab: () -> Unit, onUsage: () -> Unit,
) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val working = AgentHost.state == AgentHost.State.WORKING
var focused by remember { mutableStateOf(false) }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(44.dp).clip(Shape16).background(colors.surface)
.border(if (focused) 2.dp else 1.dp, if (focused) pal.primary else pal.line, Shape16)
.then(inputModifier).onFocusChanged { focused = it.isFocused }.clickable { composer.open() }.testTag("agent-composer-bar")
.padding(start = 14.dp, end = 4.dp),
) {
Text(
draft.ifBlank { stringResource(if (working) R.string.agent_hint_working else R.string.agent_message) }, fontSize = 15.sp,
color = if (draft.isBlank()) pal.onSurfaceVariant else colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = !hasActivity()).widthIn(min = 72.dp),
)
if (hasActivity()) Row(
horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f).padding(start = 8.dp).horizontalScroll(rememberScrollState()),
) { AgentActivity(labOpen, onLab) }
ContextRing("agent-usage-bar", onUsage)
if (working) Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(start = 4.dp).size(36.dp).clip(CircleShape).background(pal.error.copy(alpha = 0.22f))
.clickable { AgentHost.stop(context) }.testTag("agent-stop"),
) { Icon(Icons.Outlined.Stop, stringResource(R.string.agent_stop), tint = colors.error, modifier = Modifier.size(20.dp)) }
}
}
/** The full editor: model and usage on top, the text with attach, stop and send under them. */
@Composable
private fun AgentEditor(
composer: ComposerState, draftState: MutableState<String>, inputModifier: Modifier, panel: AgentPanel, onPanel: (AgentPanel) -> Unit,
onSetup: () -> Unit, send: () -> Unit,
) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var draft by draftState
val working = AgentHost.state == AgentHost.State.WORKING
if (draft.startsWith("/") && !draft.contains(' ')) {
val matches = (LOCAL_COMMANDS + CLI_COMMANDS).filter { it.startsWith(draft) && it != draft }
if (matches.isNotEmpty()) Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
modifier = Modifier.padding(top = 10.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
) {
for (command in matches) Text(
command, fontSize = 13.sp, fontFamily = FontFamily.Monospace, color = pal.primary,
@@ -603,80 +322,40 @@ private fun AgentEditor(
}
if (AgentAttachments.pending.isNotEmpty()) Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
modifier = Modifier.padding(top = 10.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
) {
for (path in AgentAttachments.pending.toList()) AttachmentChip(path) { AgentAttachments.pending.remove(path) }
}
var focused by remember { mutableStateOf(false) }
var menu by rememberSaveable { mutableStateOf(false) }
val field = remember { FocusRequester() }
LaunchedEffect(composer.focusRequests) { if (composer.focusRequests > 0) runCatching { field.requestFocus() } }
Column(
Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape16).background(colors.surface)
.border(1.dp, if (focused) pal.primary else pal.line, Shape16).padding(6.dp),
Row(
verticalAlignment = Alignment.Bottom,
modifier = Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 16.dp).clip(Shape16).background(colors.surface)
.border(1.dp, if (focused) pal.primary else pal.line, Shape16).padding(start = 6.dp, end = 6.dp, top = 6.dp, bottom = 6.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().height(36.dp)) {
val model = AgentHost.models(context).firstOrNull { it.id == AgentHost.model }?.label ?: AgentHost.model ?: stringResource(R.string.agent_model_default)
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f, fill = false).height(30.dp).clip(Shape12).clickable { onPanel(AgentPanel.MODEL) }
.padding(horizontal = 8.dp).testTag("agent-model"),
) {
val parts = listOfNotNull(AgentHost.harness.name, model, AgentHost.effort, stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans })
Text(parts.joinToString(" · "), fontSize = 13.sp, color = if (panel == AgentPanel.MODEL) pal.primary else pal.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
Icon(Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
ContextRing("agent-usage", onClick = { onPanel(AgentPanel.USAGE) })
}
if (menu) {
HeaderAction(Icons.Outlined.History, stringResource(R.string.agent_history), size = 32.dp, tag = "agent-history") { menu = false; onPanel(AgentPanel.HISTORY) }
HeaderAction(Icons.Outlined.Memory, stringResource(R.string.agent_processes), size = 32.dp, tag = "agent-processes") { menu = false; onPanel(AgentPanel.PROCESSES) }
HeaderAction(Icons.Outlined.Add, stringResource(R.string.agent_new), enabled = !working && AgentHost.entries.isNotEmpty(), size = 32.dp, tag = "agent-new") {
menu = false
AgentHost.forget(context)
}
HeaderAction(Icons.Outlined.Pets, stringResource(R.string.setup_agent_pet), selected = AgentPet.enabled, size = 32.dp, tag = "agent-pet-toggle") {
AgentPet.set(context, !AgentPet.enabled)
}
HeaderAction(Icons.Outlined.Settings, stringResource(R.string.agent_setup_title), enabled = !working, size = 32.dp, tag = "agent-settings") {
menu = false
onSetup()
}
}
HeaderAction(if (menu) Icons.Outlined.Close else Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), size = 32.dp, tag = "agent-menu") { menu = !menu }
if (LocalActivityResultRegistryOwner.current != null) AttachButton()
Box(Modifier.weight(1f).padding(start = 8.dp, top = 11.dp, bottom = 11.dp)) {
if (draft.isEmpty()) Text(
stringResource(if (working) R.string.agent_hint_working else R.string.agent_hint), fontSize = 16.sp,
color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
BasicTextField(
draft, { draft = it },
Modifier.fillMaxWidth().onFocusChanged { focused = it.isFocused }.testTag("agent-input").then(inputModifier),
textStyle = TextStyle(fontSize = 16.sp, color = colors.onSurface),
cursorBrush = SolidColor(pal.primary),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
keyboardActions = KeyboardActions(onSend = { send() }),
maxLines = 6,
)
}
Row(verticalAlignment = Alignment.Bottom) {
if (LocalActivityResultRegistryOwner.current != null) AttachButton()
Box(Modifier.weight(1f).padding(start = 8.dp, top = 10.dp, bottom = 10.dp)) {
if (draft.isEmpty()) Text(
stringResource(if (working) R.string.agent_hint_working else R.string.agent_hint), fontSize = 16.sp,
color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
BasicTextField(
draft, { draft = it },
Modifier.fillMaxWidth().focusRequester(field).onFocusChanged {
focused = it.isFocused
if (it.isFocused) composer.opening = false
}.testTag("agent-input").then(inputModifier),
textStyle = TextStyle(fontSize = 16.sp, color = colors.onSurface),
cursorBrush = SolidColor(pal.primary),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
keyboardActions = KeyboardActions(onSend = { send() }),
minLines = 1,
maxLines = 8,
)
}
if (working) RoundButton(Icons.Outlined.Stop, stringResource(R.string.agent_stop), pal.error.copy(alpha = 0.22f), colors.error, "agent-stop") {
AgentHost.stop(context)
}
val canSend = draft.isNotBlank() || AgentAttachments.pending.isNotEmpty()
RoundButton(
Icons.AutoMirrored.Outlined.Send, stringResource(if (working) R.string.agent_queue else R.string.agent_send),
if (canSend) pal.primary else pal.surfaceVariant, if (canSend) pal.onPrimary else pal.onSurfaceVariant, "agent-send", enabled = canSend,
) { send() }
if (working) RoundButton(Icons.Outlined.Stop, stringResource(R.string.agent_stop), pal.error.copy(alpha = 0.22f), colors.error, "agent-stop") {
AgentHost.stop(context)
}
val canSend = draft.isNotBlank() || AgentAttachments.pending.isNotEmpty()
RoundButton(
Icons.AutoMirrored.Outlined.Send, stringResource(if (working) R.string.agent_queue else R.string.agent_send),
if (canSend) pal.primary else pal.surfaceVariant, if (canSend) pal.onPrimary else pal.onSurfaceVariant, "agent-send", enabled = canSend,
) { send() }
}
}
@@ -706,9 +385,9 @@ private fun RoundButton(
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(start = 6.dp).size(42.dp).clip(CircleShape).background(background)
modifier = Modifier.padding(start = 6.dp).size(46.dp).clip(CircleShape).background(background)
.clickable(enabled = enabled, onClick = onClick).testTag(tag),
) {
Icon(icon, label, tint = tint, modifier = Modifier.size(21.dp))
Icon(icon, label, tint = tint, modifier = Modifier.size(22.dp))
}
}
@@ -14,12 +14,10 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
@@ -50,7 +48,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
/** The model, reasoning effort and plan mode for the next turns; a conversation keeps going with whatever is chosen. */
/** The model and plan mode for the next turns; a conversation keeps going with whatever is chosen. */
@Composable
internal fun AgentModelPicker() {
val context = LocalContext.current
@@ -65,16 +63,6 @@ internal fun AgentModelPicker() {
else SecondaryButton(choice.label, compact = true) { AgentHost.chooseModel(context, id) }
}
}
if (AgentHost.harness.efforts.isNotEmpty()) Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(stringResource(R.string.agent_effort), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.padding(horizontal = 2.dp))
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) {
for (level in listOf<String?>(null) + AgentHost.harness.efforts) {
val label = level ?: stringResource(R.string.agent_model_default)
if (level == AgentHost.effort) PrimaryButton(label, compact = true) {}
else SecondaryButton(label, compact = true) { AgentHost.chooseEffort(context, level) }
}
}
}
if (AgentHost.harness.plans) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp)) {
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.agent_plan), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
@@ -192,71 +180,3 @@ internal fun AgentProcessList(modifier: Modifier) {
}
}
}
/** How full the conversation's context is, how much of the plan's limits is used, and what this conversation cost. */
@Composable
internal fun AgentUsage() {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(
Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).padding(horizontal = 14.dp, vertical = 10.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
if (AgentHost.window > 0) UsageRow(
stringResource(R.string.agent_usage_context),
stringResource(R.string.agent_usage_of, tokens(AgentHost.context), tokens(AgentHost.window)),
(AgentHost.context.toFloat() / AgentHost.window).coerceIn(0f, 1f),
)
for (limit in AgentHost.limits) {
val used = liveUsed(limit)
val label = when {
limit.minutes in 9_000..11_000 -> stringResource(R.string.agent_limit_week)
limit.minutes >= 60 -> stringResource(R.string.agent_limit_hours, limit.minutes / 60)
else -> stringResource(R.string.agent_limit_minutes, limit.minutes)
}
val value = if (limit.resetsAt * 1000 > System.currentTimeMillis()) stringResource(R.string.agent_limit_resets, used, resetTime(context, limit.resetsAt)) else "$used%"
UsageRow(label, value, used / 100f)
}
val turns = AgentHost.entries.filterIsInstance<AgentHost.Entry.Finished>().mapNotNull { it.usage }
val cost = turns.sumOf { it.costUsd }
val ms = turns.sumOf { it.durationMs }
Row(verticalAlignment = Alignment.CenterVertically) {
val facts = buildList {
if (ms > 0) add(clock(ms / 1000))
if (cost >= 0.005) add("$" + String.format(java.util.Locale.US, "%.2f", cost))
}
Text(
if (facts.isEmpty()) stringResource(R.string.agent_usage_unknown) else stringResource(R.string.agent_usage_conversation, facts.joinToString(" · ")),
fontSize = 12.5.sp, color = pal.onSurfaceVariant, modifier = Modifier.weight(1f),
)
if (AgentHost.harness.plans && AgentHost.entries.isNotEmpty() && AgentHost.state == AgentHost.State.IDLE) {
SecondaryButton("/compact", compact = true) { AgentHost.send(context, "/compact") }
}
}
}
}
@Composable
private fun UsageRow(label: String, value: String, fraction: Float) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(label, fontSize = 14.sp, color = colors.onBackground, modifier = Modifier.weight(1f))
Text(value, fontSize = 12.5.sp, color = pal.onSurfaceVariant)
}
LinearProgressIndicator(
progress = { fraction }, color = if (fraction >= 0.8f) AttentionAmber else pal.primary, trackColor = pal.surfaceVariant,
modifier = Modifier.fillMaxWidth().height(5.dp).clip(CircleShape),
)
}
}
/** A reset later today shows its time; one further off shows the day too. */
private fun resetTime(context: android.content.Context, epochSeconds: Long): String {
val ms = epochSeconds * 1000
val flags = if (ms - System.currentTimeMillis() < 20 * 3_600_000L) DateUtils.FORMAT_SHOW_TIME
else DateUtils.FORMAT_SHOW_WEEKDAY or DateUtils.FORMAT_ABBREV_WEEKDAY or DateUtils.FORMAT_SHOW_TIME
return DateUtils.formatDateTime(context, ms, flags)
}
@@ -1,319 +0,0 @@
package com.droiddeck.launcher.ui
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.provider.Settings
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.onClick
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.agent.AgentHost
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
/** A DroidDeck window the pet can live in when it may not float over other apps. */
internal interface AgentPetHost {
/** Something already covers the pet's place, such as the session drawer. */
val petBlocked: Boolean
}
/**
* DeeDee, the agent's pet: shows what the agent is doing and opens a chat with it. With the
* "display over other apps" permission it floats over every app in windows of its own
* ([PetWindows]); without it, it lives in DroidDeck's own windows. Either way it opens the same
* chat, growing out of it.
*/
internal object AgentPet {
var enabled by mutableStateOf(false)
private set
/** May draw over other apps. */
var allowed by mutableStateOf(false)
private set
/** Agent pages on screen; the pet steps aside while the conversation itself is in view. */
var agentOnScreen by mutableIntStateOf(0)
var now by mutableLongStateOf(SystemClock.elapsedRealtime())
private set
/** When the agent last changed what it was doing. */
var since by mutableLongStateOf(SystemClock.elapsedRealtime())
private set
/** The floating windows could not be made, so the pet stays in DroidDeck's own windows instead. */
private var floatFailed by mutableStateOf(false)
val floating get() = enabled && allowed && !floatFailed
/** How to close the chat open inside each DroidDeck window that has one. */
private val closeInWindow = java.util.WeakHashMap<AgentPetHost, () -> Unit>()
/**
* B and Back close a chat open inside [host] before the window acts on them, since the window's
* own keys (leaving a session, going back a page) would otherwise run under it.
*/
fun handleBack(host: AgentPetHost, event: android.view.KeyEvent): Boolean {
val close = closeInWindow[host] ?: return false
if (event.keyCode != android.view.KeyEvent.KEYCODE_BACK && event.keyCode != android.view.KeyEvent.KEYCODE_BUTTON_B) return false
if (event.action == android.view.KeyEvent.ACTION_UP) close()
return true
}
internal fun chatOpenInWindow(host: AgentPetHost, close: (() -> Unit)?) {
if (close == null) closeInWindow.remove(host) else closeInWindow[host] = close
}
private var windows: PetWindows? = null
private val main = Handler(Looper.getMainLooper())
private const val TAG = "agent-pet"
private const val KEY = "pet"
private const val SIDE = "pet_side"
private const val HEIGHT = "pet_y"
fun set(context: Context, on: Boolean) {
enabled = on
AgentHost.prefs(context).edit().putBoolean(KEY, on).apply()
}
/** Opens the system page where the user lets DroidDeck draw over other apps. */
fun requestFloating(context: Context) {
val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:${context.packageName}"))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
runCatching { context.startActivity(intent) }
}
internal fun place(context: Context) = AgentHost.prefs(context).let { it.getBoolean(SIDE, true) to it.getFloat(HEIGHT, 0.3f) }
internal fun save(context: Context, right: Boolean, height: Float) {
AgentHost.prefs(context).edit().putBoolean(SIDE, right).putFloat(HEIGHT, height).apply()
}
fun install(app: Application) {
enabled = AgentHost.prefs(app).getBoolean(KEY, false)
allowed = PetWindows.allowed(app)
val scope = MainScope()
scope.launch {
snapshotFlow { Triple(AgentHost.state, AgentHost.entries.size, AgentHost.lab?.running) }.collect { since = SystemClock.elapsedRealtime() }
}
scope.launch {
snapshotFlow { floating && AgentHost.installed }.collect { show ->
if (show && windows == null) windows = runCatching { PetWindows(app) }.onFailure {
android.util.Log.w("AgentPet", "could not float the pet", it)
floatFailed = true
}.getOrNull()
if (!show) windows?.close()?.also { windows = null }
}
}
tick(app)
app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
override fun onActivityResumed(activity: Activity) {
allowed = PetWindows.allowed(activity)
attach(activity)
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit
override fun onActivityStarted(activity: Activity) = Unit
override fun onActivityPaused(activity: Activity) = Unit
override fun onActivityStopped(activity: Activity) = Unit
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
override fun onActivityDestroyed(activity: Activity) = Unit
})
}
private fun tick(app: Application) {
now = SystemClock.elapsedRealtime()
// The permission can be granted or taken back in Settings while DroidDeck is away.
if (enabled) allowed = PetWindows.allowed(app)
main.postDelayed({ tick(app) }, 1_000)
}
private fun attach(activity: Activity) {
val host = activity as? AgentPetHost ?: return
val decor = activity.window.decorView as? ViewGroup ?: return
if (decor.findViewWithTag<View>(TAG) != null) return
val layer = ComposeView(activity).apply {
tag = TAG
isFocusable = false
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
setContent { DroidDeckTheme(appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(activity)) { PetLayer(host) } }
}
decor.addView(layer, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
}
}
private const val SLEEP_AFTER_MS = 5 * 60_000L
private const val CHEER_MS = 10_000L
internal const val PREVIEW_MS = 6_000L
/** What the agent is up to, as the pet shows it; [since] is when the agent last changed what it was doing. */
internal fun petState(now: Long, since: Long): PetState {
if (AgentHost.state == AgentHost.State.WORKING || AgentHost.lab?.running == true) return PetState.WORKING
val last = AgentHost.entries.lastOrNull { it is AgentHost.Entry.Finished } as? AgentHost.Entry.Finished
if (AgentHost.unseen && last != null && !last.stopped) {
if (last.error != null) return PetState.ERROR
val said = (AgentHost.entries.lastOrNull { it is AgentHost.Entry.Said } as? AgentHost.Entry.Said)?.text?.trimEnd().orEmpty()
if (last.planned || said.endsWith("?")) return PetState.QUESTION
if (now - since < CHEER_MS) return PetState.DONE
}
return if (now - since > SLEEP_AFTER_MS) PetState.SLEEP else PetState.IDLE
}
internal fun petStateNow() = petState(AgentPet.now, AgentPet.since)
/** The line the preview bubble shows while the pet has news, or null when it has none. */
internal fun petBubbleText(): String? {
if (!AgentHost.unseen) return null
val state = petStateNow()
if (state != PetState.DONE && state != PetState.QUESTION && state != PetState.ERROR) return null
val last = AgentHost.entries.lastOrNull { it is AgentHost.Entry.Finished } as? AgentHost.Entry.Finished
last?.error?.let { return it }
val said = AgentHost.entries.lastOrNull { it is AgentHost.Entry.Said } as? AgentHost.Entry.Said ?: return null
return said.text.lineSequence().map { it.trim().trimStart('#', '*', '-', ' ') }.firstOrNull { it.isNotEmpty() }
}
/** DeeDee in [state], with a dot while a reply waits to be read. */
@Composable
internal fun PetFigure(state: PetState, modifier: Modifier) {
Box(modifier.testTag("agent-pet")) {
Box(Modifier.fillMaxSize().padding(4.dp).clip(CircleShape).background(Color(0xEB0E141B)).border(1.dp, Color(0x29FFFFFF), CircleShape))
DeeDee(state, Modifier.fillMaxSize().padding(6.dp))
if (AgentHost.unseen && (state == PetState.IDLE || state == PetState.SLEEP)) Box(
Modifier.align(Alignment.TopEnd).padding(8.dp).size(14.dp).clip(CircleShape).background(Color(0xFF1A9FFF)).border(2.dp, Color(0xFF0E141B), CircleShape),
)
}
}
@Composable
internal fun PetPreview(text: String, modifier: Modifier, onTap: () -> Unit) {
val shape = RoundedCornerShape(16.dp)
Text(
text, fontSize = 14.sp, color = Color.White, maxLines = 2, overflow = TextOverflow.Ellipsis,
modifier = modifier.widthIn(max = 260.dp).clip(shape).background(Color(0xF0171D25)).border(1.dp, Color(0x33FFFFFF), shape)
.pointerInput(Unit) { detectTapGestures { onTap() } }.padding(horizontal = 14.dp, vertical = 10.dp),
)
}
/** The pet inside one DroidDeck window, for when it may not float over other apps. */
@Composable
private fun PetLayer(host: AgentPetHost) {
var chatOpen by remember { mutableStateOf(false) }
var chatShown by remember { mutableStateOf(false) }
val shown = AgentPet.enabled && !AgentPet.floating && AgentHost.installed && (chatShown || AgentPet.agentOnScreen == 0) && !host.petBlocked
if (!shown) return
val context = LocalContext.current
val motion = remember { PetMotion(context) }
val density = LocalDensity.current
val openLabel = androidx.compose.ui.res.stringResource(com.droiddeck.launcher.R.string.agent_pet_open)
val openChat = {
motion.dock()
chatShown = true
chatOpen = true
}
val closeChat = {
chatOpen = false
motion.undock()
}
BoxWithConstraints(Modifier.fillMaxSize()) {
motion.fit(constraints.maxWidth.toFloat(), constraints.maxHeight.toFloat())
if (chatShown) PetChat(chatOpen, motion, closeChat) { chatShown = false }
androidx.compose.runtime.DisposableEffect(host, chatOpen) {
AgentPet.chatOpenInWindow(host, if (chatOpen) closeChat else null)
onDispose { AgentPet.chatOpenInWindow(host, null) }
}
var bubble by remember { mutableStateOf<String?>(null) }
val news = petBubbleText()
LaunchedEffect(news) {
bubble = news
if (news != null) {
delay(PREVIEW_MS)
bubble = null
}
}
if (motion.dragging) Box(Modifier.offset {
val (tx, ty) = motion.target
IntOffset((tx - motion.size / 2).roundToInt(), (ty - motion.size / 2).roundToInt())
}) { PetCloseTarget(motion.overTarget) }
val text = bubble
if (text != null && !motion.dragging) {
var size by remember { mutableStateOf(IntSize.Zero) }
val gap = with(density) { 10.dp.toPx() }
PetPreview(text, Modifier.onSizeChanged { size = it }.offset {
val x = if (motion.right) motion.x - gap - size.width else motion.x + motion.size + gap
IntOffset(x.roundToInt(), (motion.y + motion.size / 2 - size.height / 2).roundToInt())
}) {
bubble = null
openChat()
}
}
PetFigure(
petStateNow(),
Modifier.offset { IntOffset(motion.x.roundToInt(), motion.y.roundToInt()) }
.size(with(density) { motion.size.toDp() })
.semantics {
contentDescription = openLabel
role = androidx.compose.ui.semantics.Role.Button
onClick { if (chatOpen) closeChat() else openChat(); true }
}
.pointerInput(Unit) { detectTapGestures { bubble = null; if (chatOpen) closeChat() else openChat() } }
.pointerInput(Unit) {
// The pet moves under the finger, so its velocity is measured where it is on the screen.
val tracker = androidx.compose.ui.input.pointer.util.VelocityTracker()
detectDragGestures(
onDragStart = { bubble = null; if (chatOpen) closeChat(); tracker.resetTracking(); motion.start() },
onDrag = { change, amount ->
change.consume()
motion.move(amount.x, amount.y)
tracker.addPosition(change.uptimeMillis, androidx.compose.ui.geometry.Offset(motion.x + change.position.x, motion.y + change.position.y))
},
onDragEnd = {
val v = tracker.calculateVelocity()
if (motion.end(v.x, v.y)) AgentPet.set(context, false)
},
onDragCancel = { motion.cancel() },
)
},
)
}
}
@@ -1,559 +0,0 @@
package com.droiddeck.launcher.ui
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.PixelFormat
import android.os.Build
import android.provider.Settings
import android.view.Gravity
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.WindowManager
import android.view.animation.OvershootInterpolator
import android.widget.FrameLayout
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.animation.core.Animatable
import androidx.compose.foundation.Canvas
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.unit.IntOffset
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.setViewTreeLifecycleOwner
import androidx.savedstate.SavedStateRegistry
import androidx.savedstate.SavedStateRegistryController
import androidx.savedstate.SavedStateRegistryOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentHost
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlin.math.abs
import kotlin.math.hypot
import kotlin.math.roundToInt
/**
* Where the pet is on the screen and how it moves: dragged anywhere, then settling against the
* nearer side edge, or dropped on the close target to turn it off. While its chat is open it is
* docked at the top corner, the way a chat head hops up when its conversation opens, and goes home
* when the chat closes. Positions are screen pixels.
*/
internal class PetMotion(private val context: Context) {
var x by mutableFloatStateOf(0f)
private set
var y by mutableFloatStateOf(0f)
private set
var right by mutableStateOf(true)
private set
var dragging by mutableStateOf(false)
private set
var width by mutableFloatStateOf(0f)
private set
var height by mutableFloatStateOf(0f)
private set
/** Docked for the chat; where to go back to is kept as a side and a relative height. */
var docked by mutableStateOf(false)
private set
private val density = context.resources.displayMetrics.density
val size = 76 * density
private val margin = 6 * density
private val inset = 24 * density
private var settle: ValueAnimator? = null
private val spring = FlingSpring { sx, sy -> x = sx; y = sy }
val dockX get() = width - size - margin
private companion object {
/** The share of the pet that hangs past the edge it rests against. */
const val TUCK = 0.2f
}
val dockY get() = inset
val target get() = Pair(width / 2, height - 72 * density)
val overTarget get() = dragging && hypot(x + size / 2 - target.first, y + size / 2 - target.second) < size
/** Fits the pet into a [w] by [h] screen, keeping its side and relative height, as after a rotation. */
fun fit(w: Float, h: Float) {
if (w <= 0 || h <= 0 || (w == width && h == height)) return
val first = width == 0f
val fraction = if (first) AgentPet.place(context).also { right = it.first }.second else if (docked) home else fractionOf(y)
settle?.cancel()
spring.cancel()
width = w
height = h
home = fraction
if (docked) {
x = dockX
y = dockY
} else {
x = edge(right)
y = inset + travel() * fraction
}
}
private var home = 0f
private fun travel() = (height - size - inset * 2).coerceAtLeast(0f)
private fun fractionOf(at: Float) = if (travel() > 0) ((at - inset) / travel()).coerceIn(0f, 1f) else 0f
/** At rest the pet tucks part of itself past the screen edge, as a chat head does. */
private fun edge(side: Boolean) = if (side) width - size * (1f - TUCK) else -size * TUCK
/** Hops up to the top corner for the chat. */
fun dock() {
if (docked) return
home = fractionOf(y)
docked = true
glide(dockX, dockY, 260, OvershootInterpolator(0.9f))
}
/** Goes back to where it was before the chat opened. */
fun undock() {
if (!docked) return
docked = false
glide(edge(right), inset + travel() * home, 320, android.view.animation.DecelerateInterpolator(1.6f))
}
fun start() {
settle?.cancel()
spring.cancel()
docked = false
dragging = true
}
fun move(dx: Float, dy: Float) {
x += dx
y += dy
}
/** A drag the system took away: the pet goes back to an edge, never to the close target. */
fun cancel() {
if (!dragging) return
dragging = false
right = x + size / 2 > width / 2
val toY = y.coerceIn(inset, (height - size - inset).coerceAtLeast(inset))
home = fractionOf(toY)
spring.start(x, y, 0f, 0f, edge(right), toY)
}
/** Ends a drag let go at [vx], [vy] pixels per second; true when the pet was dropped on the close target. */
fun end(vx: Float = 0f, vy: Float = 0f): Boolean {
val dismissed = overTarget
dragging = false
if (dismissed) return true
right = EdgeFling.toRight(x + size / 2, width, vx, density)
val toY = EdgeFling.restY(y, vy, inset, height - size - inset)
home = fractionOf(toY)
AgentPet.save(context, right, home)
spring.start(x, y, vx, vy, edge(right), toY)
return false
}
private fun glide(toX: Float, toY: Float, ms: Long, curve: android.animation.TimeInterpolator) {
settle?.cancel()
spring.cancel()
val fromX = x
val fromY = y
settle = ValueAnimator.ofFloat(0f, 1f).apply {
duration = (ms * Motion.scale).toLong().coerceAtLeast(0)
interpolator = curve
addUpdateListener {
val f = it.animatedValue as Float
x = fromX + (toX - fromX) * f
y = fromY + (toY - fromY) * f
}
start()
}
}
}
/** Lets a ComposeView live in a window no activity owns. */
private class OverlayOwner : LifecycleOwner, SavedStateRegistryOwner {
private val registry = LifecycleRegistry(this)
private val saved = SavedStateRegistryController.create(this)
override val lifecycle: Lifecycle get() = registry
override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry
init {
saved.performRestore(null)
registry.currentState = Lifecycle.State.RESUMED
}
fun destroy() {
registry.currentState = Lifecycle.State.DESTROYED
}
}
/**
* The pet over every app, in windows of its own: the pet, its message preview, the close target
* while it is dragged, and the chat it opens. Needs the "display over other apps" permission.
*/
@SuppressLint("ClickableViewAccessibility")
internal class PetWindows(private val context: Context) {
private val windows = context.getSystemService(WindowManager::class.java)
private val owner = OverlayOwner()
private val motion = PetMotion(context)
private val scope = MainScope()
/** The chat is open, or opening; its window stays up until it has shrunk back into the pet. */
private var chatOpen by mutableStateOf(false)
private var bubble by mutableStateOf<String?>(null)
private var bubbleWidth by mutableFloatStateOf(0f)
private var bubbleHeight by mutableFloatStateOf(0f)
/** The windows are in the window manager, so moving one goes through it. */
private var added = false
private val turns = object : android.content.ComponentCallbacks {
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) = fitScreen()
@Deprecated("Deprecated in Java")
override fun onLowMemory() = Unit
}
// A window emptied to no size keeps showing its last frame, so each is hidden as a whole instead.
private val head = window(touchable = true, focusable = false) {
PetFigure(petStateNow(), Modifier.size(76.dp))
}
private val preview = window(touchable = true, focusable = false, onSize = { w, h -> bubbleWidth = w.toFloat(); bubbleHeight = h.toFloat() }) {
bubble?.let { PetPreview(it, Modifier.padding(2.dp)) { openChat() } }
}
private val target = window(touchable = false, focusable = false) {
PetCloseTarget(motion.overTarget)
}
private val chat: Window = window(touchable = true, focusable = true, full = true) {
PetChat(chatOpen, motion, ::closeChat) { showChat(false) }
}
init {
head.view.setOnTouchListener(DragTouch())
head.view.contentDescription = context.getString(R.string.agent_pet_open)
head.view.setOnClickListener { if (chatOpen) closeChat() else openChat() }
scope.launch { snapshotFlow { Triple(motion.x, motion.y, motion.right) }.collectLatest { place() } }
scope.launch { snapshotFlow { bubbleWidth to bubbleHeight }.collectLatest { place() } }
scope.launch { snapshotFlow { AgentPet.agentOnScreen == 0 }.collectLatest { setVisible(head, it) } }
scope.launch { snapshotFlow { motion.dragging }.collectLatest { setVisible(target, it) } }
scope.launch {
snapshotFlow { bubble != null && !chatOpen && !motion.dragging && AgentPet.agentOnScreen == 0 }.collectLatest { setVisible(preview, it) }
}
scope.launch {
snapshotFlow { petBubbleText() }.collectLatest { text ->
bubble = text
if (text != null) {
kotlinx.coroutines.delay(PREVIEW_MS)
bubble = null
}
}
}
fitScreen()
context.registerComponentCallbacks(turns)
place()
listOf(target, preview).forEach { setVisible(it, false) }
showChat(false)
listOf(chat, target, preview, head).forEach { windows.addView(it.view, it.params) }
added = true
}
private class Window(val view: FrameLayout, val params: WindowManager.LayoutParams, val touchable: Boolean)
private fun window(
touchable: Boolean, focusable: Boolean, full: Boolean = false, onSize: ((Int, Int) -> Unit)? = null, content: @Composable () -> Unit,
): Window {
val compose = ComposeView(context).apply {
setViewTreeLifecycleOwner(owner)
setViewTreeSavedStateRegistryOwner(owner)
setContent { DroidDeckTheme(appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(context)) { content() } }
}
val frame = object : FrameLayout(context) {
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (full && event.keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_UP && chatOpen) {
closeChat()
return true
}
return super.dispatchKeyEvent(event)
}
}.apply {
addView(compose)
setViewTreeLifecycleOwner(owner)
setViewTreeSavedStateRegistryOwner(owner)
}
val size = if (full) WindowManager.LayoutParams.MATCH_PARENT else WindowManager.LayoutParams.WRAP_CONTENT
val params = WindowManager.LayoutParams(
size, size, WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
(if (focusable) 0 else WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) or
(if (touchable) 0 else WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE) or
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
(if (full) 0 else WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS),
PixelFormat.TRANSLUCENT,
).apply {
gravity = Gravity.TOP or Gravity.START
if (full) softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
}
if (onSize != null) compose.addOnLayoutChangeListener { v, _, _, _, _, _, _, _, _ -> onSize(v.width, v.height) }
return Window(frame, params, touchable)
}
/** A hidden overlay window still owns its frame, which the system can stretch over the screen, so it also stops taking touches. */
private fun setVisible(window: Window, shown: Boolean) {
window.view.visibility = if (shown) View.VISIBLE else View.GONE
setTouchable(window, shown && window.touchable)
}
private fun setTouchable(window: Window, on: Boolean) {
val flags = if (on) window.params.flags and WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE.inv()
else window.params.flags or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
if (flags == window.params.flags) return
window.params.flags = flags
if (added) runCatching { windows.updateViewLayout(window.view, window.params) }
}
private fun place() {
val gap = 10 * context.resources.displayMetrics.density
update(head, motion.x, motion.y)
val bx = if (motion.right) motion.x - gap - bubbleWidth else motion.x + motion.size + gap
update(preview, bx, motion.y + motion.size / 2 - bubbleHeight / 2)
val (tx, ty) = motion.target
update(target, tx - motion.size / 2, ty - motion.size / 2)
}
private fun update(window: Window, x: Float, y: Float) {
if (window.params.x == x.roundToInt() && window.params.y == y.roundToInt()) return
window.params.x = x.roundToInt()
window.params.y = y.roundToInt()
if (added) runCatching { windows.updateViewLayout(window.view, window.params) }
}
private fun openChat() {
bubble = null
if (chatOpen) return
motion.dock()
showChat(true)
chatOpen = true
}
private fun closeChat() {
if (!chatOpen) return
chatOpen = false
motion.undock()
}
/**
* The chat window is always drawn; closed, it waits off the screen and takes neither touches nor
* keys, so opening it is a move and not a first layout.
*/
private fun showChat(on: Boolean) {
chat.params.x = if (on) 0 else OFFSCREEN
val quiet = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
chat.params.flags = if (on) chat.params.flags and quiet.inv() else chat.params.flags or quiet
if (added) runCatching { windows.updateViewLayout(chat.view, chat.params) }
}
/** The whole screen, the status and navigation bars included, since overlay windows can cover them. */
private fun fitScreen() {
val bounds = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) windows.maximumWindowMetrics.bounds
else android.graphics.Point().also { @Suppress("DEPRECATION") windows.defaultDisplay.getRealSize(it) }.let { android.graphics.Rect(0, 0, it.x, it.y) }
motion.fit(bounds.width().toFloat(), bounds.height().toFloat())
}
fun close() {
runCatching { context.unregisterComponentCallbacks(turns) }
scope.cancel()
listOf(head, preview, target, chat).forEach { runCatching { windows.removeView(it.view) } }
owner.destroy()
}
/** Drags and taps on the pet, in screen coordinates, since its window moves under the finger. */
private inner class DragTouch : View.OnTouchListener {
private val slop = ViewConfiguration.get(context).scaledTouchSlop
private var downX = 0f
private var downY = 0f
private var lastX = 0f
private var lastY = 0f
private var moved = false
private var tracker: android.view.VelocityTracker? = null
/** The window moves under the finger, so velocity is measured on the screen. */
private fun track(e: MotionEvent) {
val onScreen = MotionEvent.obtain(e).apply { setLocation(e.rawX, e.rawY) }
(tracker ?: android.view.VelocityTracker.obtain().also { tracker = it }).addMovement(onScreen)
onScreen.recycle()
}
private fun release(): Pair<Float, Float> {
val t = tracker ?: return 0f to 0f
t.computeCurrentVelocity(1000)
val v = t.xVelocity to t.yVelocity
t.recycle()
tracker = null
return v
}
override fun onTouch(v: View, e: MotionEvent): Boolean {
track(e)
when (e.actionMasked) {
MotionEvent.ACTION_DOWN -> {
downX = e.rawX; downY = e.rawY; lastX = e.rawX; lastY = e.rawY
moved = false
}
MotionEvent.ACTION_MOVE -> {
if (!moved && (abs(e.rawX - downX) > slop || abs(e.rawY - downY) > slop)) {
moved = true
bubble = null
closeChat()
motion.start()
}
if (moved) motion.move(e.rawX - lastX, e.rawY - lastY)
lastX = e.rawX; lastY = e.rawY
}
MotionEvent.ACTION_UP -> {
val (vx, vy) = release()
if (moved) {
if (motion.end(vx, vy)) AgentPet.set(context, false)
} else v.performClick()
}
MotionEvent.ACTION_CANCEL -> {
release()
if (moved) motion.cancel()
}
}
return true
}
}
companion object {
private const val OFFSCREEN = 10_000
fun allowed(context: Context) = Settings.canDrawOverlays(context)
}
}
/**
* The floating chat, opened the way a chat head opens its conversation: the pet hops into the top
* corner while the whole conversation scales up out of it and fades in, and closing shrinks it back
* into the pet as the pet glides home. In landscape it sits beside the docked pet, in portrait
* under it. Its contents are built while it is closed, so opening only animates.
*/
@Composable
internal fun PetChat(open: Boolean, motion: PetMotion, onClose: () -> Unit, onClosed: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val density = androidx.compose.ui.platform.LocalDensity.current
BoxWithConstraints(
Modifier.fillMaxSize().onPreviewKeyEvent { e ->
val k = e.nativeKeyEvent
if (k.keyCode != KeyEvent.KEYCODE_BUTTON_B || k.action != KeyEvent.ACTION_UP) return@onPreviewKeyEvent false
onClose()
true
},
) {
val w = constraints.maxWidth.toFloat()
val h = constraints.maxHeight.toFloat()
val margin = with(density) { 8.dp.toPx() }
val gap = with(density) { 6.dp.toPx() }
val wide = w > h
val panel = if (wide) {
val right = motion.dockX - gap
Rect((right - with(density) { 900.dp.toPx() }).coerceAtLeast(margin), motion.dockY, right, h - margin)
} else {
Rect(margin, motion.dockY + motion.size + gap, w - margin, h - margin)
}
val grow = remember { Animatable(0f) }
val fade = remember { Animatable(0f) }
LaunchedEffect(open) {
if (open) coroutineScope {
launch { grow.animateTo(1f, Motion.sp(0.82f, 520f)) }
launch { fade.animateTo(1f, Motion.tw(140)) }
} else if (fade.value > 0f) {
coroutineScope {
launch { grow.animateTo(0f, Motion.tw(170, easing = androidx.compose.animation.core.FastOutLinearInEasing)) }
launch { delay(Motion.ms(40).toLong()); fade.animateTo(0f, Motion.tw(130)) }
}
onClosed()
}
}
Box(
Modifier.fillMaxSize().graphicsLayer { alpha = fade.value }.background(Color(0x8C000000))
.clickable(remember { MutableInteractionSource() }, null, enabled = open) { onClose() },
)
Column(
Modifier.offset { IntOffset(panel.left.roundToInt(), panel.top.roundToInt()) }
.size(with(density) { panel.width.toDp() }, with(density) { panel.height.toDp() })
.graphicsLayer {
// Grows from where the pet is right now, so the two travel together while the pet hops to its corner.
transformOrigin = androidx.compose.ui.graphics.TransformOrigin(
((motion.x + motion.size / 2 - panel.left) / panel.width.coerceAtLeast(1f)).coerceIn(0f, 1f),
((motion.y + motion.size / 2 - panel.top) / panel.height.coerceAtLeast(1f)).coerceIn(0f, 1f),
)
val s = 0.12f + 0.88f * grow.value
scaleX = s
scaleY = s
alpha = fade.value
}
.clip(Shape16).background(colors.background).border(1.dp, pal.line, Shape16)
.clickable(remember { MutableInteractionSource() }, null, enabled = open) {}
.padding(start = 12.dp, end = 12.dp, top = 6.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(bottom = 2.dp)) {
Text(stringResource(R.string.agent_pet_name), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
modifier = Modifier.padding(start = 4.dp))
Spacer(Modifier.weight(1f))
HeaderAction(Icons.Outlined.Close, stringResource(R.string.agent_close), size = 34.dp, tag = "agent-pet-close", onClick = onClose)
}
AgentPage(Modifier.weight(1f).fillMaxWidth(), visible = open, startTyping = AgentHost.entries.isEmpty(), hidesPet = false)
}
}
}
@Composable
internal fun PetCloseTarget(over: Boolean) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(4.dp).size(if (over) 84.dp else 68.dp).clip(androidx.compose.foundation.shape.CircleShape)
.background(Color(0xCC0E141B))
.border(2.dp, if (over) Color(0xFFFF5A5F) else Color(0x66FFFFFF), androidx.compose.foundation.shape.CircleShape),
) { Icon(Icons.Outlined.Close, null, tint = Color.White, modifier = Modifier.size(30.dp)) }
}
@@ -22,7 +22,6 @@ import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
@@ -56,6 +55,8 @@ import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.FilterAlt
import androidx.compose.material.icons.filled.Sort
import androidx.compose.material.icons.filled.Widgets
@@ -74,7 +75,6 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
@@ -92,7 +92,6 @@ import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.platform.LocalContext
@@ -111,13 +110,10 @@ import androidx.compose.ui.zIndex
import com.droiddeck.launcher.HomeApp
import com.droiddeck.launcher.HomeFolders
import com.droiddeck.launcher.HomeHidden
import com.droiddeck.launcher.HomeIcons
import com.droiddeck.launcher.HomePins
import com.droiddeck.launcher.IconPack
import android.content.pm.ShortcutInfo
import android.graphics.Bitmap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.withContext
import com.droiddeck.launcher.HomeWidgets
import com.droiddeck.launcher.R
@@ -149,9 +145,6 @@ private sealed interface AppEntry : AppEntryKey {
}
}
/** The focus id of the tile an entry is shown as. */
private fun tileId(entry: AppEntry): String = "tile:" + if (entry is AppEntry.App) entry.app.key else entry.key
private fun indexLetter(label: String): String {
val c = label.trim().firstOrNull()?.uppercaseChar() ?: return "#"
return if (c in 'A'..'Z') c.toString() else if (c.isLetter()) c.toString() else "#"
@@ -238,48 +231,6 @@ internal object AppsView {
}
}
internal object AppsGrid {
const val SMALL = 44
const val MEDIUM = 52
const val LARGE = 64
private val ICON_SIZES = listOf(SMALL, MEDIUM, LARGE)
const val TIGHT = -12
const val NORMAL = 0
const val ROOMY = 16
private val SPACINGS = listOf(TIGHT, NORMAL, ROOMY)
var labels by mutableStateOf(true)
private set
var iconDp by mutableStateOf(MEDIUM)
private set
var spacing by mutableStateOf(NORMAL)
private set
private fun prefs(context: Context) = context.getSharedPreferences("home_launcher", Context.MODE_PRIVATE)
fun load(context: Context) {
val p = prefs(context)
labels = p.getBoolean("grid_labels", true)
iconDp = p.getInt("grid_icon", MEDIUM).takeIf { it in ICON_SIZES } ?: MEDIUM
spacing = p.getInt("grid_spacing", NORMAL).takeIf { it in SPACINGS } ?: NORMAL
}
fun setLabels(context: Context, value: Boolean) {
labels = value
prefs(context).edit().putBoolean("grid_labels", value).apply()
}
fun setIconDp(context: Context, value: Int) {
iconDp = value
prefs(context).edit().putInt("grid_icon", value).apply()
}
fun setSpacing(context: Context, value: Int) {
spacing = value
prefs(context).edit().putInt("grid_spacing", value).apply()
}
}
internal interface AppEntryKey {
val label: String
val installedAt: Long
@@ -288,9 +239,9 @@ internal interface AppEntryKey {
@OptIn(ExperimentalLayoutApi::class)
@Composable
internal fun AndroidAppsPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier, onLaunch: (HomeApp.LaunchableApp) -> Unit) {
internal fun AndroidAppsPage(s: FrontEndState, modifier: Modifier, onLaunch: (HomeApp.LaunchableApp) -> Unit) {
val ctx = LocalContext.current
remember { HomeFolders.load(ctx); HomeWidgets.load(ctx); HomeHidden.load(ctx); AppsView.load(ctx); AppsGrid.load(ctx); true }
remember { HomeFolders.load(ctx); HomeWidgets.load(ctx); HomeHidden.load(ctx); AppsView.load(ctx); true }
val colors = MaterialTheme.colorScheme
val narrow = LocalNarrowPane.current
val padH = if (narrow) 16.dp else 22.dp
@@ -298,10 +249,6 @@ internal fun AndroidAppsPage(s: FrontEndState, a: FrontEndActions, modifier: Mod
var openFolder by rememberSaveable { mutableStateOf<String?>(null) }
var renameOnOpen by rememberSaveable { mutableStateOf(false) }
var picking by rememberSaveable { mutableStateOf(false) }
var iconFor by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
LaunchedEffect(Unit) {
snapshotFlow { HomeIcons.overrides }.drop(1).collect { a.onAppIconsChanged() }
}
val folders = HomeFolders.folders
val byKey = remember(s.androidApps) { s.androidApps.associateBy { it.key } }
val byPkg = remember(s.androidApps) { s.androidApps.filterNot { it.work }.groupBy { it.packageName }.mapNotNull { (pkg, apps) -> apps.singleOrNull()?.let { pkg to it } }.toMap() }
@@ -347,7 +294,7 @@ internal fun AndroidAppsPage(s: FrontEndState, a: FrontEndActions, modifier: Mod
ModeHeader(
stringResource(R.string.content_android_apps), query, { query = it },
placeholder = stringResource(R.string.apps_search_hint),
clearSearchFocus = openFolder != null || picking || iconFor != null,
clearSearchFocus = openFolder != null || picking,
lead = {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(start = 2.dp, end = 4.dp)) {
Text(stringResource(R.string.content_android_apps), fontSize = if (narrow) 20.sp else 24.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
@@ -358,37 +305,16 @@ internal fun AndroidAppsPage(s: FrontEndState, a: FrontEndActions, modifier: Mod
) {
AppsFilterButton()
AppsSortButton()
AppsAppearanceButton(a)
HeaderIconButton(stringResource(R.string.apps_add_widget), Icons.Filled.Widgets, "add-widget") {
HomeWidgets.loadProviders(ctx)
picking = true
}
}
}
val front = LocalFrontFocus.current
val steer = rememberCoroutineScope()
// Down goes to the tile straight below. The grid's own search only sees the tiles laid out so far, so above a short or
// unseen last row it lands on a tile further left; above a gap in a short last row the row's last tile takes it.
Box(Modifier.weight(1f).fillMaxWidth().onPreviewKeyEvent { event ->
val k = event.nativeKeyEvent
if (k.keyCode != KeyEvent.KEYCODE_DPAD_DOWN || front == null) return@onPreviewKeyEvent false
val from = entries.indexOfFirst { tileId(it) == front.last }
val columns = (grid.layoutInfo.visibleItemsInfo.maxOfOrNull { it.column } ?: 0) + 1
if (from < 0 || from / columns == entries.lastIndex / columns) return@onPreviewKeyEvent false
if (k.action == KeyEvent.ACTION_DOWN) {
val id = tileId(entries[minOf(from + columns, entries.lastIndex)])
val shown = (front.attached[id] ?: 0) > 0
if (!shown || runCatching { front.items.getValue(id).requestFocus() }.isFailure) steer.launch {
// The row below is not laid out yet: bring it in, then take it.
if (!shown) grid.scrollBy((grid.layoutInfo.visibleItemsInfo.firstOrNull { it.index == from + leadItems }?.size?.height ?: 0).toFloat())
focusSoon { front.items.getValue(id) }
}
}
true
}) {
Box(Modifier.weight(1f).fillMaxWidth()) {
val scroller = q.isEmpty() && byName && entries.size > 16
LazyVerticalGrid(
columns = GridCells.Adaptive((if (narrow) 84 else 96).dp + AppsGrid.spacing.dp),
columns = GridCells.Adaptive(if (narrow) 84.dp else 96.dp),
state = grid,
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
@@ -419,7 +345,7 @@ internal fun AndroidAppsPage(s: FrontEndState, a: FrontEndActions, modifier: Mod
items(entries, key = { it.key }) { entry ->
when (entry) {
is AppEntry.App -> AppTile(
entry.app, folderId = null, onLaunch = onLaunch, onNewFolder = newFolder, onChangeIcon = { iconFor = it },
entry.app, folderId = null, onLaunch = onLaunch, onNewFolder = newFolder,
first = entry === entries.first(),
)
is AppEntry.Shortcut -> PinnedTile(entry.pinned, first = entry === entries.first())
@@ -443,7 +369,7 @@ internal fun AndroidAppsPage(s: FrontEndState, a: FrontEndActions, modifier: Mod
var last by remember { mutableStateOf(folder) }
if (folder != null) last = folder
last?.let { f ->
FolderSheet(f, f.apps.mapNotNull(member).filter { it.key !in hidden }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }), renameOnOpen, onLaunch, newFolder, { iconFor = it }) {
FolderSheet(f, f.apps.mapNotNull(member).filter { it.key !in hidden }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }), renameOnOpen, onLaunch, newFolder) {
openFolder = null
renameOnOpen = false
}
@@ -453,19 +379,11 @@ internal fun AndroidAppsPage(s: FrontEndState, a: FrontEndActions, modifier: Mod
picking, enter = fadeIn(Motion.tw(180)), exit = fadeOut(Motion.tw(160)),
modifier = Modifier.fillMaxSize().zIndex(3f),
) { WidgetPicker(padH) { picking = false } }
AnimatedVisibility(
iconFor != null, enter = fadeIn(Motion.tw(180)), exit = fadeOut(Motion.tw(160)),
modifier = Modifier.fillMaxSize().zIndex(4f),
) {
var last by remember { mutableStateOf(iconFor) }
iconFor?.let { last = it }
last?.let { app -> AppIconPicker(app, padH) { iconFor = null } }
}
}
}
@Composable
internal fun SwipeLock() {
private fun SwipeLock() {
DisposableEffect(Unit) {
PageSwipe.locks++
onDispose { PageSwipe.locks-- }
@@ -652,22 +570,22 @@ private fun AppIcon(app: HomeApp.LaunchableApp, size: androidx.compose.ui.unit.D
private fun AppTile(
app: HomeApp.LaunchableApp, folderId: String?, first: Boolean,
onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit,
onChangeIcon: (HomeApp.LaunchableApp) -> Unit, modifier: Modifier = Modifier,
modifier: Modifier = Modifier,
) {
var menu by remember { mutableStateOf(false) }
Box(modifier) {
TileFrame(app.key, first, onClick = { onLaunch(app) }, onMenu = { menu = true }) {
AppIcon(app, AppsGrid.iconDp.dp)
if (AppsGrid.labels) TileLabel(app.label)
AppIcon(app, 52.dp)
TileLabel(app.label)
}
AppMenu(app, folderId, menu, onDismiss = { menu = false }, onNewFolder = onNewFolder, onChangeIcon = onChangeIcon)
AppMenu(app, folderId, menu, onDismiss = { menu = false }, onNewFolder = onNewFolder)
}
}
@Composable
private fun AppMenu(
app: HomeApp.LaunchableApp, folderId: String?, open: Boolean,
onDismiss: () -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit, onChangeIcon: (HomeApp.LaunchableApp) -> Unit,
onDismiss: () -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit,
) {
val ctx = LocalContext.current
var choosing by remember { mutableStateOf(false) }
@@ -720,14 +638,6 @@ private fun AppMenu(
onDismiss()
HomeHidden.set(ctx, app.key, !isHidden)
}
if (IconPack.active(ctx) != null) MenuItem(stringResource(R.string.apps_change_icon), checked = false) {
onDismiss()
onChangeIcon(app)
}
if (app.key in HomeIcons.overrides) MenuItem(stringResource(R.string.apps_reset_icon), checked = false) {
onDismiss()
HomeIcons.clear(ctx, app.key)
}
MenuItem(stringResource(R.string.apps_app_info), checked = false) {
onDismiss()
runCatching { HomeApp.openAppInfo(ctx, app) }
@@ -754,10 +664,10 @@ private fun PinnedTile(pinned: HomePins.Pinned, first: Boolean) {
TileFrame(pinned.key, first, onClick = { runCatching { HomeApp.startShortcut(ctx, pinned.info) } }, onMenu = { menu = true }) {
Box {
val icon = pinned.icon
if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(AppsGrid.iconDp.dp))
else Box(Modifier.size(AppsGrid.iconDp.dp).clip(CircleShape).background(artBrush(hueOf(pinned.label))))
if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(52.dp))
else Box(Modifier.size(52.dp).clip(CircleShape).background(artBrush(hueOf(pinned.label))))
}
if (AppsGrid.labels) TileLabel(pinned.label)
TileLabel(pinned.label)
}
AnchoredMenu(menu, onDismiss = { menu = false }, title = pinned.label, compact = true, minWidth = 180.dp) { firstItem ->
MenuItem(stringResource(R.string.apps_shortcut_remove), checked = false, detail = pinned.appLabel, focusRequester = firstItem) {
@@ -792,8 +702,8 @@ private fun FolderTile(entry: AppEntry.Folder, first: Boolean, onOpen: () -> Uni
var menu by remember { mutableStateOf(false) }
Box {
TileFrame(entry.key, first, onClick = onOpen, onMenu = { menu = true }) {
FolderIcon(entry.apps, AppsGrid.iconDp.dp)
if (AppsGrid.labels) TileLabel(entry.folder.name)
FolderIcon(entry.apps, 52.dp)
TileLabel(entry.folder.name)
}
AnchoredMenu(menu, onDismiss = { menu = false }, title = entry.folder.name, compact = true, minWidth = 160.dp) { firstItem ->
MenuItem(stringResource(R.string.apps_folder_rename), checked = false, focusRequester = firstItem) {
@@ -812,8 +722,7 @@ private fun FolderTile(entry: AppEntry.Folder, first: Boolean, onOpen: () -> Uni
@Composable
private fun FolderSheet(
folder: HomeFolders.Folder, apps: List<HomeApp.LaunchableApp>, renameFirst: Boolean,
onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit,
onChangeIcon: (HomeApp.LaunchableApp) -> Unit, onClose: () -> Unit,
onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit, onClose: () -> Unit,
) {
SwipeLock()
val ctx = LocalContext.current
@@ -870,40 +779,29 @@ private fun FolderSheet(
.focusGroup()
.padding(16.dp),
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp)) {
if (renaming) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp)) {
if (renaming) Box(Modifier.weight(1f)) {
AdbTextField(
value = name, onValueChange = { name = it.take(40) }, label = stringResource(R.string.apps_folder_name),
keyboardType = KeyboardType.Text, imeAction = ImeAction.Done, compact = true, showLabel = false,
placeholder = folder.name, focusOnShow = true, onDone = { commit() },
)
} else {
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val rename = { renaming = true }
Text(
folder.name, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = colors.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center,
// A faint chip at rest shows the name can be selected, now that the pencil is gone.
modifier = Modifier.clip(Shape12)
.background(if (hot) pal.signal.copy(alpha = 0.12f) else colors.onBackground.copy(alpha = 0.07f))
.glideBorder(hot, Shape12, pal.signal)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, onClickLabel = stringResource(R.string.apps_folder_rename), role = Role.Button, onClick = rename)
.controllerConfirm(onClick = rename)
.padding(horizontal = 14.dp, vertical = 6.dp),
)
Text(folder.name, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
SmallIconButton(Icons.Filled.Edit, stringResource(R.string.apps_folder_rename), tint = colors.onSurfaceVariant) { renaming = true }
Spacer(Modifier.weight(1f))
}
SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = colors.onSurfaceVariant) { close() }
}
LazyVerticalGrid(
columns = GridCells.Adaptive(92.dp + AppsGrid.spacing.dp),
columns = GridCells.Adaptive(92.dp),
state = grid,
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
items(apps, key = { it.key }) { app ->
AppTile(
app, folderId = folder.id, first = false, onLaunch = { onClose(); onLaunch(it) }, onNewFolder = onNewFolder, onChangeIcon = onChangeIcon,
app, folderId = folder.id, first = false, onLaunch = { onClose(); onLaunch(it) }, onNewFolder = onNewFolder,
modifier = if (app === apps.first()) Modifier.focusRequester(firstApp) else Modifier,
)
}
@@ -925,7 +823,7 @@ private fun WidgetCard(w: HomeWidgets.Placed, maxWidthDp: Int) {
val activity = remember(ctx) { ctx.findActivity() }
Box {
Box(
Modifier.paneItem("widget:${w.id}").size(width.dp, w.heightDp.dp)
Modifier.size(width.dp, w.heightDp.dp)
.clip(Shape16)
.background(colors.surface.copy(alpha = 0.35f))
.glideBorder(hot || menu, Shape16, pal.signal)
@@ -1,188 +0,0 @@
package com.droiddeck.launcher.ui
import android.graphics.Bitmap
import android.util.LruCache
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.graphics.drawable.toBitmap
import com.droiddeck.launcher.HomeApp
import com.droiddeck.launcher.HomeIcons
import com.droiddeck.launcher.IconPack
import com.droiddeck.launcher.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
private val CELL_ICON = 44.dp
@OptIn(ExperimentalComposeUiApi::class)
private fun Modifier.focusTrap(): Modifier = focusProperties {
exit = { dir ->
if (dir == FocusDirection.Up || dir == FocusDirection.Down || dir == FocusDirection.Left || dir == FocusDirection.Right) FocusRequester.Cancel
else FocusRequester.Default
}
}.focusGroup()
private fun normalized(text: String) = text.lowercase().filter { it.isLetterOrDigit() }
internal fun iconMatches(names: List<String>, label: String, query: String): List<String> {
val q = normalized(query)
if (q.isNotEmpty()) return names.filter { q in normalized(it) }
val hint = normalized(label)
val (likely, rest) = names.partition { hint in normalized(it) }
return likely + rest
}
@Composable
internal fun AppIconPicker(app: HomeApp.LaunchableApp, padH: androidx.compose.ui.unit.Dp, onClose: () -> Unit) {
SwipeLock()
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pack = remember { IconPack.selected(ctx) }
val names by produceState<List<String>?>(null, pack) { value = withContext(Dispatchers.IO) { IconPack.names(ctx, pack) } }
var query by remember { mutableStateOf("") }
val shown = remember(names, query) { names?.let { iconMatches(it, app.label, query) } }
val cache = remember { LruCache<String, Bitmap>(256) }
val inputMode = LocalInputModeManager.current.inputMode
val ff = LocalFrontFocus.current
val first = remember { FocusRequester() }
var closing by remember { mutableStateOf(false) }
val close = {
closing = true
onClose()
if (inputMode == InputMode.Keyboard && ff != null) {
runCatching { ff.items.getValue("tile:${app.key}").requestFocus() }
.onFailure { runCatching { ff.firstTile.requestFocus() } }
}
}
LaunchedEffect(names != null, inputMode) {
if (names != null && !closing && inputMode == InputMode.Keyboard) {
repeat(2) { androidx.compose.runtime.withFrameNanos { } }
ff?.last = "icon:${shown?.firstOrNull()}"
if (!closing) runCatching { first.requestFocus() }
}
}
BackHandler { close() }
Column(
Modifier.fillMaxSize().imePadding().background(colors.background)
.blockTouches()
.focusTrap(),
) {
val title = stringResource(R.string.touch_icon_for, app.label)
Box(Modifier.fillMaxWidth().padding(start = padH, end = padH, top = 8.dp)) {
ModeHeader(
title, query, { query = it }, placeholder = stringResource(R.string.apps_icons_search),
lead = {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
BackLink(stringResource(R.string.rail_apps), compact = true, onClick = close)
Text(title, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
},
inlineWhenStacked = true,
) { }
}
LazyVerticalGrid(
columns = GridCells.Adaptive(64.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
contentPadding = PaddingValues(horizontal = padH, vertical = 8.dp),
modifier = Modifier.fillMaxSize(),
) {
when {
shown == null -> item(key = "loading", span = { GridItemSpan(maxLineSpan) }) { Note(stringResource(R.string.apps_icons_loading)) }
shown.isEmpty() -> item(key = "none", span = { GridItemSpan(maxLineSpan) }) { Note(stringResource(R.string.apps_icons_none)) }
else -> items(shown, key = { it }) { name ->
PackIconCell(
pack, name, cache,
modifier = if (name == shown.first()) Modifier.focusRequester(first) else Modifier,
) {
HomeIcons.set(ctx, app.key, pack, name)
close()
}
}
}
}
}
}
@Composable
private fun PackIconCell(
pack: String, name: String, cache: LruCache<String, Bitmap>, modifier: Modifier, onPick: () -> Unit,
) {
val ctx = LocalContext.current
val iconPx = with(LocalDensity.current) { CELL_ICON.roundToPx() }
val bitmap by produceState(cache.get(name), name) {
if (value == null) value = withContext(Dispatchers.IO) {
runCatching { IconPack.drawable(ctx, pack, name, ctx.resources.displayMetrics.densityDpi)?.toBitmap(iconPx, iconPx) }.getOrNull()?.also { cache.put(name, it) }
}
}
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
Box(
contentAlignment = Alignment.Center,
modifier = modifier.fillMaxWidth().paneItem("icon:$name").clip(Shape12)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(hot, Shape12, pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onPick)
.controllerConfirm(onClick = onPick)
.semantics { contentDescription = name.replace('_', ' ') }
.padding(10.dp),
) {
val icon = bitmap
if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(CELL_ICON))
else Spacer(Modifier.size(CELL_ICON))
}
}
@@ -1,120 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Palette
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.HomeIcons
import com.droiddeck.launcher.IconPack
import com.droiddeck.launcher.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
private val PanelWidth = 348.dp
private val PanelHeight = 316.dp
private val TabsWidth = 204.dp
@Composable
internal fun AppsAppearanceButton(a: FrontEndActions) {
val pal = LocalPalette.current
val title = stringResource(R.string.apps_appearance)
var at by remember { mutableStateOf<Rect?>(null) }
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) {
HeaderIconButton(title, Icons.Filled.Palette, "apps-appearance") {
val from = at ?: return@HeaderIconButton
Steps.ask(StepAsk(
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = 2, maxWidth = PanelWidth,
handle = { Icon(Icons.Filled.Palette, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
) {
StepTitle(title)
Column(
Modifier.stepItem(1).fillMaxWidth().height(minOf(PanelHeight, (maxHeight - 64.dp).coerceAtLeast(44.dp))).verticalScroll(rememberScrollState()),
) { AppearanceRows(a) }
})
}
}
}
@Composable
private fun StepOutScope.AppearanceRows(a: FrontEndActions) {
val ctx = LocalContext.current
val host = rememberMenuHost()
var packsOpen by remember { mutableStateOf(false) }
var selected by remember { mutableStateOf(IconPack.selected(ctx)) }
var appColors by remember { mutableStateOf(IconPack.appColors(ctx)) }
val installed by produceState(emptyList<IconPack.Pack>()) {
value = withContext(Dispatchers.IO) { runCatching { IconPack.installed(ctx) }.getOrDefault(emptyList()) }
}
val hasBack by produceState(false, selected) { value = withContext(Dispatchers.IO) { IconPack.active(ctx)?.hasBack == true } }
CompositionLocalProvider(LocalCompactSettings provides true) {
val packs = listOf(IconPack.Pack(IconPack.NONE, stringResource(R.string.apps_icon_pack_system))) + installed
val current = packs.find { it.packageName == selected } ?: packs.first()
Box(Modifier.focusRequester(first)) {
LinkRow(
stringResource(R.string.apps_icon_pack), current.label, "", "icon-pack",
arrow = if (packsOpen) "▴" else "▾",
) { packsOpen = !packsOpen }
}
if (packsOpen) packs.forEach { (value, text) ->
MenuItem(text, checked = value == current.packageName) {
selected = value
IconPack.select(ctx, value)
a.onAppIconsChanged()
packsOpen = false
runCatching { first.requestFocus() }
}
}
SettingsRow(stringResource(R.string.apps_icon_size), null) {
SegmentedTabs(
listOf(
AppsGrid.SMALL to stringResource(R.string.apps_icon_small),
AppsGrid.MEDIUM to stringResource(R.string.apps_icon_medium),
AppsGrid.LARGE to stringResource(R.string.apps_icon_large),
),
AppsGrid.iconDp, Modifier.width(TabsWidth),
) { AppsGrid.setIconDp(ctx, it) }
}
SettingsRow(stringResource(R.string.apps_spacing), null) {
SegmentedTabs(
listOf(
AppsGrid.TIGHT to stringResource(R.string.apps_spacing_tight),
AppsGrid.NORMAL to stringResource(R.string.apps_spacing_normal),
AppsGrid.ROOMY to stringResource(R.string.apps_spacing_roomy),
),
AppsGrid.spacing, Modifier.width(TabsWidth),
) { AppsGrid.setSpacing(ctx, it) }
}
ToggleRow(host, "app-names", stringResource(R.string.apps_hide_names), null, !AppsGrid.labels) { AppsGrid.setLabels(ctx, !it) }
if (hasBack) ToggleRow(host, "app-colors", stringResource(R.string.apps_icon_app_colors), null, appColors) {
appColors = it
IconPack.setAppColors(ctx, it)
a.onAppIconsChanged()
}
if (HomeIcons.overrides.isNotEmpty()) ActionRow(stringResource(R.string.apps_icons_custom), null, stringResource(R.string.ctrl_reset), {
HomeIcons.clearAll(ctx)
runCatching { first.requestFocus() }
})
}
}
@@ -2,12 +2,7 @@ package com.droiddeck.launcher.ui
import android.app.Activity
import android.app.Application
import android.content.BroadcastReceiver
import android.content.Intent
import android.content.IntentFilter
import android.content.Context
import androidx.core.content.ContextCompat
import com.droiddeck.launcher.session.BuildWatermarkSetting
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Typeface
@@ -19,14 +14,11 @@ import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import java.util.WeakHashMap
import com.droiddeck.launcher.BuildConfig
import com.droiddeck.launcher.QuestXrActivity
object BuildWatermark {
private const val TITLE_LIMIT = 80
private val activities = WeakHashMap<Activity, Unit>()
internal var lineProvider: () -> List<String>? = { lines() }
fun lines(
pr: Int = BuildConfig.PR_NUMBER,
@@ -46,56 +38,33 @@ object BuildWatermark {
if (text.length <= TITLE_LIMIT) text else text.take(TITLE_LIMIT - 1).trimEnd() + "…"
fun install(app: Application) {
ContextCompat.registerReceiver(
app,
object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) { refresh(context) }
},
IntentFilter(BuildWatermarkSetting.CHANGED),
"${app.packageName}.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION",
null,
ContextCompat.RECEIVER_NOT_EXPORTED,
)
val lab = com.droiddeck.launcher.lab.LabOverlay.active?.let { "LAB | ${truncate(it.label)}" }
val lines = (listOfNotNull(lab) + lines().orEmpty()).ifEmpty { return }
app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
if (activity is QuestXrActivity) return
synchronized(activities) { activities[activity] = Unit }
update(activity)
val decor = activity.window.decorView as? ViewGroup ?: return
if (decor.findViewWithTag<View>(TAG) != null) return
val margin = (8 * activity.resources.displayMetrics.density).toInt()
decor.addView(
MarkView(activity, lines).apply { tag = TAG },
FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM or Gravity.END,
).apply { setMargins(margin, margin, margin, margin) },
)
}
override fun onActivityStarted(activity: Activity) = Unit
override fun onActivityResumed(activity: Activity) { update(activity) }
override fun onActivityResumed(activity: Activity) = Unit
override fun onActivityPaused(activity: Activity) = Unit
override fun onActivityStopped(activity: Activity) = Unit
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
override fun onActivityDestroyed(activity: Activity) { synchronized(activities) { activities.remove(activity) } }
override fun onActivityDestroyed(activity: Activity) = Unit
})
}
fun refresh(context: Context) {
val current = synchronized(activities) { activities.keys.toList() }
current.forEach(::update)
}
private fun update(activity: Activity) {
if (activity is QuestXrActivity) return
val decor = activity.window.decorView as? ViewGroup ?: return
decor.findViewWithTag<View>(TAG)?.let(decor::removeView)
if (!com.droiddeck.launcher.session.SessionPrefs.buildWatermarkEnabled(activity)) return
val lab = com.droiddeck.launcher.lab.LabOverlay.active?.let { "LAB | ${truncate(it.label)}" }
val build = lineProvider().orEmpty()
val content = (listOfNotNull(lab) + build).ifEmpty { return }
val margin = (8 * activity.resources.displayMetrics.density).toInt()
decor.addView(
MarkView(activity, content).apply { tag = TAG },
FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM or Gravity.END,
).apply { setMargins(margin, margin, margin, margin) },
)
}
private const val TAG = "build-watermark"
private class MarkView(context: Context, private val lines: List<String>) : View(context) {
@@ -1,381 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.Easing
import androidx.compose.foundation.Canvas
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathOperation
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.graphics.drawscope.scale
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import kotlin.math.PI
internal enum class PetState { IDLE, WORKING, QUESTION, DONE, ERROR, SLEEP }
private val White = Color(0xFFFFFFFF)
private val Blue = Color(0xFF1A9FFF)
private val Ink = Color(0xFF0E141B)
private val Amber = Color(0xFFFFB627)
private val Red = Color(0xFFFF5A5F)
private val Slate = Color(0xFF3A4A5A)
private val Term = Color(0xFF26303B)
private val TermLine = Color(0xFF8FA3B6)
private val EaseInOut: Easing = CubicBezierEasing(0.42f, 0f, 0.58f, 1f)
private val EaseOut: Easing = CubicBezierEasing(0f, 0f, 0.58f, 1f)
private val Hop: Easing = CubicBezierEasing(0.3f, 0f, 0.4f, 1f)
private val Pop: Easing = CubicBezierEasing(0.3f, 1.6f, 0.5f, 1f)
private val Linear = Easing { it }
private val Step = Easing { 0f }
/** Where 0..1 of a loop [period] seconds long is at [time]; [lead] starts it that many seconds early. */
private fun loop(time: Float, period: Float, lead: Float = 0f): Float {
val t = (time + lead) % period
return (if (t < 0) t + period else t) / period
}
/** A CSS-style keyframe track: [stops] holds (position, value) pairs, eased per segment. */
private fun track(p: Float, easing: Easing, vararg stops: Float): Float {
if (p <= stops[0]) return stops[1]
var i = 0
while (i + 2 < stops.size) {
val a = stops[i]
val b = stops[i + 2]
if (p <= b) {
val t = if (b > a) (p - a) / (b - a) else 1f
return stops[i + 1] + (stops[i + 3] - stops[i + 1]) * easing.transform(t)
}
i += 2
}
return stops[stops.size - 1]
}
private fun mix(a: Color, b: Color, t: Float) = Color(
a.red + (b.red - a.red) * t, a.green + (b.green - a.green) * t, a.blue + (b.blue - a.blue) * t, a.alpha + (b.alpha - a.alpha) * t,
)
/** The DroidDeck mark the head is drawn from, in its own 128 by 223.72 space. */
private val headMark: Path by lazy {
val d = Path().apply {
moveTo(-31.98f, 0f)
lineTo(63.97f, 0f)
cubicTo(125.81f, 0f, 175.93f, 50.08f, 175.93f, 111.86f)
cubicTo(175.93f, 173.64f, 125.81f, 223.72f, 63.97f, 223.72f)
lineTo(-31.98f, 223.72f)
close()
}
val cut = Path().apply {
addOval(Rect(Offset(63.98f, 111.86f), 71.81f))
addRect(Rect(56.055f, 0f, 56.055f + 15.83f, 45f))
addRect(Rect(56.055f, 178.72f, 56.055f + 15.83f, 223.72f))
}
Path.combine(PathOperation.Difference, d, cut)
}
private fun star(x: Float, y: Float, a: Float) = Path().apply {
moveTo(x, y - a)
quadraticBezierTo(x, y, x + a, y)
quadraticBezierTo(x, y, x, y + a)
quadraticBezierTo(x, y, x - a, y)
quadraticBezierTo(x, y, x, y - a)
close()
}
private class Spark(val x: Float, val y: Float, val size: Float, val color: Color, val lead: Float)
private val sparks = listOf(
Spark(90f, 120f, 14f, White, 0f), Spark(318f, 110f, 12f, Blue, 0.4f), Spark(104f, 210f, 9f, Blue, 0.8f),
Spark(312f, 200f, 10f, White, 0.4f), Spark(250f, 40f, 8f, White, 0f),
).map { it to star(it.x, it.y, it.size) }
/** The rig of the DeeDee mock (a 400 by 360 view box) looping through [state]; [crop] is the part of the view box shown. */
@Composable
internal fun DeeDee(state: PetState, modifier: Modifier, crop: Rect = Rect(35f, 15f, 365f, 345f)) {
val time by produceState(0f) {
val start = withFrameNanos { it }
while (true) withFrameNanos { value = (it - start) / 1_000_000_000f }
}
val text = rememberTextMeasurer()
Canvas(modifier) {
val k = minOf(size.width / crop.width, size.height / crop.height)
withTransform({
translate((size.width - crop.width * k) / 2, (size.height - crop.height * k) / 2)
scale(k, k, Offset.Zero)
translate(-crop.left, -crop.top)
}) { rig(state, time, text) }
}
}
private fun DrawScope.rig(state: PetState, t: Float, text: androidx.compose.ui.text.TextMeasurer) {
// Shadow under the feet.
var shadowX = 1f
var shadowAlpha = 0.4f
when (state) {
PetState.IDLE -> shadowX = track(loop(t, 3f), EaseInOut, 0f, 1f, 0.5f, 0.9f, 1f, 1f)
PetState.DONE -> {
val p = loop(t, 1.2f)
shadowX = track(p, Hop, 0f, 1f, 0.15f, 1f, 0.45f, 0.7f, 0.75f, 1f, 1f, 1f)
shadowAlpha = track(p, Hop, 0f, 0.4f, 0.15f, 0.4f, 0.45f, 0.2f, 0.75f, 0.4f, 1f, 0.4f)
}
else -> Unit
}
scale(shadowX, 1f, Offset(200f, 336f)) {
drawOval(Color.Black.copy(alpha = shadowAlpha), Offset(130f, 327f), Size(140f, 18f))
}
// The whole body moves together.
var dx = 0f
var dy = 0f
var sx = 1f
var sy = 1f
when (state) {
PetState.IDLE -> dy = track(loop(t, 3f), EaseInOut, 0f, 0f, 0.5f, -6f, 1f, 0f)
PetState.WORKING -> dy = track(loop(t, 1.6f), EaseInOut, 0f, 0f, 0.5f, -2f, 1f, 0f)
PetState.QUESTION -> dy = track(loop(t, 2.4f), EaseInOut, 0f, 0f, 0.5f, -4f, 1f, 0f)
PetState.DONE -> {
val p = loop(t, 1.2f)
dy = track(p, Hop, 0f, 0f, 0.15f, 0f, 0.45f, -30f, 0.75f, 0f, 1f, 0f)
sx = track(p, Hop, 0f, 1.03f, 0.15f, 1f, 0.75f, 1f, 0.85f, 1.04f, 1f, 1.03f)
sy = track(p, Hop, 0f, 0.96f, 0.15f, 1f, 0.75f, 1f, 0.85f, 0.95f, 1f, 0.96f)
}
PetState.ERROR -> dx = track(loop(t, 2f), EaseInOut, 0f, 0f, 0.04f, -7f, 0.08f, 7f, 0.12f, -5f, 0.16f, 5f, 0.2f, -2f, 0.24f, 2f, 0.3f, 0f, 1f, 0f)
PetState.SLEEP -> {
val p = loop(t, 4f)
sx = track(p, EaseInOut, 0f, 1f, 0.5f, 1.02f, 1f, 1f)
sy = track(p, EaseInOut, 0f, 1f, 0.5f, 0.97f, 1f, 1f)
}
}
val alarm = if (state == PetState.ERROR) track(loop(t, 2f), EaseInOut, 0f, 0f, 0.04f, 1f, 0.24f, 1f, 0.3f, 0f, 1f, 0f) else 0f
withTransform({
translate(dx, dy)
scale(sx, sy, Offset(200f, 317f))
}) {
legs()
body(state, t, alarm)
if (state == PetState.WORKING) terminal(t)
arms(state, t)
head(state, t, alarm)
}
extras(state, t, text)
}
private fun DrawScope.legs() {
for ((x, y, w, h, r) in listOf(
floatArrayOf(166f, 283f, 18f, 30f, 8f), floatArrayOf(216f, 283f, 18f, 30f, 8f),
floatArrayOf(158f, 305f, 30f, 12f, 6f), floatArrayOf(212f, 305f, 30f, 12f, 6f),
)) drawRoundRect(White, Offset(x, y), Size(w, h), CornerRadius(r))
}
private operator fun FloatArray.component5() = this[4]
private fun DrawScope.body(state: PetState, t: Float, alarm: Float) {
drawRect(White, Offset(194f, 200f), Size(12f, 20f))
drawRoundRect(White, Offset(148f, 215f), Size(104f, 72f), CornerRadius(22f))
val glow = when (state) {
PetState.WORKING -> track(loop(t, 0.8f), EaseInOut, 0f, 1f, 0.5f, 0.5f, 1f, 1f)
PetState.SLEEP -> track(loop(t, 4f), EaseInOut, 0f, 0.35f, 0.5f, 0.8f, 1f, 0.35f)
else -> 1f
}
drawCircle(mix(Blue, Red, alarm).copy(alpha = glow), 11f, Offset(200f, 251f))
}
private fun DrawScope.terminal(t: Float) {
drawRoundRect(Term, Offset(150f, 256f), Size(100f, 40f), CornerRadius(8f))
drawRoundRect(Blue, Offset(150f, 256f), Size(100f, 40f), CornerRadius(8f), style = Stroke(3f))
drawRoundRect(Blue, Offset(160f, 266f), Size(44f, 5f), CornerRadius(2.5f))
val grow = track(loop(t, 1.6f), EaseOut, 0f, 0.1f, 0.7f, 1f, 1f, 1f)
scale(grow, 1f, Offset(160f, 278f)) { drawRoundRect(TermLine, Offset(160f, 276f), Size(60f, 5f), CornerRadius(2.5f)) }
val cursor = track(loop(t, 0.7f), Step, 0f, 1f, 0.5f, 0.2f, 1f, 0.2f)
drawRoundRect(White.copy(alpha = cursor), Offset(224f, 276f), Size(10f, 5f), CornerRadius(2f))
}
/** One arm: from the shoulder through a curve to the hand, turned about the shoulder. */
private fun DrawScope.arm(shoulder: Offset, control: Offset, hand: Offset, degrees: Float) {
rotate(degrees, shoulder) {
val path = Path().apply {
moveTo(shoulder.x, shoulder.y)
quadraticBezierTo(control.x, control.y, hand.x, hand.y)
}
drawPath(path, White, style = Stroke(10f, cap = StrokeCap.Round))
drawCircle(White, 9f, hand)
}
}
private fun DrawScope.arms(state: PetState, t: Float) {
val l = Offset(151f, 236f)
val r = Offset(249f, 236f)
when (state) {
PetState.IDLE -> {
val sway = track(loop(t, 3f), EaseInOut, 0f, 0f, 0.5f, 4f, 1f, 0f)
arm(l, Offset(127f, 246f), Offset(123f, 276f), sway)
arm(r, Offset(273f, 246f), Offset(277f, 276f), sway)
}
PetState.WORKING -> {
val p = loop(t, 0.32f)
arm(l, Offset(133f, 258f), Offset(157f, 270f), track(p, EaseInOut, 0f, 0f, 0.5f, -6f, 1f, 0f))
arm(r, Offset(267f, 258f), Offset(243f, 270f), track(p, EaseInOut, 0f, -5f, 0.5f, 1f, 1f, -5f))
}
PetState.QUESTION -> {
arm(l, Offset(127f, 246f), Offset(123f, 276f), 0f)
arm(r, Offset(279f, 230f), Offset(287f, 198f), track(loop(t, 0.9f), EaseInOut, 0f, -8f, 0.5f, 14f, 1f, -8f))
}
PetState.DONE -> {
val p = loop(t, 1.2f)
arm(l, Offset(121f, 230f), Offset(115f, 196f), track(p, EaseInOut, 0f, 0f, 0.45f, 12f, 1f, 0f))
arm(r, Offset(279f, 230f), Offset(285f, 196f), track(p, EaseInOut, 0f, 0f, 0.45f, -12f, 1f, 0f))
}
PetState.ERROR, PetState.SLEEP -> {
arm(Offset(151f, 238f), Offset(137f, 254f), Offset(135f, 284f), 0f)
arm(Offset(249f, 238f), Offset(263f, 254f), Offset(265f, 284f), 0f)
}
}
}
private fun DrawScope.head(state: PetState, t: Float, alarm: Float) {
val tilt = when (state) {
PetState.QUESTION -> track(loop(t, 2.4f), EaseInOut, 0f, -9f, 0.5f, -5f, 1f, -9f)
PetState.SLEEP -> 6f
else -> 0f
}
withTransform({
rotate(tilt, Offset(200f, 215f))
if (state == PetState.SLEEP) translate(0f, 6f)
}) {
antenna(state, t)
withTransform({
translate(200f, 150f)
scale(0.62f, 0.62f, Offset.Zero)
translate(-64f, -111.86f)
}) {
drawPath(headMark, White)
drawCircle(mix(Blue, Red, alarm).copy(alpha = if (state == PetState.SLEEP) 0.6f else 1f), 55.98f, Offset(63.98f, 111.86f))
}
eye(state, t)
if (state == PetState.WORKING) {
val sweep = 46f / (2f * PI.toFloat() * 39.6f) * 360f
rotate(360f * loop(t, 1.1f), Offset(200f, 150f)) {
drawArc(Blue, 0f, sweep, false, Offset(160.4f, 110.4f), Size(79.2f, 79.2f), style = Stroke(5f, cap = StrokeCap.Round))
}
}
}
}
private fun DrawScope.antenna(state: PetState, t: Float) {
val lean = when (state) {
PetState.ERROR -> 22f
PetState.SLEEP -> -28f
else -> 0f
}
rotate(lean, Offset(200f, 100f)) {
drawLine(White, Offset(200f, 100f), Offset(200f, 52f), 7f, StrokeCap.Round)
var radius = 10f
val (color, alpha) = when (state) {
PetState.IDLE -> Blue to track(loop(t, 3f), EaseInOut, 0f, 1f, 0.5f, 0.45f, 1f, 1f)
PetState.WORKING -> Blue to track(loop(t, 0.5f), Step, 0f, 1f, 0.5f, 0.2f, 1f, 0.2f)
PetState.QUESTION -> {
val p = loop(t, 1f)
radius = track(p, EaseInOut, 0f, 10f, 0.5f, 13f, 1f, 10f)
Amber to track(p, EaseInOut, 0f, 1f, 0.5f, 0.5f, 1f, 1f)
}
PetState.DONE -> Blue to 1f
PetState.ERROR -> Red to track(loop(t, 1f), Step, 0f, 1f, 0.5f, 0.25f, 1f, 0.25f)
PetState.SLEEP -> Slate to 1f
}
drawCircle(color.copy(alpha = alpha), radius, Offset(200f, 45f))
}
}
private fun DrawScope.eye(state: PetState, t: Float) {
when (state) {
PetState.DONE -> drawPath(Path().apply { moveTo(186f, 156f); quadraticBezierTo(203f, 136f, 220f, 156f) }, Ink, style = Stroke(7f, cap = StrokeCap.Round))
PetState.SLEEP -> drawPath(Path().apply { moveTo(186f, 152f); quadraticBezierTo(203f, 162f, 220f, 152f) }, Ink, style = Stroke(6f, cap = StrokeCap.Round))
PetState.ERROR -> {
val stroke = 6f
drawLine(Ink, Offset(193f, 139f), Offset(215f, 161f), stroke, StrokeCap.Round)
drawLine(Ink, Offset(215f, 139f), Offset(193f, 161f), stroke, StrokeCap.Round)
}
else -> {
val blink = if (state == PetState.IDLE) track(loop(t, 4.5f), EaseInOut, 0f, 1f, 0.44f, 1f, 0.47f, 0.1f, 0.5f, 1f, 1f, 1f) else 1f
val (px, py) = when (state) {
PetState.IDLE -> track(loop(t, 9f), EaseInOut, 0f, 0f, 0.3f, 0f, 0.36f, -7f, 0.52f, -7f, 0.58f, 5f, 0.8f, 5f, 0.86f, 0f, 1f, 0f) to 0f
PetState.WORKING -> track(loop(t, 1.6f), EaseInOut, 0f, -7f, 0.5f, 6f, 1f, -7f) to 0f
else -> 5f to -5f
}
scale(1f, blink, Offset(204f, 149f)) {
translate(px, py) {
drawCircle(Ink, 16f, Offset(204f, 149f))
drawCircle(White, 5f, Offset(210f, 143f))
drawCircle(White.copy(alpha = 0.7f), 2.2f, Offset(199f, 155f))
}
}
}
}
}
private fun DrawScope.speechTail(color: Color) {
drawPath(Path().apply { moveTo(264f, 82f); lineTo(254f, 100f); lineTo(278f, 86f); close() }, color)
}
private fun DrawScope.extras(state: PetState, t: Float, text: androidx.compose.ui.text.TextMeasurer) {
when (state) {
PetState.QUESTION -> {
val p = loop(t, 2.4f)
val s = track(p, Pop, 0f, 0.4f, 0.12f, 1f, 0.88f, 1f, 1f, 0.9f)
val a = track(p, Pop, 0f, 0f, 0.12f, 1f, 0.88f, 1f, 1f, 0f).coerceIn(0f, 1f)
scale(s, s, Offset(262f, 96f)) {
drawRoundRect(Amber.copy(alpha = a), Offset(254f, 30f), Size(62f, 58f), CornerRadius(18f))
speechTail(Amber.copy(alpha = a))
val mark = text.measure("?", TextStyle(color = Ink.copy(alpha = a), fontSize = 42f.toSp(), fontWeight = FontWeight.Bold))
drawText(mark, topLeft = Offset(285f - mark.size.width / 2f, 74f - mark.firstBaseline))
}
}
PetState.ERROR -> {
val nudge = track(loop(t, 2f), EaseInOut, 0f, 0f, 0.06f, -10f, 0.14f, 8f, 0.22f, -4f, 0.3f, 0f, 1f, 0f)
rotate(nudge, Offset(262f, 96f)) {
drawRoundRect(Red, Offset(254f, 34f), Size(54f, 54f), CornerRadius(16f))
speechTail(Red)
drawRoundRect(White, Offset(277f, 44f), Size(8f, 24f), CornerRadius(4f))
drawCircle(White, 5f, Offset(281f, 77f))
}
}
PetState.DONE -> for ((spark, path) in sparks) {
val p = loop(t, 1.2f, spark.lead)
val s = track(p, EaseInOut, 0f, 0f, 0.4f, 1f, 0.7f, 0.6f, 1f, 0f)
val turn = track(p, EaseInOut, 0f, 0f, 0.4f, 45f, 0.7f, 90f, 1f, 0f)
val a = track(p, EaseInOut, 0f, 0f, 0.4f, 1f, 0.7f, 0.8f, 1f, 0f)
if (s <= 0.01f) continue
withTransform({
rotate(turn, Offset(spark.x, spark.y))
scale(s, s, Offset(spark.x, spark.y))
}) { drawPath(path, spark.color.copy(alpha = a)) }
}
PetState.SLEEP -> for ((i, z) in listOf(Triple(250f, 96f, 22f), Triple(268f, 74f, 30f), Triple(286f, 52f, 38f)).withIndex()) {
val p = loop(t, 4f, -1.3f * i)
val a = track(p, EaseOut, 0f, 0f, 0.2f, 1f, 1f, 0f)
val zx = track(p, EaseOut, 0f, -10f, 1f, 14f)
val zy = track(p, EaseOut, 0f, 16f, 1f, -22f)
val glyph = text.measure("z", TextStyle(color = White.copy(alpha = a), fontSize = z.third.toSp(), fontWeight = FontWeight.Bold))
// The view box places a glyph by its baseline.
drawText(glyph, topLeft = Offset(z.first + zx, z.second + zy - glyph.firstBaseline))
}
else -> Unit
}
}
@@ -1,92 +0,0 @@
package com.droiddeck.launcher.ui
import android.view.Choreographer
import kotlin.math.abs
import kotlin.math.sqrt
/**
* Where something dragged and let go against the side edges, like a chat head, comes to rest:
* a quick sideways flick sends it to the side it was thrown toward from wherever it is; a slower
* release goes to the side its coasting would carry it to; and its height carries on with the
* throw. Velocities are pixels per second.
*/
internal object EdgeFling {
/** How far a throw coasts, in seconds of its release velocity. */
const val COAST_S = 0.18f
/** A sideways speed past this many dp per second picks its side outright. */
private const val FLICK_DP_S = 600f
fun toRight(centerX: Float, span: Float, vx: Float, density: Float): Boolean {
if (abs(vx) > FLICK_DP_S * density) return vx > 0
return centerX + vx * COAST_S > span / 2
}
fun restY(y: Float, vy: Float, min: Float, max: Float) = (y + vy * COAST_S).coerceIn(min, max.coerceAtLeast(min))
}
/**
* A spring in two dimensions that starts with the velocity it was let go with, stepped on each
* display frame, so a throw flows into its settle instead of starting over from rest.
*/
internal class FlingSpring(
private val stiffness: Float = 340f,
dampingRatio: Float = 0.74f,
private val onFrame: (Float, Float) -> Unit,
) : Choreographer.FrameCallback {
private val damping = 2f * dampingRatio * sqrt(stiffness)
private var x = 0f
private var y = 0f
private var vx = 0f
private var vy = 0f
private var toX = 0f
private var toY = 0f
private var last = 0L
private var onEnd: (() -> Unit)? = null
var running = false
private set
fun start(fromX: Float, fromY: Float, velocityX: Float, velocityY: Float, targetX: Float, targetY: Float, end: (() -> Unit)? = null) {
cancel()
x = fromX; y = fromY; vx = velocityX; vy = velocityY; toX = targetX; toY = targetY
onEnd = end
if (Motion.scale == 0f) {
onFrame(toX, toY)
end?.invoke()
return
}
running = true
last = 0L
Choreographer.getInstance().postFrameCallback(this)
}
fun cancel() {
if (!running) return
running = false
Choreographer.getInstance().removeFrameCallback(this)
}
override fun doFrame(frameTimeNanos: Long) {
if (!running) return
val dt = if (last == 0L) 1f / 120f else ((frameTimeNanos - last) / 1e9f).coerceIn(0f, 1f / 20f)
last = frameTimeNanos
// Small fixed steps keep the spring stable however long a frame took.
var left = dt / Motion.scale.coerceAtLeast(0.1f)
while (left > 0f) {
val h = minOf(left, 1f / 480f)
vx += (-stiffness * (x - toX) - damping * vx) * h
vy += (-stiffness * (y - toY) - damping * vy) * h
x += vx * h
y += vy * h
left -= h
}
val settled = abs(x - toX) < 0.5f && abs(y - toY) < 0.5f && abs(vx) < 20f && abs(vy) < 20f
if (settled) {
running = false
onFrame(toX, toY)
onEnd?.invoke()
return
}
onFrame(x, y)
Choreographer.getInstance().postFrameCallback(this)
}
}
@@ -13,9 +13,6 @@ internal fun FrameGenMenu(
host: MenuHost, mode: FrameGen.Mode, lossless: Lossless.State,
onPick: (FrameGen.Mode) -> Unit,
onImportLossless: () -> Unit,
gameProfileId: String? = null,
hasGameOverride: Boolean = false,
onResetGame: () -> Unit = {},
) {
val context = LocalContext.current
AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = stringResource(R.string.frame_gen_title)) { firstItemFocus ->
@@ -30,12 +27,6 @@ internal fun FrameGenMenu(
onPick(m); host.open = null
}
item(FrameGen.Mode.OFF, focus = firstItemFocus)
if (gameProfileId != null) {
MenuItem(stringResource(R.string.comp_game_use_general), checked = !hasGameOverride) {
onResetGame()
host.open = null
}
}
for (m in 2..4) item(FrameGen.Mode(FrameGen.ENGINE_DDFG, m))
val lsfg = (2..4).map { FrameGen.Mode(FrameGen.ENGINE_LSFG, it) } +
FrameGen.ADAPTIVE_TARGETS.map { FrameGen.Mode(FrameGen.ENGINE_LSFG, target = it) }
@@ -275,7 +275,7 @@ private fun Content(
return
}
if (selected == "android-apps" && s.isHomeApp) {
AndroidAppsPage(s, a, modifier, onAndroidAppClick)
AndroidAppsPage(s, modifier, onAndroidAppClick)
return
}
Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = padH, vertical = padV)) {
@@ -125,7 +125,7 @@ internal fun navigationKeys(s: FrontEndState) = buildList {
add("steam"); add("games")
if (s.gameStoresEnabled) add("stores")
add("desktop")
if (com.droiddeck.launcher.agent.AgentTab.visible) add("agent")
if (com.droiddeck.launcher.agent.AgentHost.available) add("agent")
add("components")
if (s.isHomeApp) add("android-apps")
add("setup"); add("updates")
@@ -40,8 +40,6 @@ import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.width
@@ -110,7 +108,6 @@ class FrontEndState(
val vacDiagnostics: Boolean = false,
val agentCommands: Boolean = false,
val graphicsLogs: Boolean = false,
val buildWatermark: Boolean = true,
val steamGpuDrawing: Boolean = false,
val bridgeFellBack: Boolean = false,
val bridgeFellBackMemory: Boolean = false,
@@ -171,7 +168,6 @@ class FrontEndState(
val showPhantomGate: Boolean = false,
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
val launcherOrientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER,
val homePage: String = com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM,
val launcherFullscreen: Boolean = true,
val downloadSource: String = DownloadSource.MODE_AUTO,
val downloadMirror: String = "",
@@ -251,7 +247,6 @@ class FrontEndActions(
val onVacDiagnostics: () -> Unit = {},
val onAgentCommands: () -> Unit = {},
val onGraphicsLogs: () -> Unit = {},
val onBuildWatermark: () -> Unit = {},
val onSteamGpuDrawing: () -> Unit = {},
val onClearCachedApps: (Boolean) -> Unit = {},
val onMemoryHud: (String) -> Unit = {},
@@ -272,7 +267,6 @@ class FrontEndActions(
val onLauncherIcon: (String) -> Unit = {},
val onOrientation: (Int) -> Unit = {},
val onLauncherOrientation: (Int) -> Unit = {},
val onHomePage: (String) -> Unit = {},
val onLauncherFullscreen: (Boolean) -> Unit = {},
val onAnimationsEnabled: (Boolean) -> Unit = {},
val onLowStorageWarning: (Boolean) -> Unit = {},
@@ -293,7 +287,6 @@ class FrontEndActions(
val onLibraryChanged: () -> Unit = {},
val onHomeApp: () -> Unit = {},
val onHomeScreen: (Boolean) -> Unit = {},
val onAppIconsChanged: () -> Unit = {},
val onSteamIntegration: (com.droiddeck.launcher.core.SteamIntegration.Feature?) -> Unit = {},
val onDismissIntegration: () -> Unit = {},
val onIntegration: (com.droiddeck.launcher.core.SteamIntegration.Feature) -> Unit = {},
@@ -469,14 +462,6 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
"setup:launcher" -> { SetupTabs.openLauncher = true; selected = "setup" }
com.droiddeck.launcher.sync.SyncthingService.NAV -> com.droiddeck.launcher.sync.Syncthing.requestOpen()
"setup:integration" -> { SetupTabs.openOverview = true; selected = "setup" }
com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_APPS -> {
// Home lands on the apps page itself, so a page open over the rail (Components, Performance) closes first.
if (s.pageKey != null) a.onPageBack()
Hops.origin = null
Hops.restore = null
Hops.sinking = null
selected = target
}
else -> selected = target
}
a.onNavigated()
@@ -702,11 +687,9 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
onRailSelect(key)
}, a)
CompositionLocalProvider(LocalShowSection provides { key -> selected = key }) {
val agentKeyboardOpen = railSelection == "agent" && WindowInsets.ime.getBottom(androidx.compose.ui.platform.LocalDensity.current) > 0
LauncherLayout(
bottomNavigation && !s.dualScreen, pal.line,
Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() }
.then(if (railSelection == "agent") Modifier.imePadding() else Modifier)
.then(if (s.dualScreen) Modifier.onKeyEvent { event ->
val step = dualPageStep(event.nativeKeyEvent) ?: return@onKeyEvent false
if (event.type == KeyEventType.KeyDown && !processSettingsPageVisible) {
@@ -720,7 +703,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
true
} else Modifier),
navigation = {
if (s.dualScreen || (bottomNavigation && agentKeyboardOpen)) Unit
if (s.dualScreen) Unit
else if (bottomNavigation) BottomBar(s, railSelection, onRailSelect, onRailFocus, a, railFocus)
else SideRail(s, railSelection, onRailSelect, onRailFocus, a, railFocus.fillMaxHeight())
},
@@ -468,11 +468,6 @@ internal fun SetupPanel(
) { a.onHomeScreen(it) }
if (s.homeScreenEnabled) {
ActionRow(stringResource(R.string.setup_default_home), s.defaultHomeLabel ?: stringResource(R.string.setup_choose_home), stringResource(R.string.setup_choose), a.onHomeApp)
ChoiceRow(
host, "home-page", stringResource(R.string.setup_home_page), stringResource(R.string.setup_home_page_hint),
com.droiddeck.launcher.core.AppUiPrefs.homePageOptions.map { (value, label) -> value to stringResource(label) },
s.homePage, onPick = a.onHomePage,
)
}
ChoiceRow(
host, "launcher-orientation", stringResource(R.string.setup_launcher_orientation), null,
@@ -594,19 +589,6 @@ internal fun SetupPanel(
) { a.onGameDebugLogs() }
ToggleRow(host, "vacdiag", stringResource(R.string.setup_vac_diag), stringResource(R.string.setup_vac_diag_hint), s.vacDiagnostics) { a.onVacDiagnostics() }
ToggleRow(host, "agent-commands", stringResource(R.string.setup_agent_commands), null, s.agentCommands) { a.onAgentCommands() }
if (com.droiddeck.launcher.agent.AgentHost.available) {
val agentContext = androidx.compose.ui.platform.LocalContext.current
ToggleRow(host, "agent-tab", stringResource(R.string.setup_agent_tab), null, com.droiddeck.launcher.agent.AgentTab.shown) {
com.droiddeck.launcher.agent.AgentTab.set(agentContext, it)
}
ToggleRow(host, "agent-pet", stringResource(R.string.setup_agent_pet), stringResource(R.string.setup_agent_pet_hint), AgentPet.enabled) {
AgentPet.set(agentContext, it)
}
if (AgentPet.enabled && !AgentPet.allowed) ActionRow(
stringResource(R.string.setup_agent_pet_float), stringResource(R.string.setup_agent_pet_float_hint),
stringResource(R.string.setup_agent_pet_allow), onClick = { AgentPet.requestFloating(agentContext) },
)
}
ToggleRow(host, "graphics-logs", stringResource(R.string.setup_graphics_logs), stringResource(R.string.setup_graphics_logs_hint), s.graphicsLogs) { a.onGraphicsLogs() }
if (!s.adreno && com.droiddeck.launcher.session.SessionPrefs.steamGpuCompositingAllowed()) ToggleRow(host, "steam-gpu-drawing", stringResource(R.string.setup_steam_gpu_drawing), stringResource(R.string.setup_steam_gpu_drawing_hint), s.steamGpuDrawing) { a.onSteamGpuDrawing() }
ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs,
@@ -757,17 +739,6 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
val context = androidx.compose.ui.platform.LocalContext.current
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
val wincompKey = game?.takeIf { it.library == com.droiddeck.launcher.frontend.Library.ADDED || it.appId > 0 }?.profileKey
val frameGenProfileKey = game?.profileKey?.takeIf { it.isNotBlank() }
var gameFrameGenMode by remember(frameGenProfileKey) {
mutableStateOf(frameGenProfileKey?.let {
com.droiddeck.launcher.gpu.FrameGen.mode(context, it)
} ?: s.frameGen)
}
var gameFrameGenOverride by remember(frameGenProfileKey) {
mutableStateOf(frameGenProfileKey?.let {
com.droiddeck.launcher.gpu.FrameGen.hasGameOverride(context, it)
} ?: false)
}
var wincompOpen by remember(wincompKey) { mutableStateOf<Boolean?>(null) }
val wincompPicks = remember(wincompKey, wincompOpen) { wincompKey?.let { com.droiddeck.launcher.session.WinComponents.picks(context, it) }.orEmpty() }
val steamScope = game?.let { com.droiddeck.launcher.session.NoSteamLaunch.scope(it) }
@@ -786,42 +757,10 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
}
add { m ->
Box(m) {
SettingCard(
stringResource(R.string.frame_gen_title),
if (frameGenProfileKey != null)
com.droiddeck.launcher.gpu.FrameGen.label(context, gameFrameGenMode)
else s.frameGenLabel,
"card:fg", Modifier.fillMaxSize()
) {
SettingCard(stringResource(R.string.frame_gen_title), s.frameGenLabel, "card:fg", Modifier.fillMaxSize()) {
host.open = if (host.open == "fg") null else "fg"
}
FrameGenMenu(
host = host,
mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen,
lossless = s.lossless,
onPick = { mode ->
val key = frameGenProfileKey
if (key == null) {
a.onFrameGenPick(mode)
} else {
com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode)
gameFrameGenMode = mode
gameFrameGenOverride = true
}
},
onImportLossless = a.onImportLossless,
gameProfileId = frameGenProfileKey,
hasGameOverride = gameFrameGenOverride,
onResetGame = {
val key = frameGenProfileKey
if (key != null) {
com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key)
gameFrameGenMode =
com.droiddeck.launcher.gpu.FrameGen.mode(context)
gameFrameGenOverride = false
}
}
)
FrameGenMenu(s, a, host)
}
}
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
@@ -309,7 +309,7 @@ private fun GameStatusLine(source: String, game: Library.SteamGame?, item: Catal
item?.accessible == true -> listOf(stringResource(R.string.stores_eyebrow_library))
else -> listOf(stringResource(R.string.stores_eyebrow_store))
}
val size = if (folder != null && (installed != null || game != null)) diskSize(installed, folder) else catalogSize(item).takeIf { it > 0 }
val size = if (folder != null && (installed != null || game != null)) diskSize(installed, folder) else (item?.sizeBytes ?: 0L).takeIf { it > 0 }
val line = (state + listOfNotNull(size?.let { formatBytes(it) })).filter { it.isNotBlank() }.joinToString(" · ").replaceFirstChar { it.uppercase() }
val muted = colors.onBackground.copy(alpha = 0.78f)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
@@ -399,8 +399,6 @@ internal fun GameActions(
val download = rawDownload?.takeIf { it.isActive }
val failed = rawDownload?.takeIf { it.state == DownloadState.FAILED }
val cloud = game?.library == Library.XBOX_CLOUD && installed == null
val downloadBytes = catalogSize(item)
val launchSupported = store != Store.ROCKSTAR || com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(id)
Actions {
when {
s.shortcutPicker && game != null -> {
@@ -412,8 +410,8 @@ internal fun GameActions(
val xboxBusy = store == Store.XBOX && id != null && XboxContent.busy(id)
val preparing = (game?.launchKey ?: storeKey)?.let { it in s.preparingGames } == true
PrimaryButton(
stringResource(if (!launchSupported) R.string.stores_rockstar_launch_unavailable else if (preparing) R.string.store_starting else R.string.stores_play),
enabled = launchSupported && !s.busy && !preparing && gone == null && download == null && !xboxBusy && (store != Store.GOG || installed?.sidecar?.isInstalled != false),
stringResource(if (preparing) R.string.store_starting else R.string.stores_play),
enabled = !s.busy && !preparing && gone == null && download == null && !xboxBusy && (store != Store.GOG || installed?.sidecar?.isInstalled != false),
main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn,
) {
if (game != null) a.onSteamGame(game) else if (store != null && id != null) launchStoreGame(store, id, s, a)
@@ -476,7 +474,7 @@ internal fun GameActions(
if (item?.installable == true && item.xboxPc) {
SecondaryButton(
if (StoresState.isUnfinished(item)) stringResource(R.string.stores_resume_install)
else if (downloadBytes > 0) stringResource(R.string.stores_install_size, formatBytes(downloadBytes))
else if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes))
else stringResource(R.string.stores_install),
) { StoresState.requestInstall(ctx, item) }
}
@@ -494,7 +492,7 @@ internal fun GameActions(
}
item?.installable == true -> {
InstallButton(
if (downloadBytes > 0) stringResource(R.string.stores_install_size, formatBytes(downloadBytes)) else stringResource(R.string.stores_install),
if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install),
leadOn,
) { StoresState.requestInstall(ctx, item) }
if (store == Store.XBOX && item.xboxCloud) {
@@ -507,12 +505,7 @@ internal fun GameActions(
InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
SecondaryButton(stringResource(R.string.stores_view_on, item.store.shortLabel)) { openStoreUrl(ctx, item) }
}
item != null && item.isFree -> {
val adding = StoresState.claiming[item.key] == true
PrimaryButton(stringResource(if (adding) R.string.stores_claiming else R.string.stores_get_free), enabled = !adding, main = true, modifier = leadOn) {
if (StoresState.canClaim(item)) StoresState.claim(ctx, item) { openStoreUrl(ctx, item) } else openStoreUrl(ctx, item)
}
}
item != null && item.isFree -> PrimaryButton(stringResource(R.string.stores_get_free), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
item != null -> PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
}
if (cloud && (download != null || failed != null)) {
@@ -1018,13 +1011,6 @@ internal fun FactRow(label: String, value: String, labelWidth: androidx.compose.
}
}
@Composable
internal fun catalogSize(item: CatalogItem?): Long {
val ctx = LocalContext.current
if (item != null) LaunchedEffect(item.key, item.accessible) { StoreSizes.request(ctx, item) }
return item?.let { StoreSizes.size(it) } ?: 0L
}
@Composable
internal fun diskSize(installed: InstalledStoreGame?, folder: File): Long? {
val ctx = LocalContext.current
@@ -14,7 +14,7 @@ internal enum class SessionDrawerPage(val firstControl: String) {
}
internal fun sessionDrawerPages(
hasSecondScreen: Boolean, hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentHost.installed && com.droiddeck.launcher.agent.AgentTab.shown,
hasSecondScreen: Boolean, hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentHost.installed,
): List<SessionDrawerPage> =
SessionDrawerPage.entries.filter {
(hasSecondScreen || it != SessionDrawerPage.SECOND_SCREEN) && (hasGlasses || it != SessionDrawerPage.GLASSES) &&
@@ -220,9 +220,6 @@ class DrawerActions(
val hudOn: Boolean,
val hudConfig: Map<String, String> = emptyMap(),
val frameGen: FrameGen.Mode,
val frameGenTargetGameId: String? = null,
val frameGenTargetGameName: String? = null,
val hasGameOverride: Boolean = false,
val lossless: Lossless.State,
val oscMode: String,
val suspendPolicy: String,
@@ -265,7 +262,6 @@ class DrawerActions(
val onHudReset: () -> Unit = {},
val onHudExport: () -> Unit = {},
val onFrameGenPick: (FrameGen.Mode) -> Unit,
val onFrameGenReset: () -> Unit = {},
val fpsLimit: Int = 0,
val onFpsLimit: (Int) -> Unit = {},
val onImportLossless: () -> Unit,
@@ -562,7 +558,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
Modifier.weight(1f).fillMaxWidth().padding(top = 8.dp, start = 14.dp, end = 14.dp),
inputModifier = focus.track(page, "agent-input"),
visible = open,
startTyping = false,
) else Column(
modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll.getValue(page)),
) { CompositionLocalProvider(LocalChipMinWidth provides 96.dp, LocalCompactSettings provides true) {
@@ -573,21 +568,10 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
val fgOpen = host.open == "fg"
val offLabel = stringResource(R.string.frame_gen_off)
val fgLabel = FrameGen.label(LocalContext.current, a.frameGen)
SettingsRow(
stringResource(R.string.frame_gen_title),
if (a.frameGenTargetGameId != null)
"${stringResource(R.string.frame_gen_scope_game)} · ${a.frameGenTargetGameName ?: "ID ${a.frameGenTargetGameId}"}"
else stringResource(R.string.frame_gen_scope_global),
highlighted = fgOpen
) {
SettingsRow(stringResource(R.string.frame_gen_title), null, highlighted = fgOpen) {
Box {
ValueChip(fgLabel, fgOpen, modifier = focus.track(page, "fg")) { host.open = if (fgOpen) null else "fg" }
FrameGenMenu(
host, a.frameGen, a.lossless, a.onFrameGenPick, a.onImportLossless,
gameProfileId = a.frameGenTargetGameId,
hasGameOverride = a.hasGameOverride,
onResetGame = a.onFrameGenReset,
)
FrameGenMenu(host, a.frameGen, a.lossless, a.onFrameGenPick, a.onImportLossless)
}
}
if (a.direct) SliderRow(
@@ -1367,12 +1351,6 @@ private fun SelectedGameProfileGroup(host: MenuHost, a: DrawerActions, track: (S
if (!profile.fexPreset.inherited) {
ProfileSummaryRow(stringResource(R.string.comp_game_fex), fexProfileLabel(profile.fexPreset))
}
if (!profile.frameGenInherited) {
ProfileSummaryRow(
stringResource(R.string.frame_gen_title),
FrameGen.label(LocalContext.current, profile.frameGen),
)
}
if (!profile.proton.inherited) {
ProfileSummaryRow(stringResource(R.string.comp_proton), profileValueLabel(profile.proton))
}
@@ -714,7 +714,6 @@ private fun toolDetail(t: ToolUsage): String = when (t.reason) {
ToolReason.ARM_RUNTIME -> stringResource(R.string.storage_tool_arm_runtime)
ToolReason.REDISTRIBUTABLES -> stringResource(R.string.storage_tool_redist)
ToolReason.FEX -> stringResource(R.string.storage_tool_fex)
ToolReason.ANTICHEAT_RUNTIME -> stringResource(R.string.storage_tool_anticheat)
ToolReason.STEAM_TOOL -> stringResource(R.string.storage_tool_steam)
ToolReason.OLD_RUNTIME -> stringResource(R.string.storage_tool_old_runtime)
ToolReason.X86_PROTON -> stringResource(R.string.storage_tool_x86_proton)
@@ -35,7 +35,6 @@ internal fun sourceColours(source: String): SourceColours = when (source) {
Store.BATTLENET.id -> SourceColours(Color(0xFF0A2440), Color(0xFF9DD1FF), Color(0xFF148EFF))
Store.UBISOFT.id -> SourceColours(Color(0xFF0B1E44), Color(0xFFA8C6FF), Color(0xFF2E7DFF))
Store.EA.id -> SourceColours(Color(0xFF3A0E12), Color(0xFFFF9A9A), Color(0xFFFF4747))
Store.ROCKSTAR.id -> SourceColours(Color(0xFF3A2A06), Color(0xFFFFD780), Color(0xFFFCAF17))
Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal)
else -> SourceColours(Color(0xFF1A1D22), Color(0xFF9AA3AF), Color(0xFF9AA3AF))
@@ -53,7 +52,6 @@ internal fun sourceLabel(source: String): String = when (source) {
Store.BATTLENET.id -> Store.BATTLENET.label
Store.UBISOFT.id -> Store.UBISOFT.shortLabel
Store.EA.id -> Store.EA.label
Store.ROCKSTAR.id -> Store.ROCKSTAR.shortLabel
else -> stringResource(R.string.source_added)
}
Loaded 100 of 225 files, more files were not shown because too many files have changed in this diff. Show more