mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-24 15:26:04 +00:00
chore: merge main into feat/bt-controller-trinket
This commit is contained in:
commit
33ebc24647
117 files changed
+5876
-768
No files matched your search
+8
-6
@@ -125,7 +125,8 @@ def variantSuffixes = rootProject.file('tools/release/variants.txt').readLines()
|
||||
android {
|
||||
namespace 'com.droiddeck.launcher'
|
||||
compileSdk 34
|
||||
ndkVersion project.findProperty('ndkVersion') ?: '27.3.13750724'
|
||||
ndkVersion project.findProperty('ndkVersion') ?: providers.fileContents(rootProject.layout.projectDirectory.file('tools/ci/toolchains.env'))
|
||||
.asText.get().readLines().find { it.startsWith('CI_ANDROID_NDK_VERSION=') }.split('=', 2)[1].trim()
|
||||
|
||||
defaultConfig {
|
||||
applicationId "com.droiddeck.launcher"
|
||||
@@ -232,6 +233,9 @@ android {
|
||||
}
|
||||
maxHeapSize = '2g'
|
||||
maxParallelForks = 2
|
||||
def jvmTemp = new File(temporaryDir, 'jvm')
|
||||
systemProperty 'java.io.tmpdir', jvmTemp.absolutePath
|
||||
doFirst { jvmTemp.mkdirs() }
|
||||
def logTarget = providers.systemProperty('robolectric.logging').orNull
|
||||
if (logTarget != null) systemProperty 'robolectric.logging', logTarget
|
||||
}
|
||||
@@ -261,11 +265,9 @@ if (vitureSdkDir) {
|
||||
tasks.named('preBuild').configure { dependsOn(stageVitureNotices) }
|
||||
}
|
||||
|
||||
def stageSessionScripts = tasks.register('stageSessionScripts', Copy) {
|
||||
from(rootProject.file('tools/linuxfs/overlay')) {
|
||||
include 'usr/local/bin/droiddeck-*', 'usr/local/bin/steam-compatibility', 'usr/bin/**'
|
||||
}
|
||||
into(layout.projectDirectory.dir('src/main/assets/linuxfs'))
|
||||
def stageSessionScripts = tasks.register('stageSessionScripts', Exec) {
|
||||
workingDir rootProject.projectDir
|
||||
commandLine pythonExecutable, 'tools/release/check_session_assets.py', '--stage'
|
||||
}
|
||||
tasks.named('preBuild').configure { dependsOn(stageSessionScripts) }
|
||||
|
||||
|
||||
@@ -243,6 +243,7 @@
|
||||
android:exported="false"
|
||||
android:screenOrientation="user"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:windowSoftInputMode="adjustResize"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
#define SYS_munmap 215
|
||||
#define SYS_mmap 222
|
||||
#define SYS_mprotect 226
|
||||
#define SYS_getpid 172
|
||||
|
||||
#define AT_FDCWD_ (-100)
|
||||
#define O_RDONLY_ 0
|
||||
@@ -52,6 +53,21 @@ static size_t slen(const char *s) {
|
||||
return n;
|
||||
}
|
||||
|
||||
static int seq(const char *a, const char *b) {
|
||||
while (*a && *a == *b) a++, b++;
|
||||
return *a == *b;
|
||||
}
|
||||
|
||||
static const char *env_get(char **envp, const char *name) {
|
||||
size_t n = slen(name);
|
||||
for (; *envp; envp++) {
|
||||
size_t i = 0;
|
||||
while (i < n && (*envp)[i] == name[i]) i++;
|
||||
if (i == n && (*envp)[n] == '=') return *envp + n + 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void out(const char *s) { sys6(SYS_write, 2, (long)s, (long)slen(s), 0, 0, 0); }
|
||||
|
||||
static void out_num(long v) {
|
||||
@@ -112,19 +128,43 @@ static int prot_of(uint32_t flags) {
|
||||
|
||||
static void map_failed(const char *path, long r) { die("cannot map a segment", path, r); }
|
||||
|
||||
static void load(const char *path, struct image *im, uintptr_t page) {
|
||||
static void read_interp(int fd, const Elf64_Phdr *ph, int phnum, char *interp, size_t size, const char *path) {
|
||||
interp[0] = 0;
|
||||
for (int i = 0; i < phnum; i++) {
|
||||
if (ph[i].p_type != PT_INTERP) continue;
|
||||
if (ph[i].p_filesz == 0 || ph[i].p_filesz >= size) die("bad PT_INTERP", path, 0);
|
||||
if (xpread(fd, interp, ph[i].p_filesz, (long)ph[i].p_offset) != (long)ph[i].p_filesz)
|
||||
die("truncated PT_INTERP", path, 0);
|
||||
interp[ph[i].p_filesz] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
static int read_headers(const char *path, Elf64_Ehdr *eh, Elf64_Phdr *ph) {
|
||||
int fd = (int)sys6(SYS_openat, AT_FDCWD_, (long)path, O_RDONLY_ | O_CLOEXEC_, 0, 0, 0);
|
||||
if (fd < 0) die("cannot open", path, fd);
|
||||
Elf64_Ehdr eh;
|
||||
if (xpread(fd, &eh, sizeof(eh), 0) != (long)sizeof(eh)) die("not an ELF file", path, 0);
|
||||
if (eh.e_ident[EI_MAG0] != ELFMAG0 || eh.e_ident[EI_MAG1] != ELFMAG1 || eh.e_ident[EI_MAG2] != ELFMAG2 ||
|
||||
eh.e_ident[EI_MAG3] != ELFMAG3 || eh.e_ident[EI_CLASS] != ELFCLASS64 || eh.e_machine != EM_AARCH64 ||
|
||||
(eh.e_type != ET_EXEC && eh.e_type != ET_DYN) || eh.e_phentsize != sizeof(Elf64_Phdr) ||
|
||||
eh.e_phnum == 0 || eh.e_phnum > MAX_PHDRS)
|
||||
if (xpread(fd, eh, sizeof(*eh), 0) != (long)sizeof(*eh)) die("not an ELF file", path, 0);
|
||||
if (eh->e_ident[EI_MAG0] != ELFMAG0 || eh->e_ident[EI_MAG1] != ELFMAG1 || eh->e_ident[EI_MAG2] != ELFMAG2 ||
|
||||
eh->e_ident[EI_MAG3] != ELFMAG3 || eh->e_ident[EI_CLASS] != ELFCLASS64 || eh->e_machine != EM_AARCH64 ||
|
||||
(eh->e_type != ET_EXEC && eh->e_type != ET_DYN) || eh->e_phentsize != sizeof(Elf64_Phdr) ||
|
||||
eh->e_phnum == 0 || eh->e_phnum > MAX_PHDRS)
|
||||
die("not a 64-bit ARM ELF program", path, 0);
|
||||
long size = (long)eh->e_phnum * (long)sizeof(Elf64_Phdr);
|
||||
if (xpread(fd, ph, (size_t)size, (long)eh->e_phoff) != size) die("truncated program headers", path, 0);
|
||||
return fd;
|
||||
}
|
||||
|
||||
static void interp_of(const char *path, char *interp, size_t size) {
|
||||
Elf64_Ehdr eh;
|
||||
Elf64_Phdr ph[MAX_PHDRS];
|
||||
long size = (long)eh.e_phnum * (long)sizeof(Elf64_Phdr);
|
||||
if (xpread(fd, ph, (size_t)size, (long)eh.e_phoff) != size) die("truncated program headers", path, 0);
|
||||
int fd = read_headers(path, &eh, ph);
|
||||
read_interp(fd, ph, eh.e_phnum, interp, size, path);
|
||||
sys6(SYS_close, fd, 0, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
static void load(const char *path, struct image *im, uintptr_t page) {
|
||||
Elf64_Ehdr eh;
|
||||
Elf64_Phdr ph[MAX_PHDRS];
|
||||
int fd = read_headers(path, &eh, ph);
|
||||
|
||||
uintptr_t lo = UINTPTR_MAX, hi = 0;
|
||||
for (int i = 0; i < eh.e_phnum; i++) {
|
||||
@@ -173,16 +213,9 @@ static void load(const char *path, struct image *im, uintptr_t page) {
|
||||
im->phnum = eh.e_phnum;
|
||||
im->phent = eh.e_phentsize;
|
||||
im->phdr = 0;
|
||||
im->interp[0] = 0;
|
||||
for (int i = 0; i < eh.e_phnum; i++) {
|
||||
read_interp(fd, ph, eh.e_phnum, im->interp, sizeof(im->interp), path);
|
||||
for (int i = 0; i < eh.e_phnum; i++)
|
||||
if (ph[i].p_type == PT_PHDR) im->phdr = bias + ph[i].p_vaddr;
|
||||
if (ph[i].p_type == PT_INTERP) {
|
||||
if (ph[i].p_filesz == 0 || ph[i].p_filesz >= sizeof(im->interp)) die("bad PT_INTERP", path, 0);
|
||||
if (xpread(fd, im->interp, ph[i].p_filesz, (long)ph[i].p_offset) != (long)ph[i].p_filesz)
|
||||
die("truncated PT_INTERP", path, 0);
|
||||
im->interp[ph[i].p_filesz] = 0;
|
||||
}
|
||||
}
|
||||
if (!im->phdr) {
|
||||
for (int i = 0; i < eh.e_phnum; i++) {
|
||||
Elf64_Phdr *p = &ph[i];
|
||||
@@ -202,6 +235,36 @@ static unsigned long auxv_get(const uintptr_t *auxv, unsigned long type, unsigne
|
||||
return fallback;
|
||||
}
|
||||
|
||||
static int is_self_exe(const char *execfn) {
|
||||
if (!execfn) return 0;
|
||||
if (seq(execfn, "/proc/self/exe") || seq(execfn, "/proc/thread-self/exe")) return 1;
|
||||
const char *p = "/proc/";
|
||||
while (*p && *p == *execfn) p++, execfn++;
|
||||
if (*p) return 0;
|
||||
char num[24];
|
||||
int i = (int)sizeof(num) - 1;
|
||||
num[i] = 0;
|
||||
unsigned long pid = (unsigned long)sys6(SYS_getpid, 0, 0, 0, 0, 0, 0);
|
||||
do {
|
||||
num[--i] = (char)('0' + pid % 10);
|
||||
pid /= 10;
|
||||
} while (pid && i > 0);
|
||||
const char *d = num + i;
|
||||
while (*d && *d == *execfn) d++, execfn++;
|
||||
return !*d && seq(execfn, "/exe");
|
||||
}
|
||||
|
||||
static const char *guest_interp(char **envp, const char *interp, char *buf, size_t size) {
|
||||
const char *root = env_get(envp, "DDNATV_ROOT");
|
||||
if (!root || interp[0] != '/') return interp;
|
||||
size_t a = slen(root), b = slen(interp);
|
||||
if (a + b + 1 > size) return interp;
|
||||
for (size_t i = 0; i < a; i++) buf[i] = root[i];
|
||||
for (size_t i = 0; i <= b; i++) buf[a + i] = interp[i];
|
||||
if (sys6(SYS_faccessat, AT_FDCWD_, (long)buf, 0, 0, 0, 0) != 0) return interp;
|
||||
return buf;
|
||||
}
|
||||
|
||||
__attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) {
|
||||
long argc = (long)sp[0];
|
||||
char **argv = (char **)(sp + 1);
|
||||
@@ -211,25 +274,66 @@ __attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) {
|
||||
uintptr_t *auxv = (uintptr_t *)(envp + nenv + 1);
|
||||
long naux = 0;
|
||||
while (auxv[naux * 2] != AT_NULL) naux++;
|
||||
if (argc < 3) die("usage: libddexec.so <file> <argv0> [args...]", 0, 0);
|
||||
int reexec = is_self_exe((const char *)auxv_get(auxv, AT_EXECFN, 0));
|
||||
const char *path;
|
||||
char **args = argv + 2;
|
||||
long nargs = argc - 2;
|
||||
char interp_buf[4096];
|
||||
char hook_buf[4096];
|
||||
if (reexec) {
|
||||
path = env_get(envp, "DDNATV_REAL_EXE");
|
||||
if (!path || !path[0]) die("re-executed without DDNATV_REAL_EXE", 0, 0);
|
||||
args = argv;
|
||||
nargs = argc;
|
||||
const char *lib_path = env_get(envp, "DDNATV_LIBRARY_PATH");
|
||||
char prog_interp[256];
|
||||
interp_of(path, prog_interp, sizeof(prog_interp));
|
||||
if (prog_interp[0] && lib_path && lib_path[0]) {
|
||||
const char *ld_so = guest_interp(envp, prog_interp, interp_buf, sizeof(interp_buf));
|
||||
const char *hook = guest_interp(envp, "/usr/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf));
|
||||
if (hook != (const char *)hook_buf) hook = guest_interp(envp, "/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf));
|
||||
long n = argc > 1 ? argc - 1 : 0;
|
||||
char **v = (char **)__builtin_alloca((size_t)(n + 9) * sizeof(char *));
|
||||
long k = 0;
|
||||
v[k++] = (char *)ld_so;
|
||||
if (hook == (const char *)hook_buf) {
|
||||
v[k++] = (char *)"--preload";
|
||||
v[k++] = (char *)hook;
|
||||
}
|
||||
v[k++] = (char *)"--library-path";
|
||||
v[k++] = (char *)lib_path;
|
||||
v[k++] = (char *)"--argv0";
|
||||
v[k++] = argc > 0 ? argv[0] : (char *)path;
|
||||
v[k++] = (char *)path;
|
||||
for (long i = 0; i < n; i++) v[k++] = argv[1 + i];
|
||||
v[k] = 0;
|
||||
args = v;
|
||||
nargs = k;
|
||||
path = ld_so;
|
||||
}
|
||||
} else if (argc < 3) {
|
||||
die("usage: libddexec.so <file> <argv0> [args...]", 0, 0);
|
||||
} else {
|
||||
path = argv[1];
|
||||
}
|
||||
|
||||
uintptr_t page = auxv_get(auxv, AT_PAGESZ, 4096);
|
||||
const char *path = argv[1];
|
||||
struct image prog, interp;
|
||||
load(path, &prog, page);
|
||||
int has_interp = prog.interp[0] != 0;
|
||||
if (has_interp) load(prog.interp, &interp, page);
|
||||
if (has_interp) load(reexec ? guest_interp(envp, prog.interp, interp_buf, sizeof(interp_buf)) : prog.interp, &interp, page);
|
||||
|
||||
// The new stack: argc, argv, envp and auxv as the kernel lays them out, below the current one.
|
||||
// The strings stay where the kernel put them.
|
||||
static const unsigned long replaced[] = {AT_PHDR, AT_PHENT, AT_PHNUM, AT_BASE, AT_ENTRY, AT_EXECFN};
|
||||
long nreplaced = (long)(sizeof(replaced) / sizeof(replaced[0]));
|
||||
long new_argc = argc - 2;
|
||||
long new_argc = nargs;
|
||||
long words = 1 + (new_argc + 1) + (nenv + 1) + (naux + nreplaced + 1) * 2;
|
||||
uintptr_t *nsp = (uintptr_t *)(((uintptr_t)sp - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15);
|
||||
uintptr_t top = (uintptr_t)args < (uintptr_t)sp ? (uintptr_t)args : (uintptr_t)sp;
|
||||
uintptr_t *nsp = (uintptr_t *)((top - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15);
|
||||
uintptr_t *w = nsp;
|
||||
*w++ = (uintptr_t)new_argc;
|
||||
for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)argv[i + 2];
|
||||
for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)args[i];
|
||||
*w++ = 0;
|
||||
for (long i = 0; i < nenv; i++) *w++ = (uintptr_t)envp[i];
|
||||
*w++ = 0;
|
||||
|
||||
@@ -21,6 +21,7 @@ class App : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
com.droiddeck.launcher.runtime.NativeGuest.init(this)
|
||||
com.droiddeck.launcher.session.Onboarding.attach(this)
|
||||
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
|
||||
com.droiddeck.launcher.ui.Themes.loadGradient(this)
|
||||
com.droiddeck.launcher.ui.BuildWatermark.install(this)
|
||||
|
||||
@@ -79,7 +79,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
|
||||
checkAgain = null
|
||||
checkComponentUpdates(again)
|
||||
}
|
||||
if (notes.isNotEmpty()) android.widget.Toast.makeText(activity, notes.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show()
|
||||
if (notes.isNotEmpty()) Log.i(TAG, notes.joinToString("; "))
|
||||
refreshComponents()
|
||||
}
|
||||
}, "component-updates").start()
|
||||
|
||||
@@ -254,6 +254,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, WifiDiscovery.permissionGranted(this))
|
||||
refreshWifiDiscovery()
|
||||
}
|
||||
private val bluetoothPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (!granted && !shouldShowRequestPermissionRationale(android.Manifest.permission.BLUETOOTH_CONNECT)) {
|
||||
integrationSettings(SteamIntegration.appInfo(this))
|
||||
}
|
||||
integrationState = readIntegration()
|
||||
}
|
||||
private val cameraPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
|
||||
com.droiddeck.launcher.handtracking.HandTracking.refreshPermission(this)
|
||||
}
|
||||
@@ -375,6 +381,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
SteamIntegration.Feature.SHORTCUTS -> {
|
||||
if (integrationState.shortcuts) openShortcutSettings() else installShortcuts()
|
||||
}
|
||||
SteamIntegration.Feature.BLUETOOTH -> {
|
||||
if (SteamIntegration.bluetoothAllowed(this)) integrationSettings(SteamIntegration.appInfo(this))
|
||||
else bluetoothPermission.launch(android.Manifest.permission.BLUETOOTH_CONNECT)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2166,9 +2176,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
if (!OfflineMode.enabled(this)) {
|
||||
val updated = runCatching { ComponentUpdater.ensure(this, force = false) }
|
||||
.onFailure { android.util.Log.w("ComponentUpdater", "automatic component updates", it) }.getOrDefault(emptyList())
|
||||
if (updated.isNotEmpty()) ui.post {
|
||||
android.widget.Toast.makeText(this, updated.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
if (updated.isNotEmpty()) android.util.Log.i("ComponentUpdater", updated.joinToString("; "))
|
||||
}
|
||||
ui.post {
|
||||
componentsQueueBusy = false
|
||||
@@ -3209,6 +3217,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
|
||||
removalPending = LinuxRuntimeInstaller.hasRemovalPending(this)
|
||||
ui.post { autoUpdateRuntime() }
|
||||
Thread({ com.droiddeck.launcher.session.Onboarding.recheck(this) }, "onboarding-recheck").start()
|
||||
frameGenLabel = FrameGen.label(this)
|
||||
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
|
||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||
@@ -3430,18 +3439,24 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
|
||||
private fun install(release: LinuxRuntimeInstaller.Release) {
|
||||
com.droiddeck.launcher.runtime.RuntimeInstallService.start(this, release)
|
||||
followRuntimeOperation { listener -> LinuxRuntimeInstaller.install(this, release, listener) }
|
||||
followRuntimeOperation(onboarding = true) { listener -> LinuxRuntimeInstaller.install(this, release, listener) }
|
||||
}
|
||||
|
||||
private fun followRuntimeOperation(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
|
||||
private fun followRuntimeOperation(onboarding: Boolean = false, run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
|
||||
busy = true
|
||||
failed = false
|
||||
stage = getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (LinuxRuntimeInstaller.isRemoving()) R.string.main_removing_runtime else R.string.store_starting)
|
||||
percent = -1
|
||||
Thread({
|
||||
val ok = run(LinuxRuntimeInstaller.ProgressListener { s, p ->
|
||||
if (onboarding) com.droiddeck.launcher.session.Onboarding.report(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME, s, p)
|
||||
ui.post { stage = s; percent = p }
|
||||
})
|
||||
if (onboarding) {
|
||||
if (ok == false) com.droiddeck.launcher.session.Onboarding.fail(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME, LinuxRuntimeInstaller.removalError() ?: "")
|
||||
else com.droiddeck.launcher.session.Onboarding.finish(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME)
|
||||
}
|
||||
com.droiddeck.launcher.session.Onboarding.recheck(this)
|
||||
ui.post {
|
||||
busy = false
|
||||
if (ok != null) failed = !ok
|
||||
@@ -3450,7 +3465,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
refresh()
|
||||
com.droiddeck.launcher.agent.AgentHost.refresh(this)
|
||||
if (ok == true && LinuxRuntime.isInstalled(this)) protons.checkUpdates()
|
||||
if (ok == true && LinuxRuntime.isInstalled(this)) { protons.checkUpdates(); protons.ensureSteamClient() }
|
||||
}
|
||||
}, "runtime-operation").start()
|
||||
}
|
||||
@@ -3461,9 +3476,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
if (installed != null) com.droiddeck.launcher.runtime.RuntimeAutoUpdate.seed(this)
|
||||
if (release.version == installed) return
|
||||
if (installed == null && (OfflineMode.enabled(this) || !com.droiddeck.launcher.core.DeviceSupport.canDraw(this) ||
|
||||
!com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.unfavourable(this))) return
|
||||
!com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.firstRunHeldBack(this))) return
|
||||
if (com.droiddeck.launcher.runtime.RuntimeAutoUpdate.claim(this, installed, release.version)) {
|
||||
Log.i(TAG, "runtime: installing ${release.version} over ${installed ?: "nothing"} by itself")
|
||||
if (installed == null) protons.prefetchOwn()
|
||||
install(release)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,9 @@ import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.session.ExperimentalProtons
|
||||
import com.droiddeck.launcher.session.Onboarding
|
||||
import com.droiddeck.launcher.session.ProtonExtras
|
||||
import com.droiddeck.launcher.session.SteamClientPrefetch
|
||||
import com.droiddeck.launcher.ui.ProtonRow
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
@@ -60,10 +62,15 @@ internal class ProtonMenu(
|
||||
Thread({
|
||||
val problem = runCatching {
|
||||
installer(tool) { label, value ->
|
||||
if (tool.id == ProtonExtras.OWN) Onboarding.report(Onboarding.Step.PROTON, label, value)
|
||||
ui.post { protonStage = label; protonPercent = value }
|
||||
}
|
||||
}.getOrElse { it.message ?: it.javaClass.simpleName }
|
||||
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
|
||||
if (tool.id == ProtonExtras.OWN) {
|
||||
if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem)
|
||||
Onboarding.recheck(activity)
|
||||
}
|
||||
ui.post {
|
||||
protonProblem = problem
|
||||
protonBusyId = null
|
||||
@@ -170,16 +177,46 @@ internal class ProtonMenu(
|
||||
Operation.checking.set(false)
|
||||
}
|
||||
ensureAutoUpdates()
|
||||
ensureSteamClient()
|
||||
}
|
||||
if (!published) Operation.checking.set(false)
|
||||
}, "proton-updates").start()
|
||||
}
|
||||
|
||||
/** Downloads the DroidDeck Proton archive while the runtime installs; the install step later finds it whole. */
|
||||
fun prefetchOwn() {
|
||||
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
||||
if (ProtonExtras.declined(activity) || ProtonExtras.installedAll(activity, tool).isNotEmpty() ||
|
||||
ProtonExtras.installInProgress || !AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity)) return
|
||||
Thread({
|
||||
val problem = runCatching {
|
||||
ProtonExtras.prefetch(activity, tool) { label, value -> Onboarding.report(Onboarding.Step.PROTON, label, value) }
|
||||
}.getOrElse { it.message ?: it.javaClass.simpleName }
|
||||
if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem)
|
||||
Onboarding.recheck(activity)
|
||||
ui.post { ensureAutoUpdates() }
|
||||
}, "proton-prefetch").start()
|
||||
}
|
||||
|
||||
/** Fetches Steam's client in the background once the runtime exists, so the first Play does not wait for it. */
|
||||
fun ensureSteamClient() {
|
||||
if (activity.isFinishing || activity.isDestroyed || !idle() || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
|
||||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) || !LinuxRuntime.isInstalled(activity) ||
|
||||
!AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity) || SteamClientPrefetch.running()) return
|
||||
SteamClientPrefetch.start(
|
||||
activity,
|
||||
{ mb -> activity.getString(if (mb > 0) R.string.onboarding_steam_downloading_mb else R.string.onboarding_steam_downloading, mb) },
|
||||
activity.getString(R.string.onboarding_steam_failed),
|
||||
)
|
||||
}
|
||||
|
||||
internal fun ensureAutoUpdates(now: Long = System.currentTimeMillis()) {
|
||||
if (activity.isFinishing || activity.isDestroyed || !idle() || protonBusyId != null ||
|
||||
ProtonExtras.installInProgress || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
|
||||
ProtonExtras.installInProgress || ProtonExtras.prefetching || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
|
||||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
|
||||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
|
||||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity)) return
|
||||
val firstInstall = !ProtonExtras.declined(activity) && ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).isEmpty()
|
||||
if (if (firstInstall) AutoComponents.firstRunHeldBack(activity) else AutoComponents.unfavourable(activity)) return
|
||||
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
|
||||
protonBusyId = ProtonExtras.OWN
|
||||
protonProblem = null
|
||||
|
||||
@@ -154,6 +154,8 @@ import com.droiddeck.launcher.session.ComponentsManager
|
||||
import com.droiddeck.launcher.session.LatestRequestCoordinator
|
||||
import com.droiddeck.launcher.ui.SessionDrawerPage
|
||||
import com.droiddeck.launcher.ui.sessionDrawerPages
|
||||
import com.droiddeck.launcher.ui.strip
|
||||
import com.droiddeck.launcher.ui.tabFor
|
||||
import com.droiddeck.launcher.ui.step
|
||||
import kotlin.math.abs
|
||||
|
||||
@@ -594,6 +596,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private var backHold by mutableStateOf(true)
|
||||
private var dockedMenuController by mutableStateOf(false)
|
||||
private var sessionOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
|
||||
private var dualScreenSessionMode by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO)
|
||||
private var backActionsInverted by mutableStateOf(false)
|
||||
private var backDoubleTapMs by mutableStateOf(500)
|
||||
private var lowLatency by mutableStateOf(true)
|
||||
@@ -933,11 +936,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
SteamControllerBle.listener = { uiHandler.post { updatePadMotion(); refreshControls() } }
|
||||
steamController = SteamControllerBle(this, inputRouter).also { it.start() }
|
||||
if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(BLUETOOTH_CONNECT) != android.content.pm.PackageManager.PERMISSION_GRANTED &&
|
||||
!SessionPrefs.bluetoothAsked(this)) {
|
||||
SessionPrefs.setBluetoothAsked(this)
|
||||
requestPermissions(arrayOf(BLUETOOTH_CONNECT), REQUEST_BLUETOOTH)
|
||||
}
|
||||
padMotion = com.droiddeck.launcher.input.PadMotion(this) {
|
||||
@Suppress("DEPRECATION")
|
||||
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
|
||||
@@ -1535,6 +1533,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
fexPreset = fexPreset,
|
||||
secondScreenMode = secondScreenMode,
|
||||
secondScreenNone = !bottomOutputActive && !dockDrawer(),
|
||||
dualScreenMode = dualScreenSessionMode,
|
||||
onDualScreenMode = ::chooseDualScreenSessionMode,
|
||||
gameOnBottom = bottomOutputActive,
|
||||
gameSwapAvailable = bottomSwapAvailable,
|
||||
gameSwapBuiltIn = !::displayManager.isInitialized || displayManager.getDisplay(selectedSecondScreenDisplay)
|
||||
@@ -2659,6 +2659,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
backHold = SessionPrefs.backHold(this)
|
||||
dockedMenuController = SessionPrefs.dockedMenuController(this)
|
||||
sessionOrientation = SessionPrefs.orientation(this)
|
||||
dualScreenSessionMode = SessionPrefs.dualScreenSessionMode(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
physicalShortcuts.bindings = PhysicalShortcuts.read(this)
|
||||
backDoubleTapMs = SessionPrefs.backDoubleTapMs(this)
|
||||
@@ -3664,8 +3665,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (drawerOpen && (menuOwnsController || (!fromController && !(dockedTouchOnly && event.keyCode == KeyEvent.KEYCODE_BACK)))) {
|
||||
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
drawerPage = sessionDrawerPages(glasses.present)
|
||||
.step(drawerPage, if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
|
||||
// The bumpers walk the tabs on the strip; a page kept inside More counts as the More tab.
|
||||
val pages = sessionDrawerPages(glasses.present)
|
||||
drawerPage = pages.strip().step(pages.tabFor(drawerPage), if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
|
||||
releaseDrawerDirection()
|
||||
}
|
||||
return true
|
||||
@@ -4396,6 +4398,27 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
} else if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal()
|
||||
}
|
||||
|
||||
private fun chooseDualScreenSessionMode(mode: String) {
|
||||
if (mode !in com.droiddeck.launcher.input.DualScreen.modes || mode == dualScreenSessionMode) return
|
||||
SessionPrefs.setDualScreenSessionMode(this, mode)
|
||||
dualScreenSessionMode = mode
|
||||
SessionState.secondScreenAutoOpened = false
|
||||
val menuOnBottom = drawerDocked
|
||||
val menuOnTop = drawerOpenState && !drawerDocked
|
||||
if (mode == com.droiddeck.launcher.input.DualScreen.MODE_OFF) {
|
||||
if (gameOnBottom) putGameOnBottom(false)
|
||||
if (secondScreenMode != SecondScreenMode.NONE || menuOnBottom) closeSecondScreen(reset = true)
|
||||
if (menuOnBottom) drawerOpen = true
|
||||
} else if (menuOnTop) {
|
||||
// The menu moves to the second screen as the menu itself, not as one of the control panels.
|
||||
SessionState.secondScreenAutoOpened = true
|
||||
refreshSecondScreenDisplays()
|
||||
pinDockedMenu()
|
||||
return
|
||||
}
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
|
||||
private fun selectSecondScreenDisplay(displayId: Int) {
|
||||
if (secondScreenDisplays.none { it.id == displayId }) return
|
||||
selectedSecondScreenDisplay = displayId
|
||||
@@ -5958,7 +5981,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (secondScreenPresentation == null) showSecondScreen(secondScreenMode)
|
||||
if (com.droiddeck.launcher.input.DualScreen.menuReturnsOnStart(openingPanel(), SessionState.bottomMenu, menuShownOnBottom())) pinDockedMenu()
|
||||
SessionState.bottomMenu = false
|
||||
} else openDualScreenControls()
|
||||
} else {
|
||||
if (SessionState.bottomMenu && !menuShownOnBottom()) pinDockedMenu()
|
||||
SessionState.bottomMenu = false
|
||||
if (!menuShownOnBottom()) openDualScreenControls()
|
||||
}
|
||||
startedScreens++
|
||||
SessionService.setActivityVisible(this, true, sessionActivityDisplayId)
|
||||
Glasses.rescan()
|
||||
|
||||
@@ -16,7 +16,7 @@ object SteamIntegration {
|
||||
const val EXTRA_FEATURE = "integration_feature"
|
||||
const val SHORTCUTS_STATUS = "com.droiddeck.launcher.SHORTCUTS_INSTALL_STATUS"
|
||||
private const val SHORTCUTS_ASSET = "shortcuts.apk"
|
||||
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS }
|
||||
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS, BLUETOOTH }
|
||||
|
||||
data class State(
|
||||
val wifi: Boolean = false,
|
||||
@@ -28,6 +28,7 @@ object SteamIntegration {
|
||||
val shortcuts: Boolean = false,
|
||||
val shortcutsRestricted: Boolean = false,
|
||||
val shortcutsTried: Boolean = false,
|
||||
val bluetooth: Boolean = false,
|
||||
val suggested: Boolean = true,
|
||||
)
|
||||
|
||||
@@ -39,9 +40,16 @@ object SteamIntegration {
|
||||
home = HomeApp.isDefault(context),
|
||||
shortcuts = shortcutsEnabled(context) && shortcutsCurrent(context),
|
||||
shortcutsRestricted = restrictedSettings(context),
|
||||
bluetooth = bluetoothAllowed(context),
|
||||
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
|
||||
)
|
||||
|
||||
fun bluetoothAllowed(context: Context): Boolean =
|
||||
android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.S ||
|
||||
context.checkSelfPermission(android.Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
fun appInfo(context: Context) = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}"))
|
||||
|
||||
private fun restrictedSettings(context: Context): Boolean {
|
||||
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
|
||||
val mode = runCatching {
|
||||
|
||||
@@ -28,6 +28,7 @@ import androidx.compose.material.icons.filled.ArrowUpward
|
||||
import androidx.compose.material.icons.filled.Checklist
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.FileCopy
|
||||
import androidx.compose.material.icons.filled.FileOpen
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.InsertDriveFile
|
||||
@@ -101,8 +102,18 @@ private fun FileContextMenuItems(
|
||||
onToggleFavorite: () -> Unit,
|
||||
onProperties: () -> Unit,
|
||||
onDismissMenu: () -> Unit,
|
||||
onOpen: () -> Unit,
|
||||
) {
|
||||
val isDir = file.isDirectory
|
||||
if (!isDir) {
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.fm_edit_open)) },
|
||||
leadingIcon = { Icon(Icons.Filled.FileOpen, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
onClick = { onDismissMenu(); onOpen() },
|
||||
modifier = Modifier.focusGlide(),
|
||||
)
|
||||
MenuItemDivider()
|
||||
}
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.fm_select)) },
|
||||
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
|
||||
@@ -180,6 +191,7 @@ internal fun FileItemRow(
|
||||
onCut: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
onRename: () -> Unit,
|
||||
onOpen: () -> Unit = {},
|
||||
isFavorite: Boolean = false,
|
||||
onToggleFavorite: () -> Unit = {},
|
||||
onProperties: () -> Unit = {},
|
||||
@@ -291,6 +303,7 @@ internal fun FileItemRow(
|
||||
file = file,
|
||||
isFavorite = isFavorite,
|
||||
onSelect = onSelect,
|
||||
onOpen = onOpen,
|
||||
onRename = onRename,
|
||||
onCopy = onCopy,
|
||||
onCut = onCut,
|
||||
@@ -517,6 +530,7 @@ internal fun FileGridTile(
|
||||
isFavorite: Boolean = false,
|
||||
onSelect: () -> Unit = {},
|
||||
onRename: () -> Unit = {},
|
||||
onOpen: () -> Unit = {},
|
||||
onCopy: () -> Unit = {},
|
||||
onCut: () -> Unit = {},
|
||||
onDelete: () -> Unit = {},
|
||||
@@ -605,6 +619,7 @@ internal fun FileGridTile(
|
||||
file = file,
|
||||
isFavorite = isFavorite,
|
||||
onSelect = onSelect,
|
||||
onOpen = onOpen,
|
||||
onRename = onRename,
|
||||
onCopy = onCopy,
|
||||
onCut = onCut,
|
||||
|
||||
@@ -191,6 +191,7 @@ fun FileManagerScreen(
|
||||
var compactRows by remember { mutableStateOf(browsePrefs.getBoolean("fmCompactRows", false)) }
|
||||
var showNewFolderDialog by remember { mutableStateOf(false) }
|
||||
var renameTarget by remember { mutableStateOf<File?>(null) }
|
||||
var editingTarget by remember { mutableStateOf<File?>(null) }
|
||||
var propertiesTarget by remember { mutableStateOf<File?>(null) }
|
||||
var isOperationRunning by remember { mutableStateOf(false) }
|
||||
var operationLabel by remember { mutableStateOf("") }
|
||||
@@ -294,7 +295,7 @@ fun FileManagerScreen(
|
||||
if (isOperationActive()) pendingNavigation = action else navigate(action)
|
||||
}
|
||||
|
||||
BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty()) {
|
||||
BackHandler(enabled = editingTarget == null && (operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty())) {
|
||||
requestNavigation(FileManagerNavigation.BACK)
|
||||
}
|
||||
|
||||
@@ -696,6 +697,14 @@ fun FileManagerScreen(
|
||||
|
||||
val compactToolbar = LocalConfiguration.current.screenWidthDp < 600
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
editingTarget?.let { target ->
|
||||
TextEditorScreen(
|
||||
file = target,
|
||||
onExit = { editingTarget = null },
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
return@Column
|
||||
}
|
||||
if (pickMode && !pickerTitle.isNullOrEmpty()) {
|
||||
Text(
|
||||
text = pickerTitle,
|
||||
@@ -1194,6 +1203,8 @@ fun FileManagerScreen(
|
||||
pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply()
|
||||
onPick?.invoke(file)
|
||||
}
|
||||
} else {
|
||||
editingTarget = file
|
||||
}
|
||||
},
|
||||
onMenu = { showMenuFor = file },
|
||||
@@ -1205,6 +1216,7 @@ fun FileManagerScreen(
|
||||
selectedPaths = selectedPaths + file.absolutePath
|
||||
showMenuFor = null
|
||||
},
|
||||
onOpen = { editingTarget = file; showMenuFor = null },
|
||||
onRename = { renameTarget = file; showMenuFor = null },
|
||||
onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null },
|
||||
onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null },
|
||||
@@ -1273,6 +1285,8 @@ fun FileManagerScreen(
|
||||
pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply()
|
||||
onPick?.invoke(file)
|
||||
}
|
||||
} else {
|
||||
editingTarget = file
|
||||
}
|
||||
},
|
||||
onMenu = { showMenuFor = file },
|
||||
@@ -1286,6 +1300,7 @@ fun FileManagerScreen(
|
||||
onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null },
|
||||
onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null },
|
||||
onDelete = { selectedEntry = file; showMenuFor = null },
|
||||
onOpen = { editingTarget = file; showMenuFor = null },
|
||||
onRename = { renameTarget = file; showMenuFor = null },
|
||||
isFavorite = isFav,
|
||||
onToggleFavorite = {
|
||||
|
||||
@@ -0,0 +1,726 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.ScrollState
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
||||
import androidx.compose.material.icons.filled.Save
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.TextRange
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.TextFieldValue
|
||||
import androidx.compose.ui.text.rememberTextMeasurer
|
||||
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 com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.ui.focusGlide
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.File
|
||||
import java.io.InputStream
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.charset.CharacterCodingException
|
||||
import java.nio.charset.Charset
|
||||
import java.nio.charset.CodingErrorAction
|
||||
import java.nio.file.Files
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
internal const val EDITOR_FONT_SIZE_SP = 13
|
||||
internal const val EDITOR_LINE_HEIGHT_SP = 18
|
||||
internal const val EDITOR_TAB_WIDTH = 4
|
||||
internal const val EDITOR_MAX_OPEN_BYTES = 4L * 1024 * 1024
|
||||
internal const val EDITOR_MAX_EDIT_BYTES = 512L * 1024
|
||||
|
||||
internal enum class EditorCharset(val label: String, private val charsetName: String) {
|
||||
UTF8("UTF-8", "UTF-8"),
|
||||
GB18030("GB18030", "GB18030"),
|
||||
;
|
||||
|
||||
val charset: Charset get() = Charset.forName(charsetName)
|
||||
}
|
||||
|
||||
internal enum class EditorLock { NONE, BINARY, TOO_LARGE, PERMISSION, LOSSY }
|
||||
|
||||
internal enum class EditorLoadState { LOADING, READY, TOO_LARGE, UNREADABLE }
|
||||
|
||||
internal data class DecodedEditorText(val text: String, val charset: EditorCharset, val lossy: Boolean)
|
||||
|
||||
internal fun editorIsBinary(bytes: ByteArray, sample: Int = 8192): Boolean {
|
||||
val limit = minOf(bytes.size, sample)
|
||||
for (i in 0 until limit) if (bytes[i].toInt() == 0) return true
|
||||
return false
|
||||
}
|
||||
|
||||
private fun strictDecode(bytes: ByteArray, charset: Charset): String? = try {
|
||||
charset.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT)
|
||||
.decode(ByteBuffer.wrap(bytes))
|
||||
.toString()
|
||||
} catch (e: CharacterCodingException) {
|
||||
null
|
||||
}
|
||||
|
||||
internal fun decodeEditorText(bytes: ByteArray): DecodedEditorText {
|
||||
strictDecode(bytes, Charsets.UTF_8)?.let { return DecodedEditorText(it, EditorCharset.UTF8, false) }
|
||||
strictDecode(bytes, EditorCharset.GB18030.charset)?.let { return DecodedEditorText(it, EditorCharset.GB18030, false) }
|
||||
return DecodedEditorText(String(bytes, Charsets.UTF_8), EditorCharset.UTF8, true)
|
||||
}
|
||||
|
||||
internal fun resolveEditorSaveTarget(file: File): File {
|
||||
val isLink = runCatching { Files.isSymbolicLink(file.toPath()) }.getOrDefault(false)
|
||||
if (!isLink) return file
|
||||
// rename(2) replaces the link itself, so stage next to and rename onto the real target
|
||||
return runCatching { file.canonicalFile }.getOrDefault(file)
|
||||
}
|
||||
|
||||
internal fun readCapped(input: InputStream, limit: Long): ByteArray? {
|
||||
val out = ByteArrayOutputStream()
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
var total = 0L
|
||||
while (true) {
|
||||
val n = input.read(buffer)
|
||||
if (n < 0) return out.toByteArray()
|
||||
total += n
|
||||
if (total > limit) return null
|
||||
out.write(buffer, 0, n)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun expandEditorTabs(text: String, width: Int = EDITOR_TAB_WIDTH): String {
|
||||
if (text.indexOf('\t') < 0) return text
|
||||
val out = StringBuilder(text.length)
|
||||
var column = 0
|
||||
for (c in text) {
|
||||
when (c) {
|
||||
'\n' -> {
|
||||
out.append(c)
|
||||
column = 0
|
||||
}
|
||||
'\t' -> {
|
||||
val pad = width - (column % width)
|
||||
repeat(pad) { out.append(' ') }
|
||||
column += pad
|
||||
}
|
||||
else -> {
|
||||
out.append(c)
|
||||
column++
|
||||
}
|
||||
}
|
||||
}
|
||||
return out.toString()
|
||||
}
|
||||
|
||||
internal fun lineCountOf(text: String): Int {
|
||||
var lines = 1
|
||||
for (i in text.indices) if (text[i] == '\n') lines++
|
||||
return lines
|
||||
}
|
||||
|
||||
internal fun lineIndexOfOffset(text: String, offset: Int): Int {
|
||||
val end = offset.coerceIn(0, text.length)
|
||||
var line = 0
|
||||
var i = 0
|
||||
while (i < end) {
|
||||
if (text[i] == '\n') line++
|
||||
i++
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
internal fun columnOfOffset(text: String, offset: Int): Int {
|
||||
val end = offset.coerceIn(0, text.length)
|
||||
var start = end
|
||||
while (start > 0 && text[start - 1] != '\n') start--
|
||||
return end - start + 1
|
||||
}
|
||||
|
||||
internal fun findEditorMatches(
|
||||
text: String,
|
||||
query: String,
|
||||
matchCase: Boolean = false,
|
||||
limit: Int = 10000,
|
||||
): List<IntRange> {
|
||||
if (query.isEmpty()) return emptyList()
|
||||
val out = ArrayList<IntRange>()
|
||||
var at = 0
|
||||
while (out.size < limit) {
|
||||
val found = text.indexOf(query, at, ignoreCase = !matchCase)
|
||||
if (found < 0) break
|
||||
out.add(found until found + query.length)
|
||||
at = found + query.length
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
internal fun replaceEditorMatches(text: String, matches: List<IntRange>, replacement: String): String {
|
||||
if (matches.isEmpty()) return text
|
||||
val out = StringBuilder(text.length)
|
||||
var cursor = 0
|
||||
for (m in matches) {
|
||||
if (m.first < cursor || m.last >= text.length) continue
|
||||
out.append(text, cursor, m.first).append(replacement)
|
||||
cursor = m.last + 1
|
||||
}
|
||||
out.append(text, cursor, text.length)
|
||||
return out.toString()
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun TextEditorScreen(
|
||||
file: File,
|
||||
onExit: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val density = LocalDensity.current
|
||||
|
||||
var text by remember { mutableStateOf("") }
|
||||
var selection by remember { mutableStateOf(TextRange.Zero) }
|
||||
var composing by remember { mutableStateOf<TextRange?>(null) }
|
||||
var loadState by remember { mutableStateOf(EditorLoadState.LOADING) }
|
||||
var lock by remember { mutableStateOf(EditorLock.NONE) }
|
||||
var charset by remember { mutableStateOf(EditorCharset.UTF8) }
|
||||
var dirty by remember { mutableStateOf(false) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
var showDiscard by remember { mutableStateOf(false) }
|
||||
var showSearch by remember { mutableStateOf(false) }
|
||||
var query by remember { mutableStateOf("") }
|
||||
var replacement by remember { mutableStateOf("") }
|
||||
var matchCase by remember { mutableStateOf(false) }
|
||||
var matchIndex by remember { mutableIntStateOf(0) }
|
||||
|
||||
val scrollState = rememberScrollState()
|
||||
val textHorizontalState = rememberScrollState()
|
||||
var viewportHeight by remember { mutableIntStateOf(0) }
|
||||
var viewportWidth by remember { mutableIntStateOf(0) }
|
||||
|
||||
val lineHeightDp = with(density) { EDITOR_LINE_HEIGHT_SP.sp.toDp() }
|
||||
val lineHeightPx = with(density) { lineHeightDp.toPx() }
|
||||
val totalLines = remember(text) { lineCountOf(text) }
|
||||
val cursorLine = lineIndexOfOffset(text, selection.end)
|
||||
val cursorColumn = columnOfOffset(text, selection.end)
|
||||
val matches = remember(text, query, matchCase) { findEditorMatches(text, query, matchCase) }
|
||||
val readOnly = lock != EditorLock.NONE
|
||||
val bodyStyle = TextStyle(
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = EDITOR_FONT_SIZE_SP.sp,
|
||||
lineHeight = EDITOR_LINE_HEIGHT_SP.sp,
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
)
|
||||
val textMeasurer = rememberTextMeasurer()
|
||||
val charWidthPx = remember(bodyStyle) { textMeasurer.measure(text = "0", style = bodyStyle).size.width.toFloat() }
|
||||
|
||||
LaunchedEffect(file) {
|
||||
loadState = EditorLoadState.LOADING
|
||||
val size = withContext(Dispatchers.IO) { file.length() }
|
||||
if (size > EDITOR_MAX_OPEN_BYTES) {
|
||||
loadState = EditorLoadState.TOO_LARGE
|
||||
return@LaunchedEffect
|
||||
}
|
||||
val read = withContext(Dispatchers.IO) {
|
||||
runCatching { file.inputStream().use { readCapped(it, EDITOR_MAX_OPEN_BYTES) } }
|
||||
}
|
||||
val bytes = read.getOrNull()
|
||||
if (bytes == null) {
|
||||
loadState = if (read.isFailure) EditorLoadState.UNREADABLE else EditorLoadState.TOO_LARGE
|
||||
return@LaunchedEffect
|
||||
}
|
||||
val decoded = decodeEditorText(bytes)
|
||||
text = expandEditorTabs(decoded.text)
|
||||
charset = decoded.charset
|
||||
lock = when {
|
||||
editorIsBinary(bytes) -> EditorLock.BINARY
|
||||
decoded.lossy -> EditorLock.LOSSY
|
||||
bytes.size > EDITOR_MAX_EDIT_BYTES -> EditorLock.TOO_LARGE
|
||||
!file.canWrite() -> EditorLock.PERMISSION
|
||||
else -> EditorLock.NONE
|
||||
}
|
||||
selection = TextRange.Zero
|
||||
loadState = EditorLoadState.READY
|
||||
}
|
||||
|
||||
suspend fun revealLine(line: Int) {
|
||||
val current = scrollState.value
|
||||
val top = line * lineHeightPx
|
||||
val target = when {
|
||||
top < current -> top
|
||||
top + lineHeightPx > current + viewportHeight -> top + lineHeightPx - viewportHeight
|
||||
else -> return
|
||||
}
|
||||
val clamped = target.roundToInt().coerceIn(0, scrollState.maxValue)
|
||||
if (clamped != current) scrollState.scrollTo(clamped)
|
||||
}
|
||||
|
||||
LaunchedEffect(text, selection.end, viewportHeight, viewportWidth) {
|
||||
if (loadState != EditorLoadState.READY) return@LaunchedEffect
|
||||
revealLine(lineIndexOfOffset(text, selection.end))
|
||||
if (viewportWidth > 0 && charWidthPx > 0) {
|
||||
val x = (columnOfOffset(text, selection.end) - 1) * charWidthPx
|
||||
val current = textHorizontalState.value
|
||||
val target = when {
|
||||
x < current -> x
|
||||
x + charWidthPx > current + viewportWidth -> x + charWidthPx - viewportWidth
|
||||
else -> null
|
||||
}
|
||||
if (target != null) {
|
||||
val clamped = target.roundToInt().coerceIn(0, textHorizontalState.maxValue)
|
||||
if (clamped != current) textHorizontalState.scrollTo(clamped)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(query, matchCase) {
|
||||
if (query.isEmpty()) return@LaunchedEffect
|
||||
matchIndex = 0
|
||||
val first = matches.firstOrNull() ?: return@LaunchedEffect
|
||||
selection = TextRange(first.first, first.last + 1)
|
||||
composing = TextRange.Zero
|
||||
}
|
||||
|
||||
LaunchedEffect(text) { matchIndex = 0 }
|
||||
|
||||
fun gotoMatch(delta: Int) {
|
||||
if (matches.isEmpty()) return
|
||||
matchIndex = Math.floorMod(matchIndex + delta, matches.size)
|
||||
val m = matches[matchIndex]
|
||||
selection = TextRange(m.first, m.last + 1)
|
||||
composing = TextRange.Zero
|
||||
}
|
||||
|
||||
fun replaceCurrent() {
|
||||
if (readOnly) return
|
||||
val m = matches.getOrNull(matchIndex) ?: return
|
||||
text = text.replaceRange(m.first, m.last + 1, replacement)
|
||||
dirty = true
|
||||
matchIndex = 0
|
||||
selection = TextRange(m.first + replacement.length)
|
||||
composing = TextRange.Zero
|
||||
}
|
||||
|
||||
fun replaceAll() {
|
||||
if (readOnly || matches.isEmpty()) return
|
||||
val all = findEditorMatches(text, query, matchCase, limit = Int.MAX_VALUE)
|
||||
text = replaceEditorMatches(text, all, replacement)
|
||||
dirty = true
|
||||
matchIndex = 0
|
||||
selection = TextRange.Zero
|
||||
composing = TextRange.Zero
|
||||
}
|
||||
|
||||
fun save() {
|
||||
if (readOnly || saving || loadState != EditorLoadState.READY) return
|
||||
val snapshot = text
|
||||
val bytes = snapshot.toByteArray(charset.charset)
|
||||
saving = true
|
||||
scope.launch {
|
||||
val ok = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
val target = resolveEditorSaveTarget(file)
|
||||
val parent = target.parentFile
|
||||
if (parent == null) {
|
||||
target.writeBytes(bytes)
|
||||
} else {
|
||||
val tmp = File.createTempFile(".${target.name}.", ".droiddeck-tmp", parent)
|
||||
try {
|
||||
tmp.writeBytes(bytes)
|
||||
runCatching {
|
||||
Files.setPosixFilePermissions(tmp.toPath(), Files.getPosixFilePermissions(target.toPath()))
|
||||
}
|
||||
if (!tmp.renameTo(target)) error("rename to ${target.name} failed")
|
||||
} finally {
|
||||
tmp.delete()
|
||||
}
|
||||
}
|
||||
}.isSuccess
|
||||
}
|
||||
saving = false
|
||||
if (ok) {
|
||||
if (text == snapshot) dirty = false
|
||||
} else {
|
||||
Toast.makeText(context, context.getString(R.string.fm_edit_save_failed, file.name), Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun tryExit() {
|
||||
if (saving) return
|
||||
if (dirty && !readOnly) showDiscard = true else onExit()
|
||||
}
|
||||
|
||||
BackHandler { tryExit() }
|
||||
|
||||
if (showDiscard) {
|
||||
OutlinedAlertDialog(
|
||||
onDismissRequest = { showDiscard = false },
|
||||
title = { Text(stringResource(R.string.fm_edit_discard_title)) },
|
||||
text = { Text(stringResource(R.string.fm_edit_discard_text, file.name)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = onExit, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.fm_edit_discard))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showDiscard = false }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(R.string.common_cancel))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
.background(MaterialTheme.colorScheme.background),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(MaterialTheme.colorScheme.surfaceContainer)
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
) {
|
||||
IconButton(onClick = { tryExit() }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(
|
||||
Icons.Filled.ArrowBack,
|
||||
stringResource(R.string.fm_back),
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
Column(modifier = Modifier.weight(1f).padding(horizontal = 4.dp)) {
|
||||
Text(
|
||||
text = file.name,
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
fontSize = 14.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (dirty) {
|
||||
Text(
|
||||
text = "\u2022 " + stringResource(R.string.fm_edit_modified),
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontSize = 11.sp,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (loadState == EditorLoadState.READY && lock != EditorLock.NONE) {
|
||||
Text(
|
||||
text = stringResource(
|
||||
if (lock == EditorLock.BINARY) R.string.fm_edit_binary else R.string.fm_edit_read_only,
|
||||
),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontSize = 10.sp,
|
||||
maxLines = 1,
|
||||
modifier = Modifier
|
||||
.background(MaterialTheme.colorScheme.surfaceVariant, MaterialTheme.shapes.small)
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
}
|
||||
IconButton(
|
||||
onClick = { showSearch = !showSearch },
|
||||
enabled = loadState == EditorLoadState.READY,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.Search,
|
||||
stringResource(R.string.fm_edit_find),
|
||||
tint = if (showSearch) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
IconButton(
|
||||
onClick = { save() },
|
||||
enabled = loadState == EditorLoadState.READY && !readOnly && dirty && !saving,
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.Save,
|
||||
stringResource(R.string.fm_edit_save),
|
||||
tint = if (dirty) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (showSearch && loadState == EditorLoadState.READY) {
|
||||
Column(Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceContainer)) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(start = 8.dp, end = 4.dp, top = 4.dp),
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = query,
|
||||
onValueChange = { query = it; matchIndex = 0 },
|
||||
singleLine = true,
|
||||
placeholder = { Text(stringResource(R.string.fm_edit_find), fontSize = 13.sp) },
|
||||
textStyle = MaterialTheme.typography.bodySmall,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
|
||||
keyboardActions = KeyboardActions(onSearch = { gotoMatch(1) }),
|
||||
modifier = Modifier.weight(1f).focusGlide(),
|
||||
)
|
||||
Text(
|
||||
text = if (matches.isEmpty()) "0/${matches.size}" else "${matchIndex.coerceAtMost(matches.size - 1) + 1}/${matches.size}",
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontSize = 12.sp,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.padding(horizontal = 6.dp).widthIn(min = 44.dp, max = 80.dp),
|
||||
)
|
||||
IconButton(
|
||||
onClick = { gotoMatch(-1) },
|
||||
enabled = matches.isNotEmpty(),
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.KeyboardArrowUp,
|
||||
stringResource(R.string.fm_edit_find_previous),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
IconButton(
|
||||
onClick = { gotoMatch(1) },
|
||||
enabled = matches.isNotEmpty(),
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.KeyboardArrowDown,
|
||||
stringResource(R.string.fm_edit_find_next),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
TextButton(onClick = { matchCase = !matchCase }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(
|
||||
text = "Aa",
|
||||
color = if (matchCase) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontSize = 13.sp,
|
||||
)
|
||||
}
|
||||
IconButton(onClick = { showSearch = false }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Icon(
|
||||
Icons.Filled.Close,
|
||||
stringResource(R.string.common_cancel),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(start = 8.dp, top = 2.dp, end = 4.dp, bottom = 2.dp),
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = replacement,
|
||||
onValueChange = { replacement = it },
|
||||
singleLine = true,
|
||||
placeholder = { Text(stringResource(R.string.fm_edit_replace), fontSize = 13.sp) },
|
||||
textStyle = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.weight(1f).focusGlide(),
|
||||
)
|
||||
TextButton(
|
||||
onClick = { replaceCurrent() },
|
||||
enabled = !readOnly && matches.isNotEmpty(),
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) {
|
||||
Text(stringResource(R.string.fm_edit_replace), fontSize = 13.sp)
|
||||
}
|
||||
TextButton(
|
||||
onClick = { replaceAll() },
|
||||
enabled = !readOnly && matches.isNotEmpty(),
|
||||
modifier = Modifier.focusGlide(CircleShape),
|
||||
) {
|
||||
Text(stringResource(R.string.fm_edit_replace_all), fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.fillMaxWidth()
|
||||
.onSizeChanged { viewportHeight = it.height },
|
||||
) {
|
||||
when (loadState) {
|
||||
EditorLoadState.LOADING -> CircularProgressIndicator(
|
||||
modifier = Modifier.align(Alignment.Center),
|
||||
)
|
||||
|
||||
EditorLoadState.TOO_LARGE, EditorLoadState.UNREADABLE -> Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier.align(Alignment.Center).padding(24.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(
|
||||
if (loadState == EditorLoadState.TOO_LARGE) R.string.fm_edit_too_large
|
||||
else R.string.fm_edit_open_failed,
|
||||
if (loadState == EditorLoadState.TOO_LARGE) FileOps.formatBytes(context, file.length())
|
||||
else file.name,
|
||||
),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontSize = 14.sp,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
|
||||
EditorLoadState.READY -> Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(scrollState),
|
||||
) {
|
||||
Row(modifier = Modifier.fillMaxWidth().height(lineHeightDp * totalLines.toFloat())) {
|
||||
LineNumbers(
|
||||
scrollState = scrollState,
|
||||
viewportHeight = viewportHeight,
|
||||
lineHeightDp = lineHeightDp,
|
||||
lineHeightPx = lineHeightPx,
|
||||
totalLines = totalLines,
|
||||
cursorLine = cursorLine,
|
||||
style = bodyStyle,
|
||||
mutedColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
cursorColor = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Box(modifier = Modifier.weight(1f).onSizeChanged { viewportWidth = it.width }.horizontalScroll(textHorizontalState)) {
|
||||
BasicTextField(
|
||||
value = TextFieldValue(text = text, selection = selection, composition = composing),
|
||||
onValueChange = { next ->
|
||||
val changed = next.text != text
|
||||
text = next.text
|
||||
selection = next.selection
|
||||
composing = next.composition
|
||||
if (changed) dirty = true
|
||||
},
|
||||
readOnly = readOnly,
|
||||
textStyle = bodyStyle,
|
||||
cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Text,
|
||||
capitalization = KeyboardCapitalization.None,
|
||||
),
|
||||
modifier = Modifier.fillMaxHeight().focusGlide(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (loadState == EditorLoadState.READY) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.fm_edit_position, cursorLine + 1, cursorColumn),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontSize = 12.sp,
|
||||
maxLines = 1,
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(
|
||||
text = charset.label + " \u2022 " + FileOps.formatBytes(context, file.length()),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontSize = 12.sp,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LineNumbers(
|
||||
scrollState: ScrollState,
|
||||
viewportHeight: Int,
|
||||
lineHeightDp: Dp,
|
||||
lineHeightPx: Float,
|
||||
totalLines: Int,
|
||||
cursorLine: Int,
|
||||
style: TextStyle,
|
||||
mutedColor: Color,
|
||||
cursorColor: Color,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val firstLine = (scrollState.value / lineHeightPx).toInt().coerceIn(0, totalLines - 1)
|
||||
val lastLine = ((scrollState.value + viewportHeight) / lineHeightPx)
|
||||
.toInt()
|
||||
.coerceIn(firstLine, totalLines - 1)
|
||||
Column(
|
||||
horizontalAlignment = Alignment.End,
|
||||
modifier = modifier
|
||||
.width(IntrinsicSize.Min)
|
||||
.padding(top = lineHeightDp * firstLine.toFloat()),
|
||||
) {
|
||||
for (line in firstLine..lastLine) {
|
||||
Text(
|
||||
text = (line + 1).toString(),
|
||||
color = if (line == cursorLine) cursorColor else mutedColor,
|
||||
textAlign = TextAlign.End,
|
||||
maxLines = 1,
|
||||
style = style,
|
||||
modifier = Modifier.fillMaxWidth().height(lineHeightDp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,7 @@ object AutoComponents {
|
||||
{ c, comp, all, progress -> WinComponents.install(c, comp, all, progress) }
|
||||
@VisibleForTesting internal var sessionRunning: () -> Boolean = { SessionState.running }
|
||||
@VisibleForTesting internal var unfavourable: (Context) -> Boolean = { c -> constrained(c) }
|
||||
@VisibleForTesting internal var firstRunHeldBack: (Context) -> Boolean = { c -> powerSaveOrMetered(c) }
|
||||
@VisibleForTesting internal var online: (Context) -> Boolean = { c -> isOnline(c) }
|
||||
@VisibleForTesting @Volatile internal var runNow = false
|
||||
|
||||
@@ -533,6 +534,10 @@ object AutoComponents {
|
||||
caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
||||
}
|
||||
|
||||
fun powerSaveOrMetered(context: Context): Boolean =
|
||||
context.getSystemService(PowerManager::class.java)?.isPowerSaveMode == true ||
|
||||
context.getSystemService(ConnectivityManager::class.java)?.isActiveNetworkMetered == true
|
||||
|
||||
fun constrained(context: Context): Boolean {
|
||||
val power = context.getSystemService(PowerManager::class.java)
|
||||
if (power?.isPowerSaveMode == true) return true
|
||||
|
||||
@@ -56,7 +56,7 @@ object BattleNet {
|
||||
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"),
|
||||
)
|
||||
|
||||
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" && it.code != "WoWF" }
|
||||
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" }
|
||||
|
||||
// Blizzard's China client installs some products under a CN uid; they are the same games and keep their store identity.
|
||||
private val CN_UIDS = mapOf("s2_cn" to "s2", "osic" to "osi", "anbs_cn" to "anbs")
|
||||
|
||||
@@ -72,6 +72,8 @@ object CurseForgeApp {
|
||||
JSONObject().put("instanceId", guid).put("projectId", projectId.toLong()).put("categoryClassId", 1)
|
||||
.put("installLatestFile", true).put("installSource", 4)
|
||||
|
||||
private const val CACHE = "__droiddeckServices"
|
||||
|
||||
private const val SERVICES = """(() => {
|
||||
const seen = new Set(), out = {};
|
||||
const walk = (o, d) => {
|
||||
@@ -91,7 +93,8 @@ object CurseForgeApp {
|
||||
internal fun expression(service: String, method: String, args: JSONArray?, pick: String = "r => r"): String {
|
||||
val name = JSONObject.quote(method)
|
||||
val run = if (args == null) "true" else "($pick)(await s[$name](...$args))"
|
||||
val inner = "(async () => { const s = $SERVICES[${JSONObject.quote(service)}]; " +
|
||||
val key = JSONObject.quote(service)
|
||||
val inner = "(async () => { let m = globalThis.$CACHE; if (!m || !m[$key]) m = globalThis.$CACHE = $SERVICES; const s = m[$key]; " +
|
||||
"if (!s || typeof s[$name] !== 'function') return { missing: true }; " +
|
||||
"return { value: $run }; })()"
|
||||
return "(() => { const w = require('electron').BrowserWindow.getAllWindows()" +
|
||||
@@ -170,6 +173,7 @@ object CurseForgeApp {
|
||||
}
|
||||
|
||||
private val holds = ConcurrentHashMap<String, AtomicBoolean>()
|
||||
private val connected = ConcurrentHashMap.newKeySet<String>()
|
||||
|
||||
private fun lines(context: Context, argv: List<String>): List<String> {
|
||||
val out = ArrayList<String>()
|
||||
@@ -232,19 +236,25 @@ object CurseForgeApp {
|
||||
}
|
||||
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") }
|
||||
hold.set(true)
|
||||
inspector?.let(connected::remove)
|
||||
if (holds.remove(dir, hold)) runCatching { lines(context, helperArgv("stop", dir)) }
|
||||
}
|
||||
|
||||
private fun connect(context: Context, inspector: String) {
|
||||
if (inspector in connected) return
|
||||
call(context, inspector, "CoreService", "connect", JSONArray(), 120_000, "r => true")
|
||||
connected += inspector
|
||||
}
|
||||
|
||||
private fun instances(context: Context, inspector: String): Any? =
|
||||
call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000,
|
||||
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
|
||||
|
||||
fun instance(context: Context, inspector: String, root: String, flavorDir: String): String {
|
||||
connect(context, inspector)
|
||||
instanceFor(instances(context, inspector), flavorDir, null)?.let { return it }
|
||||
val detected = call(context, inspector, "GameDetectionAppService", "detectGameFromPath", JSONArray().put(root).put(WOW), 60_000) as? JSONObject
|
||||
val instances = call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000,
|
||||
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
|
||||
return instanceFor(instances, flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir")
|
||||
return instanceFor(instances(context, inspector), flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir")
|
||||
}
|
||||
|
||||
fun search(context: Context, inspector: String, guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): WowAddonCatalog.Page =
|
||||
@@ -260,34 +270,34 @@ object CurseForgeApp {
|
||||
"locked: !!(p.installedVersion && p.installedVersion.isLocked), " +
|
||||
"folders: ((p.installedVersion && p.installedVersion.addonFolders) || []).map(f => f.name) }))"
|
||||
|
||||
private fun settle(context: Context, inspector: String, guid: String, done: (List<Project>) -> Boolean): Boolean {
|
||||
private fun settle(context: Context, inspector: String, guid: String, done: (List<Project>) -> Boolean): List<Project>? {
|
||||
val deadline = System.currentTimeMillis() + INSTALL_MS
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
val listed = runCatching { projects(context, inspector, guid) }
|
||||
val error = listed.exceptionOrNull()
|
||||
if (error is Failure && error.gone) throw error
|
||||
listed.getOrNull()?.let { if (done(it)) return true }
|
||||
listed.getOrNull()?.let { if (done(it)) return it }
|
||||
Thread.sleep(1_000)
|
||||
}
|
||||
return false
|
||||
return null
|
||||
}
|
||||
|
||||
fun install(context: Context, inspector: String, guid: String, projectId: String): Boolean {
|
||||
fun install(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
|
||||
connect(context, inspector)
|
||||
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return false
|
||||
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return null
|
||||
return settle(context, inspector, guid) { list -> list.any { it.id == projectId } }
|
||||
}
|
||||
|
||||
fun update(context: Context, inspector: String, guid: String, projectId: String): Boolean {
|
||||
fun update(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
|
||||
connect(context, inspector)
|
||||
if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return false
|
||||
if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return null
|
||||
return settle(context, inspector, guid) { list -> list.any { it.id == projectId && !it.update } }
|
||||
}
|
||||
|
||||
fun uninstall(context: Context, inspector: String, guid: String, project: Project): Boolean {
|
||||
fun uninstall(context: Context, inspector: String, guid: String, project: Project): List<Project>? {
|
||||
connect(context, inspector)
|
||||
val failed = call(context, inspector, "InstalledProjectsAppService", "deleteMods", JSONArray().put(guid).put(JSONArray().put(project.installedModId)), 120_000) as? JSONArray
|
||||
if (failed == null || failed.length() > 0) return false
|
||||
if (failed == null || failed.length() > 0) return null
|
||||
return settle(context, inspector, guid) { list -> list.none { it.id == project.id } }
|
||||
}
|
||||
}
|
||||
@@ -275,12 +275,15 @@ class LinuxNetworkLinkComponent(
|
||||
* 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()
|
||||
synchronized(WRITES) {
|
||||
if (runCatching { file.isFile && file.readText() == text }.getOrDefault(false)) return
|
||||
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")
|
||||
}
|
||||
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
|
||||
}
|
||||
|
||||
private fun writeResolver(properties: LinkProperties?) {
|
||||
@@ -333,6 +336,8 @@ class LinuxNetworkLinkComponent(
|
||||
seededMac { Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) }
|
||||
|
||||
companion object {
|
||||
private val WRITES = Any()
|
||||
|
||||
internal fun gateways(properties: LinkProperties?, capabilities: NetworkCapabilities?): List<InetAddress> =
|
||||
listOf(Inet4Address::class.java, Inet6Address::class.java).mapNotNull { family ->
|
||||
properties?.routes.orEmpty()
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
|
||||
import com.droiddeck.launcher.runtime.RuntimeInstallService
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
|
||||
/** What first run installs by itself, in the order it is needed, and how far each part has got. */
|
||||
object Onboarding {
|
||||
enum class Step { RUNTIME, PROTON, STEAM }
|
||||
|
||||
data class Progress(val label: String, val percent: Int)
|
||||
|
||||
data class Facts(val runtime: Boolean = true, val proton: Boolean = true, val steam: Boolean = true)
|
||||
|
||||
enum class State { DONE, ACTIVE, WAITING, FAILED }
|
||||
|
||||
data class Row(val step: Step, val state: State, val label: String?, val percent: Int)
|
||||
|
||||
val active = MutableStateFlow<Map<Step, Progress>>(emptyMap())
|
||||
val failed = MutableStateFlow<Map<Step, String>>(emptyMap())
|
||||
val facts = MutableStateFlow(Facts())
|
||||
|
||||
@Volatile private var appContext: Context? = null
|
||||
private var hold: (() -> Unit)? = null
|
||||
|
||||
fun attach(context: Context) {
|
||||
appContext = context.applicationContext
|
||||
}
|
||||
|
||||
/** Keeps the process in the foreground, with one notification, while a step downloads and the runtime installer is not already doing so. */
|
||||
@Synchronized private fun keepAlive() {
|
||||
val context = appContext ?: return
|
||||
val running = active.value
|
||||
if (running.isNotEmpty() && !LinuxRuntimeInstaller.isBusy()) {
|
||||
if (hold == null) hold = RuntimeInstallService.holdForPackage(context, context.getString(R.string.onboarding_title))
|
||||
val rows = rows(running, failed.value, facts.value)
|
||||
RuntimeInstallService.packageProgress(running.values.first().label, overall(rows))
|
||||
} else {
|
||||
hold?.invoke()
|
||||
hold = null
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized fun recheck(context: Context) {
|
||||
val runtime = LinuxRuntime.isInstalled(context)
|
||||
val own = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
||||
facts.value = Facts(
|
||||
runtime = runtime,
|
||||
proton = ProtonExtras.declined(context) || ProtonExtras.installedAll(context, own).isNotEmpty(),
|
||||
steam = runtime && !SteamClientPrefetch.pending(context),
|
||||
)
|
||||
}
|
||||
|
||||
fun report(step: Step, label: String, percent: Int) {
|
||||
failed.value = failed.value - step
|
||||
active.value = active.value + (step to Progress(label, percent))
|
||||
keepAlive()
|
||||
}
|
||||
|
||||
fun finish(step: Step) {
|
||||
active.value = active.value - step
|
||||
failed.value = failed.value - step
|
||||
keepAlive()
|
||||
}
|
||||
|
||||
fun fail(step: Step, message: String) {
|
||||
active.value = active.value - step
|
||||
failed.value = failed.value + (step to message)
|
||||
keepAlive()
|
||||
}
|
||||
|
||||
fun rows(active: Map<Step, Progress>, failed: Map<Step, String>, facts: Facts): List<Row> = Step.entries.map { step ->
|
||||
val ready = when (step) { Step.RUNTIME -> facts.runtime; Step.PROTON -> facts.proton; Step.STEAM -> facts.steam }
|
||||
val progress = active[step]
|
||||
when {
|
||||
progress != null -> Row(step, State.ACTIVE, progress.label, progress.percent)
|
||||
failed[step] != null -> Row(step, State.FAILED, failed[step], -1)
|
||||
ready -> Row(step, State.DONE, null, 100)
|
||||
else -> Row(step, State.WAITING, null, -1)
|
||||
}
|
||||
}
|
||||
|
||||
fun pending(rows: List<Row>): Boolean = rows.any { it.state != State.DONE }
|
||||
|
||||
/** The aggregate fraction of the whole first-run work, weighting each step by what it downloads. */
|
||||
fun overall(rows: List<Row>): Int {
|
||||
val weights = mapOf(Step.RUNTIME to 60, Step.PROTON to 15, Step.STEAM to 25)
|
||||
val total = weights.values.sum()
|
||||
val got = rows.sumOf { row ->
|
||||
val w = weights.getValue(row.step)
|
||||
when (row.state) {
|
||||
State.DONE -> w
|
||||
State.ACTIVE -> if (row.percent >= 0) w * row.percent / 100 else 0
|
||||
else -> 0
|
||||
}
|
||||
}
|
||||
return got * 100 / total
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ object ProtonExtras {
|
||||
const val CHECK_EVERY_MS = 60L * 60 * 1000
|
||||
@Volatile
|
||||
var installInProgress = false
|
||||
@Volatile var prefetching = false
|
||||
private set
|
||||
@Volatile
|
||||
private var replacing = false
|
||||
@@ -217,24 +218,12 @@ object ProtonExtras {
|
||||
|
||||
@Synchronized
|
||||
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (installInProgress) return context.getString(R.string.pextra_busy)
|
||||
if (installInProgress || prefetching) return context.getString(R.string.pextra_busy)
|
||||
installInProgress = true
|
||||
return try { installNow(context, tool, onProgress) } finally { installInProgress = false }
|
||||
}
|
||||
|
||||
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
|
||||
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
|
||||
|
||||
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
|
||||
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
|
||||
val archive = File(downloads, "${tool.id}-${asset.name}")
|
||||
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
|
||||
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
|
||||
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
|
||||
return context.getString(R.string.pextra_no_space, tool.name)
|
||||
}
|
||||
|
||||
private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit): String? {
|
||||
val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag)
|
||||
onProgress(downloading, 0)
|
||||
var downloaded = false
|
||||
@@ -252,6 +241,41 @@ object ProtonExtras {
|
||||
}
|
||||
}
|
||||
if (!downloaded) return context.getString(R.string.pextra_download_failed)
|
||||
return null
|
||||
}
|
||||
|
||||
/** Downloads the newest build of [tool] ahead of the runtime it installs into; [install] verifies and unpacks it later. */
|
||||
@Synchronized
|
||||
fun prefetch(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (installInProgress) return context.getString(R.string.pextra_busy)
|
||||
prefetching = true
|
||||
try { return prefetchNow(context, tool, onProgress) } finally { prefetching = false }
|
||||
}
|
||||
|
||||
private fun prefetchNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
|
||||
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
|
||||
val archive = File(downloads, "${tool.id}-${asset.name}")
|
||||
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
|
||||
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
|
||||
if (StatFs(context.filesDir.path).availableBytes < NEED_BYTES + missing) return context.getString(R.string.pextra_no_space, tool.name)
|
||||
return fetchArchive(context, tool, asset, archive, onProgress)
|
||||
}
|
||||
|
||||
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
|
||||
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
|
||||
|
||||
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
|
||||
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
|
||||
val archive = File(downloads, "${tool.id}-${asset.name}")
|
||||
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
|
||||
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
|
||||
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
|
||||
return context.getString(R.string.pextra_no_space, tool.name)
|
||||
}
|
||||
|
||||
fetchArchive(context, tool, asset, archive, onProgress)?.let { return it }
|
||||
if (asset.size > 0 && archive.length() != asset.size) {
|
||||
if (archive.length() > asset.size) {
|
||||
archive.delete()
|
||||
|
||||
@@ -95,7 +95,11 @@ object SessionFiles {
|
||||
return all
|
||||
}
|
||||
|
||||
fun stage(context: Context, root: File, startsSession: Boolean = false) {
|
||||
private val STAGE_LOCK = Any()
|
||||
|
||||
fun stage(context: Context, root: File, startsSession: Boolean = false) = synchronized(STAGE_LOCK) { stageNow(context, root, startsSession) }
|
||||
|
||||
private fun stageNow(context: Context, root: File, startsSession: Boolean) {
|
||||
if (DesktopCatalog.desktopInstalled(root) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) }
|
||||
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
|
||||
GameEnvironmentStore.publish(context)
|
||||
@@ -660,6 +664,7 @@ object SessionFiles {
|
||||
private const val UI_STATE = "UIStoreLocalSteamUIState"
|
||||
private const val SORT_RECENT_OFF = "\\\"bSortedByRecent\\\":false"
|
||||
private const val SORT_RECENT_ON = "\\\"bSortedByRecent\\\":true"
|
||||
private const val LIBRARY_BIG_ART = "LibraryHomeBigArt"
|
||||
private const val BATTERY_PERCENT_ON = "{\\\"bShowBatteryPercentage\\\":true}"
|
||||
|
||||
/**
|
||||
@@ -709,7 +714,12 @@ object SessionFiles {
|
||||
val block = out.substring(web.keyStart, web.close + 1)
|
||||
out = out.replaceRange(web.keyStart, web.close + 1, setScalar(block, BATTERY_PREFERENCES, BATTERY_PERCENT_ON, newline))
|
||||
}
|
||||
return seedRecentSort(out, newline)
|
||||
out = seedRecentSort(out, newline)
|
||||
val last = findObject(out, "UserLocalConfigStore", 0, out.length) ?: return out
|
||||
if (!hasKey(out.substring(last.open + 1, last.close), LIBRARY_BIG_ART)) {
|
||||
out = insertInto(out, last, listOf("\"$LIBRARY_BIG_ART\"\t\t\"1\""), newline)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// The library sort lives inside a JSON string; Steam writes bSortedByRecent:false until the player picks a sort,
|
||||
@@ -729,9 +739,11 @@ object SessionFiles {
|
||||
|
||||
private fun insertInto(text: String, parent: VdfBlock, lines: List<String>, newline: String): String {
|
||||
val lineStart = text.lastIndexOf('\n', parent.close).let { if (it < 0) 0 else it + 1 }
|
||||
val indent = text.substring(lineStart, parent.close).takeWhile { it == '\t' || it == ' ' } + "\t"
|
||||
val before = text.substring(lineStart, parent.close)
|
||||
val indent = before.takeWhile { it == '\t' || it == ' ' } + "\t"
|
||||
val section = lines.joinToString(newline) { indent + it } + newline
|
||||
return text.substring(0, lineStart) + section + text.substring(lineStart)
|
||||
if (before.isBlank()) return text.substring(0, lineStart) + section + text.substring(lineStart)
|
||||
return text.substring(0, parent.close) + newline + section + text.substring(parent.close)
|
||||
}
|
||||
|
||||
private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds")
|
||||
|
||||
@@ -63,6 +63,13 @@ object SessionPrefs {
|
||||
.takeIf { value -> orientationOptions.any { it.first == value } }
|
||||
?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
|
||||
|
||||
/** The session menu's width in dp the user dragged it to; null keeps the default. */
|
||||
fun drawerWidthDp(context: Context): Int? = prefs(context).getInt("drawerWidthDp", 0).takeIf { it > 0 }
|
||||
|
||||
fun setDrawerWidthDp(context: Context, dp: Int) {
|
||||
prefs(context).edit().putInt("drawerWidthDp", dp).apply()
|
||||
}
|
||||
|
||||
fun setOrientation(context: Context, orientation: Int) {
|
||||
require(orientationOptions.any { it.first == orientation })
|
||||
prefs(context).edit().putInt("orientation", orientation).apply()
|
||||
|
||||
@@ -2705,6 +2705,7 @@ class SessionService : Service() {
|
||||
gameId: String? = null,
|
||||
displayId: Int = Display.DEFAULT_DISPLAY,
|
||||
) {
|
||||
SteamClientPrefetch.cancel()
|
||||
SessionState.activityDisplayId = displayId
|
||||
val intent = Intent(context, SessionService::class.java).putExtra(EXTRA_MODE, mode)
|
||||
.putExtra(EXTRA_DISPLAY_ID, displayId)
|
||||
|
||||
@@ -13,7 +13,7 @@ object SettingsReset {
|
||||
|
||||
internal val SESSION_KEYS = setOf(
|
||||
"orientation", "launcherFullscreen", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
|
||||
"dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
|
||||
"drawerWidthDp", "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
|
||||
"soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
|
||||
"storesInstallLanguage",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "dockedMenuController", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController",
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import kotlinx.coroutines.flow.update
|
||||
|
||||
/**
|
||||
* Downloads Valve's Steam client while the session is stopped, so the first Play does not wait on it.
|
||||
* It runs the same droiddeck-steam-install the session runs, which keeps what arrived when it is cut
|
||||
* short and resumes from there.
|
||||
*/
|
||||
object SteamClientPrefetch {
|
||||
private const val TAG = "SteamClientPrefetch"
|
||||
private val DOWNLOADING = Regex("""downloading Steam: .*, (\d+) of (\d+) MB""")
|
||||
|
||||
private const val CANCELLED = "cancelled"
|
||||
private val lock = Any()
|
||||
private var process: Process? = null
|
||||
private var cancelled = false
|
||||
@Volatile private var thread: Thread? = null
|
||||
|
||||
internal fun parse(line: String): Pair<Int, Int>? {
|
||||
val match = DOWNLOADING.find(line) ?: return null
|
||||
val done = match.groupValues[1].toLongOrNull() ?: return null
|
||||
val total = match.groupValues[2].toLongOrNull()?.takeIf { it > 0 } ?: return null
|
||||
return (done * 100 / total).toInt().coerceIn(0, 100) to total.toInt()
|
||||
}
|
||||
|
||||
fun running(): Boolean = thread?.isAlive == true
|
||||
|
||||
private const val CACHED = "root/.local/share/Steam/package/droiddeck-cached"
|
||||
|
||||
fun installPending(context: Context): Boolean = SteamDownloadMonitor.clientInstallPending(LinuxRuntime.rootDir(context))
|
||||
|
||||
fun pending(context: Context): Boolean =
|
||||
installPending(context) || !File(LinuxRuntime.rootDir(context), CACHED).isFile
|
||||
|
||||
/** Stops a running download so a session can take over; the script resumes the partial files. */
|
||||
fun cancel() {
|
||||
synchronized(lock) {
|
||||
cancelled = true
|
||||
process?.destroy()
|
||||
}
|
||||
}
|
||||
|
||||
private fun isCancelled() = synchronized(lock) { cancelled }
|
||||
|
||||
@Synchronized
|
||||
fun start(context: Context, label: (Int) -> String, failedLabel: String) {
|
||||
if (running() || SessionState.running || !LinuxRuntime.isInstalled(context) || !pending(context)) return
|
||||
val app = context.applicationContext
|
||||
synchronized(lock) { cancelled = false }
|
||||
thread = Thread({
|
||||
Onboarding.report(Onboarding.Step.STEAM, label(-1), -1)
|
||||
val problem = runCatching { run(app, label) }.getOrElse { it.message ?: it.javaClass.simpleName }
|
||||
synchronized(lock) { process = null }
|
||||
if (problem == null && !pending(app)) Onboarding.finish(Onboarding.Step.STEAM)
|
||||
else if (SessionState.running || problem == CANCELLED || isCancelled()) Onboarding.finish(Onboarding.Step.STEAM)
|
||||
else Onboarding.fail(Onboarding.Step.STEAM, problem ?: failedLabel)
|
||||
val steamReady = !pending(app)
|
||||
Onboarding.facts.update { it.copy(steam = steamReady) }
|
||||
}, "steam-client-prefetch").also { it.start() }
|
||||
}
|
||||
|
||||
private fun run(context: Context, label: (Int) -> String): String? {
|
||||
if (isCancelled()) return CANCELLED
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
LinuxRuntime.writeAccounts(context)
|
||||
SessionFiles.stage(context, root)
|
||||
val install = installPending(context)
|
||||
if (install) {
|
||||
val problem = script(context, emptyList(), label, 0, 35)
|
||||
if (problem != null) return problem
|
||||
}
|
||||
return script(context, listOf("--cache"), label, if (install) 35 else 0, 100)
|
||||
}
|
||||
|
||||
private fun script(context: Context, args: List<String>, label: (Int) -> String, from: Int, to: Int): String? {
|
||||
val guest = listOf(
|
||||
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "PATH=/usr/local/bin:/usr/bin:/bin",
|
||||
"LANG=C.UTF-8", "XDG_DATA_HOME=/root/.local/share", "/usr/local/bin/droiddeck-steam-install",
|
||||
) + args
|
||||
if (isCancelled()) return CANCELLED
|
||||
val child = ProtonExtras.guestProcess(context, guest).start()
|
||||
synchronized(lock) {
|
||||
if (cancelled) {
|
||||
child.destroy()
|
||||
return CANCELLED
|
||||
}
|
||||
process = child
|
||||
}
|
||||
child.inputStream.bufferedReader().useLines { lines ->
|
||||
lines.forEach { line ->
|
||||
Log.i(TAG, line)
|
||||
val progress = parse(line)
|
||||
if (progress != null) Onboarding.report(Onboarding.Step.STEAM, label(progress.second), from + progress.first * (to - from) / 100)
|
||||
}
|
||||
}
|
||||
val status = child.waitFor()
|
||||
return if (status == 0) null else "droiddeck-steam-install exited $status"
|
||||
}
|
||||
}
|
||||
@@ -103,7 +103,9 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
|
||||
XboxContent.complete(app, item, folder)
|
||||
return folder.path
|
||||
}
|
||||
val exe = executable(folder)
|
||||
val exe = runCatching { executable(folder) }.onFailure {
|
||||
StoresState.logLine("Xbox: install folder holds ${folder.list().orEmpty().sorted().take(MAX_ERROR_LINES).joinToString()}")
|
||||
}.getOrThrow()
|
||||
StoreInstalls.complete(app, folder, StoreGameSidecar(Store.XBOX, item.id, item.title, exe,
|
||||
installVersion = XboxManifest.read(folder).version, installedAt = System.currentTimeMillis(), cover = item.tallImageUrl, hero = item.imageUrl,
|
||||
extra = item.extra + mapOf("contentId" to selected, "market" to market)))
|
||||
|
||||
@@ -21,8 +21,9 @@ internal object XboxManifest {
|
||||
val files = folder.listFiles().orEmpty()
|
||||
val config = files.filter { it.name.equals(GAME_CONFIG, true) && it.isFile }
|
||||
val legacy = files.filter { it.name.equals(APPX_MANIFEST, true) && it.isFile }
|
||||
require(config.size + legacy.size == 1) { "Missing or ambiguous game manifest." }
|
||||
val manifest = (config + legacy).single()
|
||||
val manifests = config.ifEmpty { legacy }
|
||||
require(manifests.size == 1) { "Missing or ambiguous game manifest." }
|
||||
val manifest = manifests.single()
|
||||
val rootTag = if (config.isEmpty()) "Package" else "Game"
|
||||
require(manifest.length() <= 1_048_576)
|
||||
val parser = android.util.Xml.newPullParser().apply { setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false) }
|
||||
|
||||
@@ -110,6 +110,9 @@ internal class CurseLink(val app: UserApps.App) {
|
||||
private val guids = HashMap<String, String>()
|
||||
private val scanLock = Object()
|
||||
private val scans = HashMap<String, Pair<Any, List<CurseForgeApp.Project>>>()
|
||||
private val settleLock = Object()
|
||||
private val settled = HashMap<String, Pair<Int, List<CurseForgeApp.Project>>>()
|
||||
private val turns = HashMap<String, Int>()
|
||||
var generation by mutableIntStateOf(0)
|
||||
private set
|
||||
|
||||
@@ -120,7 +123,7 @@ internal class CurseLink(val app: UserApps.App) {
|
||||
fun installed(context: Context, target: WowAddons.Target, key: Any): List<CurseForgeApp.Project> = CurseForgeApp.onDisk(
|
||||
synchronized(scanLock) {
|
||||
scans[target.addOns.path]?.takeIf { it.first == key }?.second
|
||||
?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }.also {
|
||||
?: (settledFor(target) ?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }).also {
|
||||
scans[target.addOns.path] = key to it
|
||||
report(target, it)
|
||||
}
|
||||
@@ -131,6 +134,26 @@ internal class CurseLink(val app: UserApps.App) {
|
||||
fun marks(context: Context, target: WowAddons.Target, key: Any): Map<String, String?> =
|
||||
runCatching { installed(context, target, key).associate { it.id to curseMark(it) } }.getOrElse { lastReported(target) }
|
||||
|
||||
private fun settledFor(target: WowAddons.Target): List<CurseForgeApp.Project>? = synchronized(settleLock) {
|
||||
settled.remove(target.addOns.path)?.takeIf { it.first == generation }?.second
|
||||
}
|
||||
|
||||
fun change(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> List<CurseForgeApp.Project>?): Boolean {
|
||||
val path = target.addOns.path
|
||||
val turn = synchronized(settleLock) {
|
||||
settled.remove(path)
|
||||
((turns[path] ?: 0) + 1).also { turns[path] = it }
|
||||
}
|
||||
val projects = call(context, target, launch, block) ?: return false
|
||||
synchronized(settleLock) {
|
||||
if (turns[path] == turn) {
|
||||
settled[path] = generation to projects
|
||||
report(target, projects)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
fun <T> call(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> T): T {
|
||||
val linked = synchronized(lock) { link(context, target, launch) }
|
||||
try {
|
||||
@@ -174,11 +197,9 @@ internal class CurseLink(val app: UserApps.App) {
|
||||
return Linked(url, guid)
|
||||
}
|
||||
|
||||
fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = call(context, target, launch = false) { linked ->
|
||||
fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = change(context, target, launch = false) { linked ->
|
||||
val projects = CurseForgeApp.onDisk(CurseForgeApp.projects(context, linked.inspector, linked.guid), target.addOns)
|
||||
val project = CurseForgeApp.owner(projects, folder) ?: return@call false
|
||||
if (!CurseForgeApp.uninstall(context, linked.inspector, linked.guid, project)) throw CurseState()
|
||||
true
|
||||
CurseForgeApp.owner(projects, folder)?.let { CurseForgeApp.uninstall(context, linked.inspector, linked.guid, it) ?: throw CurseState() }
|
||||
}
|
||||
|
||||
internal val stopped: Job get() = work
|
||||
@@ -322,7 +343,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
scope.launch {
|
||||
val done = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
via.call(context, into) {
|
||||
via.change(context, into) {
|
||||
if (updating) CurseForgeApp.update(context, it.inspector, it.guid, addon.id)
|
||||
else CurseForgeApp.install(context, it.inspector, it.guid, addon.id)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.animation.expandVertically
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.shrinkHorizontally
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.expandHorizontally
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.shrinkVertically
|
||||
@@ -228,8 +229,14 @@ private fun AgentPageContent(
|
||||
}
|
||||
val topBar: @Composable () -> Unit = { AgentTopBar(panel, togglePanel, inputModifier, menu) }
|
||||
val inlineControls: (@Composable () -> Unit)? = if (inline) ({
|
||||
ModelChip(panel, togglePanel, inputModifier, compact = true)
|
||||
ContextRing("agent-usage", onClick = { togglePanel(AgentPanel.USAGE) })
|
||||
// The open menu needs the row's width for its own buttons.
|
||||
androidx.compose.animation.AnimatedVisibility(!menuOpen, enter = expandHorizontally(expandFrom = Alignment.Start) + fadeIn(),
|
||||
exit = shrinkHorizontally(shrinkTowards = Alignment.Start) + fadeOut()) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
ModelChip(panel, togglePanel, inputModifier, compact = true)
|
||||
ContextRing("agent-usage", onClick = { togglePanel(AgentPanel.USAGE) })
|
||||
}
|
||||
}
|
||||
menu()
|
||||
}) else null
|
||||
// A host with a title bar shows the top bar there.
|
||||
@@ -245,8 +252,11 @@ private fun AgentPageContent(
|
||||
LaunchedEffect(AgentHost.approvals.size, panel) {
|
||||
if (AgentHost.approvals.isNotEmpty() && (panel == AgentPanel.HISTORY || panel == AgentPanel.PROCESSES || panel == AgentPanel.TOOLS)) panel = AgentPanel.NONE
|
||||
}
|
||||
androidx.compose.foundation.layout.BoxWithConstraints(modifier.fillMaxSize()) {
|
||||
// On a short page the picker would take it all and leave no conversation, so it scrolls within a share of the page.
|
||||
val panelMax = maxHeight * 0.5f
|
||||
Column(
|
||||
modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e ->
|
||||
Modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e ->
|
||||
val k = e.nativeKeyEvent
|
||||
if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y || composer.focused) return@onPreviewKeyEvent false
|
||||
if (k.action == KeyEvent.ACTION_UP) composer.open()
|
||||
@@ -269,8 +279,8 @@ private fun AgentPageContent(
|
||||
else -> {
|
||||
if (menuSlot == null && !inline) Box(Modifier.padding(bottom = 6.dp)) { topBar() }
|
||||
when (panel) {
|
||||
AgentPanel.MODEL -> Box(Modifier.padding(bottom = 8.dp)) { AgentModelPicker() }
|
||||
AgentPanel.USAGE -> Box(Modifier.padding(bottom = 8.dp)) { AgentUsage() }
|
||||
AgentPanel.MODEL -> Box(Modifier.heightIn(max = panelMax).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { AgentModelPicker() }
|
||||
AgentPanel.USAGE -> Box(Modifier.heightIn(max = panelMax).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { AgentUsage() }
|
||||
else -> Unit
|
||||
}
|
||||
val list = rememberLazyListState()
|
||||
@@ -322,11 +332,12 @@ private fun AgentPageContent(
|
||||
}
|
||||
}
|
||||
androidx.compose.animation.AnimatedVisibility(!hidden, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
|
||||
AgentComposer(composer, draft, visible && started, inlineControls, onPanel = { panel = it }, onSent = toLatest)
|
||||
AgentComposer(composer, draft, visible && started, inlineControls, onPanel = { panel = it }, onSent = toLatest, hideAttach = inline && menuOpen)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the editor has the cursor; [open] puts it there. */
|
||||
@@ -397,10 +408,12 @@ private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentP
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val working = AgentHost.state == AgentHost.State.WORKING
|
||||
// Closed, the outline sits flush against the lone button.
|
||||
val shape = if (open) Shape16 else Shape12
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.clip(Shape16).background(colors.surface.copy(alpha = if (open) 0.97f else 0.88f))
|
||||
.border(1.dp, pal.line, Shape16).padding(end = 2.dp),
|
||||
modifier = Modifier.clip(shape).background(colors.surface.copy(alpha = if (open) 0.97f else 0.88f))
|
||||
.border(1.dp, pal.line, shape).then(if (open) Modifier.padding(top = 3.dp, bottom = 3.dp, end = 4.dp) else Modifier),
|
||||
) {
|
||||
androidx.compose.animation.AnimatedVisibility(open, enter = expandHorizontally(expandFrom = Alignment.End) + fadeIn(),
|
||||
exit = shrinkHorizontally(shrinkTowards = Alignment.End) + fadeOut()) {
|
||||
@@ -423,7 +436,7 @@ private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentP
|
||||
}
|
||||
}
|
||||
}
|
||||
HeaderAction(Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), selected = open, size = 36.dp, tag = "agent-menu") { onOpen(!open) }
|
||||
HeaderAction(Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), selected = open, size = 36.dp, tag = "agent-menu", startPadding = if (open) null else 0.dp) { onOpen(!open) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -437,12 +450,13 @@ private fun AgentPanelBar(title: String, onClose: () -> Unit) {
|
||||
|
||||
@Composable
|
||||
internal fun HeaderAction(
|
||||
icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, size: Dp = 44.dp, onClick: () -> Unit,
|
||||
icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, size: Dp = 44.dp,
|
||||
startPadding: Dp? = 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 = startPadding ?: if (size < 44.dp) 4.dp else 8.dp).size(size).clip(Shape12)
|
||||
.background(if (selected) pal.primary.copy(alpha = 0.2f) else pal.surfaceVariant)
|
||||
.clickable(enabled = enabled, onClick = onClick)
|
||||
.then(if (tag != null) Modifier.testTag(tag) else Modifier),
|
||||
@@ -715,7 +729,7 @@ internal fun liveUsed(limit: AgentHost.Limit) = if (limit.resetsAt > 0 && limit.
|
||||
@Composable
|
||||
private fun AgentComposer(
|
||||
composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?,
|
||||
onPanel: (AgentPanel) -> Unit, onSent: () -> Unit,
|
||||
onPanel: (AgentPanel) -> Unit, onSent: () -> Unit, hideAttach: Boolean = false,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
var draft by draftState
|
||||
@@ -747,13 +761,13 @@ private fun AgentComposer(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
|
||||
) { AgentActivity(labOpen) { labOpen = !labOpen } }
|
||||
AgentEditor(composer, draftState, visible, controls, send)
|
||||
AgentEditor(composer, draftState, visible, controls, send, hideAttach)
|
||||
}
|
||||
}
|
||||
|
||||
/** The text with attach, stop and send beside it, and [controls] while the text is not being typed in. */
|
||||
@Composable
|
||||
private fun AgentEditor(composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, send: () -> Unit) {
|
||||
private fun AgentEditor(composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, send: () -> Unit, hideAttach: Boolean = false) {
|
||||
val context = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
@@ -852,14 +866,14 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
|
||||
if (stacked) Column {
|
||||
text(Modifier.fillMaxWidth())
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
|
||||
if (attach) AttachButton()
|
||||
if (AgentAttachments.gameFrame != null) GameFrameButton()
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp)) { if (controls != null && !focused) controls() }
|
||||
AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() }
|
||||
AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() }
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp).horizontalScroll(rememberScrollState(), reverseScrolling = true)) { if (controls != null && !focused) controls() }
|
||||
actions()
|
||||
}
|
||||
} else Row(verticalAlignment = Alignment.Bottom) {
|
||||
if (attach) AttachButton()
|
||||
if (AgentAttachments.gameFrame != null) GameFrameButton()
|
||||
AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() }
|
||||
AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() }
|
||||
text(Modifier.weight(1f))
|
||||
if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() }
|
||||
actions()
|
||||
|
||||
@@ -175,7 +175,7 @@ internal fun SessionDrawerPreview(secondScreens: List<SecondScreenDisplay>) {
|
||||
val code = e.nativeKeyEvent.keyCode
|
||||
if (code != android.view.KeyEvent.KEYCODE_BUTTON_L1 && code != android.view.KeyEvent.KEYCODE_BUTTON_R1) return@onPreviewKeyEvent false
|
||||
if (e.type == KeyEventType.KeyDown && e.nativeKeyEvent.repeatCount == 0) {
|
||||
page = sessionDrawerPages().step(page, if (code == android.view.KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
|
||||
page = sessionDrawerPages().let { it.strip().step(it.tabFor(page), if (code == android.view.KeyEvent.KEYCODE_BUTTON_R1) 1 else -1) }
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
@@ -33,6 +33,8 @@ import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Outline
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.geometry.RoundRect
|
||||
import androidx.compose.ui.layout.LayoutCoordinates
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
@@ -109,13 +111,21 @@ internal fun VeilRing() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun cornerOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): Float =
|
||||
private fun cornersOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): FloatArray =
|
||||
when (val o = shape.createOutline(size, dir, density)) {
|
||||
is Outline.Rounded -> o.roundRect.topLeftCornerRadius.x
|
||||
is Outline.Rectangle -> 0f
|
||||
is Outline.Generic -> minOf(size.width, size.height) / 2f
|
||||
is Outline.Rounded -> o.roundRect.run {
|
||||
floatArrayOf(topLeftCornerRadius.x, topRightCornerRadius.x, bottomRightCornerRadius.x, bottomLeftCornerRadius.x)
|
||||
}
|
||||
is Outline.Rectangle -> FloatArray(4)
|
||||
is Outline.Generic -> FloatArray(4) { minOf(size.width, size.height) / 2f }
|
||||
}
|
||||
|
||||
private fun ringRect(l: Float, t: Float, w: Float, h: Float, radii: FloatArray, inset: Float): Path {
|
||||
// Radii are not capped one by one: the path scales corners whose neighbours overlap, as the outline does.
|
||||
fun r(i: Int) = CornerRadius((radii[i] - inset).coerceAtLeast(0f))
|
||||
return Path().apply { addRoundRect(RoundRect(Rect(l, t, l + w, t + h), r(0), r(1), r(2), r(3))) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun Modifier.glideBorder(
|
||||
hot: Boolean,
|
||||
@@ -190,7 +200,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
val density = LocalDensity.current
|
||||
val dir = LocalLayoutDirection.current
|
||||
val edges = remember { List(4) { Animatable(0f) } }
|
||||
val corner = remember { Animatable(0f) }
|
||||
val corners = remember { List(4) { Animatable(0f) } }
|
||||
val solid = remember { Animatable(0f) }
|
||||
val alpha = remember { Animatable(0f) }
|
||||
val scope = rememberCoroutineScope()
|
||||
@@ -259,14 +269,14 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
fun droplet(s: GlideSource, b: Rect) {
|
||||
jobs.forEach { it?.cancel() }
|
||||
val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size
|
||||
val endCorner = cornerOf(s.shape, size, dir, density)
|
||||
val endCorners = cornersOf(s.shape, size, dir, density)
|
||||
jobs[5] = scope.launch {
|
||||
val r = with(density) { 6.dp.toPx() }
|
||||
fun dot(c: Offset) = listOf(c.x - r, c.y - r, c.x + r, c.y + r)
|
||||
val here = Offset((edges[0].value + edges[2].value) / 2f, (edges[1].value + edges[3].value) / 2f)
|
||||
coroutineScope {
|
||||
launch { solid.animateTo(1f, Motion.tw(80)) }
|
||||
launch { corner.animateTo(r, Motion.tw(90)) }
|
||||
corners.forEach { c -> launch { c.animateTo(r, Motion.tw(90)) } }
|
||||
dot(here).forEachIndexed { i, v -> launch { edges[i].animateTo(v, Motion.tw(90)) } }
|
||||
}
|
||||
val distance = hypot(b.center.x - here.x, b.center.y - here.y) / density.density
|
||||
@@ -281,7 +291,9 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
flight.cancel()
|
||||
val at = glide.boundsOf(s) ?: b
|
||||
launch { solid.animateTo(0f, Motion.tw(150)) }
|
||||
launch { corner.animateTo(endCorner, Motion.sp(0.8f, 600f)) }
|
||||
// The droplet job is cancelled by the next move, so the shape settles on the corner job instead.
|
||||
jobs[4]?.cancel()
|
||||
jobs[4] = scope.launch { corners.forEachIndexed { i, c -> launch { c.animateTo(endCorners[i], Motion.sp(0.8f, 600f)) } } }
|
||||
listOf(at.left, at.top, at.right, at.bottom).forEachIndexed { i, v ->
|
||||
jobs[i] = launch { edges[i].animateTo(v, Motion.sp(0.7f, 750f)) }
|
||||
}
|
||||
@@ -289,9 +301,11 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
}
|
||||
fun cornerTo(s: GlideSource, b: Rect, snap: Boolean) {
|
||||
val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size
|
||||
val r = cornerOf(s.shape, size, dir, density)
|
||||
val r = cornersOf(s.shape, size, dir, density)
|
||||
jobs[4]?.cancel()
|
||||
jobs[4] = scope.launch { if (snap) corner.snapTo(r) else corner.animateTo(r, Motion.sp(0.8f, 500f)) }
|
||||
jobs[4] = scope.launch {
|
||||
corners.forEachIndexed { i, c -> launch { if (snap) c.snapTo(r[i]) else c.animateTo(r[i], Motion.sp(0.8f, 500f)) } }
|
||||
}
|
||||
}
|
||||
snapshotFlow { Triple(glide.current, glide.moves, glide.hidden || RingVeil.count > 0) }.collectLatest { (src, _, hidden) ->
|
||||
if (Motion.scale == 0f) {
|
||||
@@ -302,7 +316,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
else {
|
||||
listOf(b.left, b.top, b.right, b.bottom).forEachIndexed { i, v -> edges[i].snapTo(v) }
|
||||
val size = src.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size
|
||||
corner.snapTo(cornerOf(src.shape, size, dir, density))
|
||||
cornersOf(src.shape, size, dir, density).forEachIndexed { i, v -> corners[i].snapTo(v) }
|
||||
alpha.snapTo(1f)
|
||||
}
|
||||
shown = src
|
||||
@@ -343,10 +357,11 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
val out = with(density) { 3.dp.toPx() }
|
||||
val grown = listOf(b.left - out, b.top - out, b.right + out, b.bottom + out)
|
||||
jobs.forEach { it?.cancel() }
|
||||
// Set before the join: a move of the target restarts this block there, after shown is already set.
|
||||
cornerTo(src, b, snap = true)
|
||||
scope.launch { solid.snapTo(0f); edges.forEachIndexed { i, e -> e.snapTo(grown[i]) } }.join()
|
||||
dirSpecs = List(4) { Edge(0.6f, 700f) }
|
||||
delays = LongArray(4)
|
||||
cornerTo(src, b, snap = true)
|
||||
scope.launch { alpha.animateTo(1f, Motion.tw(140)) }
|
||||
} else {
|
||||
val dx = b.center.x - (edges[0].value + edges[2].value) / 2f
|
||||
@@ -394,21 +409,13 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
|
||||
val l = edges[0].value; val t = edges[1].value; val r = edges[2].value; val b = edges[3].value
|
||||
val sw = (r - l - w).coerceAtLeast(0f)
|
||||
val sh = (b - t - w).coerceAtLeast(0f)
|
||||
val rad = (corner.value - w / 2f).coerceIn(0f, minOf(sw, sh) / 2f)
|
||||
val radii = FloatArray(4) { corners[it].value }
|
||||
val f = solid.value
|
||||
if (f > 0.01f) drawRoundRect(
|
||||
color, topLeft = Offset(l, t), size = Size(r - l, b - t),
|
||||
cornerRadius = CornerRadius(corner.value), alpha = a * f,
|
||||
)
|
||||
if (f > 0.01f) drawPath(ringRect(l, t, r - l, b - t, radii, 0f), color, alpha = a * f)
|
||||
if (f < 0.99f) {
|
||||
drawRoundRect(
|
||||
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
|
||||
cornerRadius = CornerRadius(rad), alpha = a * (1f - f) * fillAlpha,
|
||||
)
|
||||
drawRoundRect(
|
||||
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
|
||||
cornerRadius = CornerRadius(rad), style = Stroke(w), alpha = a,
|
||||
)
|
||||
val inner = ringRect(l + w / 2f, t + w / 2f, sw, sh, radii, w / 2f)
|
||||
drawPath(inner, color, alpha = a * (1f - f) * fillAlpha)
|
||||
drawPath(inner, color, style = Stroke(w), alpha = a)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,7 @@ import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -248,6 +249,7 @@ internal fun SetupPanel(
|
||||
if (listing) SettingsSearchResults(query) { section -> pick(section.ordinal) }
|
||||
else when (tab) {
|
||||
OVERVIEW_TAB -> {
|
||||
OnboardingCard(limitBlocks, a.onShowPhantomGate)
|
||||
// Setup's "Safe mode" row, under the GPU row while the bridge is on and can be used here.
|
||||
val bridgeModeRow = !s.adreno && s.vkBridge && com.droiddeck.launcher.core.DeviceSupport.bridgeUsable()
|
||||
val gpuCheck: @Composable (Boolean) -> Unit = { divider ->
|
||||
@@ -1273,3 +1275,65 @@ private fun CustomColorRows() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun OnboardingCard(limitBlocks: Boolean = false, onSetUpLimit: () -> Unit = {}) {
|
||||
val active by com.droiddeck.launcher.session.Onboarding.active.collectAsState()
|
||||
val failed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState()
|
||||
val facts by com.droiddeck.launcher.session.Onboarding.facts.collectAsState()
|
||||
val rows = com.droiddeck.launcher.session.Onboarding.rows(active, failed, facts)
|
||||
val settling = com.droiddeck.launcher.session.Onboarding.pending(rows)
|
||||
if (!settling) return
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val overall = com.droiddeck.launcher.session.Onboarding.overall(rows)
|
||||
Column(Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 12.dp)) {
|
||||
Text(stringResource(R.string.onboarding_title), fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
Text(stringResource(R.string.onboarding_summary, overall), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
LinearProgressIndicator(progress = { overall / 100f }, modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(4.dp))
|
||||
}
|
||||
rows.forEach { row ->
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
stringResource(when (row.step) {
|
||||
com.droiddeck.launcher.session.Onboarding.Step.RUNTIME -> R.string.onboarding_step_runtime
|
||||
com.droiddeck.launcher.session.Onboarding.Step.PROTON -> R.string.onboarding_step_proton
|
||||
com.droiddeck.launcher.session.Onboarding.Step.STEAM -> R.string.onboarding_step_steam
|
||||
}),
|
||||
fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
|
||||
)
|
||||
val detail = when (row.state) {
|
||||
com.droiddeck.launcher.session.Onboarding.State.ACTIVE -> row.label.orEmpty()
|
||||
com.droiddeck.launcher.session.Onboarding.State.FAILED -> stringResource(R.string.onboarding_failed)
|
||||
com.droiddeck.launcher.session.Onboarding.State.WAITING -> stringResource(R.string.onboarding_waiting)
|
||||
com.droiddeck.launcher.session.Onboarding.State.DONE -> stringResource(R.string.onboarding_done)
|
||||
}
|
||||
Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (row.state == com.droiddeck.launcher.session.Onboarding.State.ACTIVE) {
|
||||
if (row.percent >= 0) LinearProgressIndicator(progress = { row.percent / 100f }, modifier = Modifier.fillMaxWidth().padding(top = 6.dp).height(3.dp))
|
||||
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(top = 6.dp).height(3.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (limitBlocks) {
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(stringResource(R.string.setup_limit), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
Text(stringResource(R.string.onboarding_limit_reason), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
PrimaryButton(stringResource(R.string.onboarding_limit_action), compact = true, onClick = onSetUpLimit)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1157,7 +1157,7 @@ internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Add
|
||||
val message = withContext(Dispatchers.IO) {
|
||||
if (curse != null) {
|
||||
val (project, link) = curse
|
||||
val done = runCatching { link.call(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false)
|
||||
val done = runCatching { link.change(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false)
|
||||
WowAddons.changed()
|
||||
if (done) context.getString(R.string.user_apps_updated, name) else context.getString(R.string.stores_dl_failed_reason, name)
|
||||
} else update?.let { installAddon(context, it, target) { pct -> scope.launch { progress = pct } }.first }
|
||||
|
||||
@@ -57,7 +57,7 @@ internal fun ManageDrawerPages(offeredNow: List<SessionDrawerPage>, modifier: Mo
|
||||
SortableRows(
|
||||
rows = { current.map { it.name } },
|
||||
commit = { names -> DrawerPages.rearrange(ctx, names.mapNotNull { n -> current.firstOrNull { it.name == n } }) },
|
||||
movable = { true },
|
||||
movable = { it != SessionDrawerPage.MORE.name },
|
||||
rowHeight = STORE_ROW, handleWidth = STORE_HANDLE,
|
||||
releaseSignal = releaseSignal,
|
||||
onGrab = { before -> DrawerPages.heldFrom = before?.mapNotNull { n -> current.firstOrNull { it.name == n } } },
|
||||
@@ -66,6 +66,8 @@ internal fun ManageDrawerPages(offeredNow: List<SessionDrawerPage>, modifier: Mo
|
||||
},
|
||||
) { name, held, offset, hint, rowModifier, onFocus ->
|
||||
val page = current.first { it.name == name }
|
||||
// The same divider the launcher's Edit tabs uses: pages above it are tabs, pages below it are kept in More.
|
||||
if (page == SessionDrawerPage.MORE) { MoreLine(STORE_ROW); return@SortableRows }
|
||||
val shown = page !in DrawerPages.hidden
|
||||
val pal = LocalPalette.current
|
||||
val label = stringResource(page.title)
|
||||
|
||||
@@ -202,7 +202,7 @@ internal fun SideSheet(open: Boolean, onClose: () -> Unit, returnFocus: FocusReq
|
||||
if (!pad) return@LaunchedEffect
|
||||
repeat(60) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
if (holds || !open) return@LaunchedEffect
|
||||
if (holds || !open || Steps.open) return@LaunchedEffect
|
||||
runCatching { inside.requestFocus() }
|
||||
}
|
||||
}
|
||||
@@ -210,7 +210,7 @@ internal fun SideSheet(open: Boolean, onClose: () -> Unit, returnFocus: FocusReq
|
||||
Modifier.width(width).fillMaxHeight()
|
||||
.onFocusChanged { holds = it.hasFocus }
|
||||
.focusRequester(inside)
|
||||
.focusProperties { exit = { if (open) FocusRequester.Cancel else FocusRequester.Default } }
|
||||
.focusProperties { exit = { if (open && !Steps.open) FocusRequester.Cancel else FocusRequester.Default } }
|
||||
.focusGroup()
|
||||
.background(MaterialTheme.colorScheme.background)
|
||||
.border(1.dp, pal.line).padding(horizontal = 18.dp, vertical = 16.dp).testTag(tag),
|
||||
|
||||
@@ -27,7 +27,7 @@ internal object DeveloperTools {
|
||||
internal object NavTabs {
|
||||
const val MORE = "more"
|
||||
val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
||||
val DEFAULT_SHELVED = setOf("stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
||||
val DEFAULT_SHELVED = setOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
||||
val DEFAULT_HIDDEN = setOf("android-apps", "agent")
|
||||
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
||||
private val OLD_ORDER = listOf("steam", "games", "soundtracks", "stores", "downloads", "desktop", "agent", "components", "android-apps", "storage", "sync", "setup", "updates")
|
||||
|
||||
@@ -12,10 +12,11 @@ internal enum class SessionDrawerPage(val firstControl: String) {
|
||||
DISPLAY("fg"),
|
||||
HUD("hud"),
|
||||
EFFECTS("look"),
|
||||
VR("steamvr"),
|
||||
GAMES("anisotropy"),
|
||||
AGENT("agent-input"),
|
||||
SESSION("suspend"),
|
||||
MORE("more-edit"),
|
||||
VR("steamvr"),
|
||||
}
|
||||
|
||||
internal object DrawerPages {
|
||||
@@ -27,7 +28,7 @@ internal object DrawerPages {
|
||||
/** The order captured when a page row was grabbed in Arrange pages; Back restores it. */
|
||||
var heldFrom: List<SessionDrawerPage>? = null
|
||||
|
||||
fun hideable(page: SessionDrawerPage) = page != SessionDrawerPage.SESSION
|
||||
fun hideable(page: SessionDrawerPage) = page != SessionDrawerPage.SESSION && page != SessionDrawerPage.MORE
|
||||
|
||||
fun load(context: Context) {
|
||||
order = arrange(SessionPrefs.drawerPageOrder(context))
|
||||
@@ -81,6 +82,22 @@ internal fun sessionDrawerPages(
|
||||
hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
|
||||
): List<SessionDrawerPage> = offeredDrawerPages(hasGlasses, hasAgent).filter { it !in DrawerPages.hidden }
|
||||
|
||||
/** The pages shown as tabs: everything up to and including the More tab. */
|
||||
internal fun List<SessionDrawerPage>.strip(): List<SessionDrawerPage> {
|
||||
val more = indexOf(SessionDrawerPage.MORE)
|
||||
return if (more < 0) this else subList(0, more + 1)
|
||||
}
|
||||
|
||||
/** The pages kept inside More: those after the More tab. */
|
||||
internal fun List<SessionDrawerPage>.inMore(): List<SessionDrawerPage> {
|
||||
val more = indexOf(SessionDrawerPage.MORE)
|
||||
return if (more < 0) emptyList() else subList(more + 1, size)
|
||||
}
|
||||
|
||||
/** The tab that stands for [page]: the More tab for a page kept inside More. */
|
||||
internal fun List<SessionDrawerPage>.tabFor(page: SessionDrawerPage): SessionDrawerPage =
|
||||
if (page in inMore()) SessionDrawerPage.MORE else page
|
||||
|
||||
internal fun List<SessionDrawerPage>.step(current: SessionDrawerPage, direction: Int): SessionDrawerPage {
|
||||
val index = indexOf(current).coerceAtLeast(0)
|
||||
return this[Math.floorMod(index + direction, size)]
|
||||
|
||||
@@ -39,6 +39,7 @@ import androidx.compose.material.icons.outlined.AutoFixHigh
|
||||
import androidx.compose.material.icons.outlined.ExpandMore
|
||||
import androidx.compose.material.icons.outlined.Home
|
||||
import androidx.compose.material.icons.outlined.MoreHoriz
|
||||
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
|
||||
import androidx.compose.material.icons.outlined.PowerSettingsNew
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.material.icons.outlined.DesktopWindows
|
||||
@@ -95,6 +96,14 @@ import androidx.compose.ui.ExperimentalComposeUiApi
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import android.view.KeyEvent
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||
import androidx.compose.ui.layout.positionInRoot
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.HomeApp
|
||||
@@ -174,6 +183,7 @@ internal val SessionDrawerPage.title: Int get() = when (this) {
|
||||
SessionDrawerPage.GAMES -> R.string.game_settings_title
|
||||
SessionDrawerPage.AGENT -> R.string.rail_agent
|
||||
SessionDrawerPage.SESSION -> R.string.mode_session
|
||||
SessionDrawerPage.MORE -> R.string.drawer_page_more
|
||||
}
|
||||
|
||||
internal val SessionDrawerPage.icon get() = when (this) {
|
||||
@@ -186,6 +196,7 @@ internal val SessionDrawerPage.icon get() = when (this) {
|
||||
SessionDrawerPage.GAMES -> Icons.Outlined.Layers
|
||||
SessionDrawerPage.AGENT -> Icons.Outlined.Terminal
|
||||
SessionDrawerPage.SESSION -> Icons.Outlined.Settings
|
||||
SessionDrawerPage.MORE -> Icons.Outlined.MoreHoriz
|
||||
}
|
||||
|
||||
private class DrawerFocus {
|
||||
@@ -261,6 +272,8 @@ class DrawerActions(
|
||||
val textureLodBias: String? = TextureFiltering.LOD_BIAS_OFF,
|
||||
val secondScreenMode: SecondScreenMode,
|
||||
val secondScreenNone: Boolean = true,
|
||||
val dualScreenMode: String = com.droiddeck.launcher.input.DualScreen.MODE_AUTO,
|
||||
val onDualScreenMode: (String) -> Unit = {},
|
||||
val gameOnBottom: Boolean = false,
|
||||
val gameSwapAvailable: Boolean = false,
|
||||
val gameSwapBuiltIn: Boolean = true,
|
||||
@@ -418,6 +431,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
|
||||
var confirmStop by remember { mutableStateOf(false) }
|
||||
var sheetCoords by remember { mutableStateOf<LayoutCoordinates?>(null) }
|
||||
val widthContext = LocalContext.current
|
||||
var savedWidth by remember { mutableStateOf(SessionPrefs.drawerWidthDp(widthContext)) }
|
||||
var stopCoords by remember { mutableStateOf<LayoutCoordinates?>(null) }
|
||||
val pageScroll = remember { SessionDrawerPage.entries.associateWith { ScrollState(0) } }
|
||||
LaunchedEffect(glassesTab) {
|
||||
@@ -428,11 +443,17 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
val focus = remember { DrawerFocus() }
|
||||
val inputModeManager = LocalInputModeManager.current
|
||||
val focusManager = LocalFocusManager.current
|
||||
// A page kept inside More is one step deeper than the strip: back returns to More before it closes the menu.
|
||||
val insideMore = page in pages.inMore()
|
||||
BackHandler(enabled = open) {
|
||||
if (host.open != null) host.open = null else a.onClose()
|
||||
when {
|
||||
host.open != null -> host.open = null
|
||||
insideMore -> onPageChange(SessionDrawerPage.MORE)
|
||||
else -> a.onClose()
|
||||
}
|
||||
}
|
||||
BackHandler(enabled = open && confirmStop) { confirmStop = false }
|
||||
val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop)
|
||||
val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop || insideMore)
|
||||
LaunchedEffect(layerOpen) { onLayerChange(layerOpen) }
|
||||
var seenBackRequest by remember { mutableStateOf(backRequest) }
|
||||
LaunchedEffect(backRequest) {
|
||||
@@ -442,9 +463,10 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
confirmStop -> confirmStop = false
|
||||
appToChooseDisplay != null -> appToChooseDisplay = null
|
||||
host.open != null -> host.open = null
|
||||
insideMore -> onPageChange(SessionDrawerPage.MORE)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null }
|
||||
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null; managing = false }
|
||||
LaunchedEffect(a.selectedGameProfileId) {
|
||||
if (host.open == "fex") host.open = null
|
||||
}
|
||||
@@ -506,17 +528,22 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
}
|
||||
androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize().exposeTestTags(), contentAlignment = Alignment.CenterEnd) {
|
||||
val short = maxHeight < 440.dp
|
||||
val sheetWidth = if (docked) maxWidth else minOf(420.dp, maxWidth * 0.92f)
|
||||
// The handle keeps a strip on the left free, so a sheet dragged wide can always be dragged back.
|
||||
val maxSheet = (maxWidth - DRAWER_EDGE_GAP).coerceAtLeast(0.dp)
|
||||
val minSheet = minOf(DRAWER_MIN_WIDTH, maxSheet)
|
||||
val defaultSheet = minOf(420.dp, maxWidth * 0.92f)
|
||||
val sheetWidth = if (docked) maxWidth else (savedWidth?.dp ?: defaultSheet).coerceIn(minSheet, maxSheet)
|
||||
val narrow = sheetWidth < 320.dp
|
||||
AnimatedVisibility(
|
||||
open,
|
||||
enter = if (docked) fadeIn(Motion.tw(160)) else slideInHorizontally(Motion.sp(0.8f, Spring.StiffnessLow)) { it } + fadeIn(Motion.tw(220)),
|
||||
exit = if (docked) fadeOut(Motion.tw(140)) else slideOutHorizontally(Motion.tw(240)) { it } + fadeOut(Motion.tw(200)),
|
||||
) {
|
||||
FocusGlideHost(Modifier.fillMaxHeight().width(sheetWidth)) { Box(Modifier.fillMaxSize().onGloballyPositioned { sheetCoords = it }) {
|
||||
FocusGlideHost(Modifier.fillMaxHeight().width(if (docked) sheetWidth else sheetWidth + DRAWER_HANDLE_STRIP)) { Box(Modifier.fillMaxSize().onGloballyPositioned { sheetCoords = it }) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(start = if (docked) 0.dp else DRAWER_HANDLE_STRIP)
|
||||
.background(if (docked) pal.background else pal.background.copy(alpha = 0.97f))
|
||||
.blockTouches()
|
||||
.focusGroup()
|
||||
@@ -527,6 +554,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
DrawerPages.rearrange(drawerContext, held)
|
||||
releaseSignal++
|
||||
} ?: run { managing = false }
|
||||
insideMore -> onPageChange(SessionDrawerPage.MORE)
|
||||
else -> a.onClose()
|
||||
}
|
||||
}
|
||||
@@ -604,16 +632,14 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
|
||||
) {
|
||||
DrawerBumper("LB", stringResource(R.string.drawer_prev_page), modifier = focus.track(page, "prev")) {
|
||||
host.open = null; onPageChange(pages.step(page, -1))
|
||||
host.open = null; onPageChange(pages.strip().step(pages.tabFor(page), -1))
|
||||
}
|
||||
DrawerPageTabs(page = page, pages = pages, compact = true, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) }
|
||||
DrawerPageTabs(page = pages.tabFor(page), pages = pages.strip(), compact = true, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) }
|
||||
DrawerBumper("RB", stringResource(R.string.drawer_next_page), modifier = focus.track(page, "next")) {
|
||||
host.open = null; onPageChange(pages.step(page, 1))
|
||||
host.open = null; onPageChange(pages.strip().step(pages.tabFor(page), 1))
|
||||
}
|
||||
SmallIconButton(
|
||||
Icons.Outlined.Tune, stringResource(R.string.drawer_manage_pages), colors.onSurfaceVariant,
|
||||
) { host.open = null; managing = !managing }
|
||||
}
|
||||
if (insideMore && !managing) DrawerMoreBack(stringResource(page.title), focus.track(page, "more-back")) { host.open = null; onPageChange(SessionDrawerPage.MORE) }
|
||||
if (managing) ManageDrawerPages(
|
||||
offeredDrawerPages(a.glassesPresent),
|
||||
Modifier.weight(1f).fillMaxWidth().padding(top = 8.dp, start = 14.dp, end = 14.dp),
|
||||
@@ -888,6 +914,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
)
|
||||
}
|
||||
SessionDrawerPage.AGENT -> Unit
|
||||
SessionDrawerPage.MORE -> DrawerMorePage(host, pages.inMore(), { host.open = null; onPageChange(it) }, { host.open = null; managing = true }) { key -> focus.track(page, key) }
|
||||
SessionDrawerPage.SESSION -> {
|
||||
SettingsGroup(stringResource(R.string.drawer_support)) {
|
||||
SettingsRow(stringResource(R.string.report_problem), stringResource(R.string.report_problem_hint)) {
|
||||
@@ -965,6 +992,12 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
} }
|
||||
}
|
||||
}
|
||||
if (!docked) DrawerResizeHandle(
|
||||
width = sheetWidth, min = minSheet, max = maxSheet,
|
||||
onWidth = { savedWidth = it.value.roundToInt() },
|
||||
onCommit = { savedWidth?.let { SessionPrefs.setDrawerWidthDp(widthContext, it) } },
|
||||
modifier = Modifier.align(Alignment.CenterStart).then(focus.track(page, "resize")),
|
||||
)
|
||||
StopConfirm(
|
||||
open = confirmStop,
|
||||
pill = sheetCoords?.let { sc -> stopCoords?.takeIf { it.isAttached && sc.isAttached }?.let { sc.localBoundingBoxOf(it, clipBounds = false) } },
|
||||
@@ -1152,6 +1185,70 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPag
|
||||
|
||||
private const val LOOK_CUSTOM = "custom"
|
||||
|
||||
/** The row above a page kept inside More that goes back to the More list. */
|
||||
@Composable
|
||||
private fun DrawerMoreBack(title: String, modifier: Modifier, onBack: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
|
||||
val shape = RoundedCornerShape(12.dp)
|
||||
val label = stringResource(R.string.drawer_more_back, stringResource(R.string.drawer_page_more))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = modifier.padding(top = 8.dp, start = 14.dp, end = 14.dp).fillMaxWidth().heightIn(min = 44.dp).clip(shape)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
|
||||
.glideBorder(hot, shape, pal.signal)
|
||||
.testTag("drawer-more-back")
|
||||
.hoverable(source)
|
||||
.clickable(interactionSource = source, indication = null, role = androidx.compose.ui.semantics.Role.Button, onClick = onBack)
|
||||
.controllerConfirm(onClick = onBack)
|
||||
.semantics { contentDescription = label }
|
||||
.padding(horizontal = 8.dp),
|
||||
) {
|
||||
Icon(Icons.AutoMirrored.Outlined.ArrowBack, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(22.dp))
|
||||
Text(stringResource(R.string.drawer_page_more), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
Text("·", fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
/** The pages kept inside More, and the way into arranging which pages sit on the strip and which here. */
|
||||
@Composable
|
||||
private fun DrawerMorePage(host: MenuHost, pages: List<SessionDrawerPage>, onOpen: (SessionDrawerPage) -> Unit, onEdit: () -> Unit, track: (String) -> Modifier) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
SettingsGroup(stringResource(R.string.drawer_page_more)) {
|
||||
if (pages.isEmpty()) Text(
|
||||
stringResource(R.string.drawer_more_empty), fontSize = 13.sp, color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
)
|
||||
for (item in pages) {
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
|
||||
val shape = RoundedCornerShape(12.dp)
|
||||
val open = { onOpen(item) }
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).clip(shape)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
|
||||
.glideBorder(hot, shape, pal.signal)
|
||||
.then(track("more-${item.name.lowercase()}"))
|
||||
.testTag("drawer-more-${item.name.lowercase()}")
|
||||
.hoverable(source)
|
||||
.clickable(interactionSource = source, indication = null, role = androidx.compose.ui.semantics.Role.Button, onClick = open)
|
||||
.controllerConfirm(onClick = open)
|
||||
.padding(horizontal = 14.dp),
|
||||
) {
|
||||
Icon(item.icon, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(22.dp))
|
||||
Text(stringResource(item.title), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
DrawerOutlineButton(stringResource(R.string.drawer_manage_pages), modifier = track("more-edit").testTag("drawer-more-edit"), onClick = onEdit)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ScreenEffectsGroup(
|
||||
host: MenuHost, a: DrawerActions, advancedExpanded: Boolean, onAdvancedToggle: () -> Unit,
|
||||
@@ -1338,12 +1435,92 @@ internal fun secondScreenModes(none: Boolean, deckPad: Boolean, dashboard: Boole
|
||||
(if (dashboard) listOf(SecondScreenMode.DASHBOARD) else emptyList()) +
|
||||
(if (desktop) listOf(SecondScreenMode.DESKTOP) else emptyList())
|
||||
|
||||
private val DRAWER_MIN_WIDTH = 300.dp
|
||||
private val DRAWER_HANDLE_STRIP = 24.dp
|
||||
private val DRAWER_EDGE_GAP = 80.dp
|
||||
|
||||
/** A grip on the sheet's left edge: dragging it, or pressing left and right on a controller, resizes the sheet. */
|
||||
@Composable
|
||||
private fun DrawerResizeHandle(width: Dp, min: Dp, max: Dp, onWidth: (Dp) -> Unit, onCommit: () -> Unit, modifier: Modifier) {
|
||||
val pal = LocalPalette.current
|
||||
val density = LocalDensity.current
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val focused by source.collectIsFocusedAsState()
|
||||
var dragging by remember { mutableStateOf(false) }
|
||||
var coords by remember { mutableStateOf<LayoutCoordinates?>(null) }
|
||||
val current by rememberUpdatedState(width)
|
||||
val lower by rememberUpdatedState(min)
|
||||
val upper by rememberUpdatedState(max)
|
||||
val change by rememberUpdatedState(onWidth)
|
||||
val commit by rememberUpdatedState(onCommit)
|
||||
val hot = focused || dragging
|
||||
val label = stringResource(R.string.drawer_resize)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = modifier.width(24.dp).height(96.dp)
|
||||
.onGloballyPositioned { coords = it }
|
||||
.focusable(true, source)
|
||||
.onPreviewKeyEvent { event ->
|
||||
val key = event.nativeKeyEvent
|
||||
val wider = key.keyCode == KeyEvent.KEYCODE_DPAD_LEFT
|
||||
if (!wider && key.keyCode != KeyEvent.KEYCODE_DPAD_RIGHT) false
|
||||
else {
|
||||
if (key.action == KeyEvent.ACTION_DOWN) {
|
||||
change((current + if (wider) 24.dp else (-24).dp).coerceIn(lower, upper))
|
||||
commit()
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
// The handle moves with the finger as the sheet resizes, so the drag is measured on the screen.
|
||||
.pointerInput(Unit) {
|
||||
awaitEachGesture {
|
||||
val down = awaitFirstDown(requireUnconsumed = false)
|
||||
var last = (coords?.positionInRoot()?.x ?: 0f) + down.position.x
|
||||
// Several moves can arrive before the sheet recomposes, so the width is accumulated here.
|
||||
var live = current
|
||||
dragging = true
|
||||
do {
|
||||
val event = awaitPointerEvent()
|
||||
val pointer = event.changes.firstOrNull() ?: break
|
||||
val x = (coords?.positionInRoot()?.x ?: 0f) + pointer.position.x
|
||||
val delta = with(density) { (x - last).toDp() }
|
||||
last = x
|
||||
if (delta != 0.dp) {
|
||||
live = (live - delta).coerceIn(lower, upper)
|
||||
change(live)
|
||||
}
|
||||
pointer.consume()
|
||||
} while (event.changes.any { it.pressed })
|
||||
dragging = false
|
||||
commit()
|
||||
}
|
||||
}
|
||||
.semantics {
|
||||
contentDescription = label
|
||||
stateDescription = "${width.value.roundToInt()} dp"
|
||||
},
|
||||
) {
|
||||
Box(
|
||||
Modifier.width(if (hot) 6.dp else 4.dp).height(56.dp).clip(CircleShape)
|
||||
.background(if (hot) pal.signal else pal.onSurfaceVariant.copy(alpha = 0.55f)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
|
||||
val choosesDisplay = a.secondScreenDisplays.size > 1
|
||||
val swapsGame = a.gameSwapAvailable || a.gameOnBottom
|
||||
if (!choosesDisplay && !swapsGame) return
|
||||
val hasSecondScreen = a.secondScreenDisplays.isNotEmpty()
|
||||
if (!hasSecondScreen && !choosesDisplay && !swapsGame) return
|
||||
SettingsGroup(stringResource(R.string.drawer_second_screen)) {
|
||||
if (hasSecondScreen) ChoiceRow(host, "dual-screen-mode", stringResource(R.string.setup_dual_screen_sessions), null,
|
||||
listOf(
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_AUTO to stringResource(R.string.setup_dual_screen_auto),
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_ON to stringResource(R.string.setup_dual_screen_on),
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_OFF to stringResource(R.string.setup_dual_screen_off),
|
||||
), a.dualScreenMode, chipModifier = track("dual-screen-mode"), onPick = a.onDualScreenMode)
|
||||
if (swapsGame) ChoiceRow(host, "game-screen", stringResource(R.string.swap_game_screen), null,
|
||||
if (a.gameSwapBuiltIn) listOf(false to stringResource(R.string.swap_game_screen_top), true to stringResource(R.string.swap_game_screen_bottom))
|
||||
else listOf(false to stringResource(R.string.main_primary), true to stringResource(R.string.main_secondary)),
|
||||
|
||||
@@ -31,6 +31,7 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
@@ -154,8 +155,24 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
||||
scrim = { if (games.size >= WALL_MIN_GAMES) WallFade() },
|
||||
words = {
|
||||
val runtimeStatus: @Composable () -> Unit = {
|
||||
if (s.busy || (s.available != null && s.available != s.installed)) RuntimeChip(s)
|
||||
else if (setupNeedsAttention(s)) SecondaryButton(stringResource(R.string.play_needs_you), compact = true,
|
||||
val onboardingActive by com.droiddeck.launcher.session.Onboarding.active.collectAsState()
|
||||
val onboardingFailed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState()
|
||||
val onboardingFacts by com.droiddeck.launcher.session.Onboarding.facts.collectAsState()
|
||||
val onboardingRows = com.droiddeck.launcher.session.Onboarding.rows(onboardingActive, onboardingFailed, onboardingFacts)
|
||||
val settling = onboardingActive.isNotEmpty() && com.droiddeck.launcher.session.Onboarding.pending(onboardingRows)
|
||||
if (settling || s.busy || (s.available != null && s.available != s.installed)) {
|
||||
if (settling) {
|
||||
val overall = com.droiddeck.launcher.session.Onboarding.overall(onboardingRows)
|
||||
Chip(
|
||||
stringResource(R.string.onboarding_chip, overall, onboardingRows.firstOrNull { it.state == com.droiddeck.launcher.session.Onboarding.State.ACTIVE }?.label.orEmpty()),
|
||||
ok = false, fraction = overall / 100f,
|
||||
)
|
||||
} else RuntimeChip(s)
|
||||
if (com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)) {
|
||||
SecondaryButton(stringResource(R.string.onboarding_limit_while_waiting), compact = true,
|
||||
modifier = Modifier.testTag("setup-while-waiting"), onClick = a.onShowPhantomGate)
|
||||
}
|
||||
} else if (setupNeedsAttention(s)) SecondaryButton(stringResource(R.string.play_needs_you), compact = true,
|
||||
modifier = Modifier.testTag("play-needs-you")) { SetupTabs.openSection = SettingsSection.OVERVIEW }
|
||||
else if (s.integration.suggested && signedIn && !com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus))
|
||||
IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration)
|
||||
|
||||
@@ -23,6 +23,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.AutoAwesome
|
||||
import androidx.compose.material.icons.outlined.Close
|
||||
import androidx.compose.material.icons.outlined.Bluetooth
|
||||
import androidx.compose.material.icons.outlined.Home
|
||||
import androidx.compose.material.icons.outlined.KeyboardCommandKey
|
||||
import androidx.compose.material.icons.outlined.LightMode
|
||||
@@ -61,6 +62,7 @@ internal fun SteamIntegration.State.enabled(feature: Feature) = when (feature) {
|
||||
Feature.BRIGHTNESS -> brightness
|
||||
Feature.HOME -> home
|
||||
Feature.SHORTCUTS -> shortcuts
|
||||
Feature.BLUETOOTH -> bluetooth
|
||||
}
|
||||
|
||||
internal fun SteamIntegration.State.enabledCount() = Feature.entries.count { enabled(it) }
|
||||
@@ -116,6 +118,7 @@ private fun IntegrationRow(
|
||||
feature == Feature.WIFI -> if (on) R.string.integration_wifi_on else R.string.integration_wifi_hint
|
||||
feature == Feature.BRIGHTNESS -> R.string.integration_brightness_hint
|
||||
feature == Feature.HOME -> R.string.integration_home_hint
|
||||
feature == Feature.BLUETOOTH -> R.string.integration_bluetooth_hint
|
||||
else -> R.string.integration_shortcuts_hint
|
||||
})
|
||||
Row(
|
||||
@@ -164,6 +167,7 @@ private fun featureIcon(feature: Feature) = when (feature) {
|
||||
Feature.BRIGHTNESS -> Icons.Outlined.LightMode
|
||||
Feature.HOME -> Icons.Outlined.Home
|
||||
Feature.SHORTCUTS -> Icons.Outlined.KeyboardCommandKey
|
||||
Feature.BLUETOOTH -> Icons.Outlined.Bluetooth
|
||||
}
|
||||
|
||||
private fun featureTitle(feature: Feature) = when (feature) {
|
||||
@@ -171,6 +175,7 @@ private fun featureTitle(feature: Feature) = when (feature) {
|
||||
Feature.BRIGHTNESS -> R.string.integration_brightness
|
||||
Feature.HOME -> R.string.integration_home
|
||||
Feature.SHORTCUTS -> R.string.integration_shortcuts
|
||||
Feature.BLUETOOTH -> R.string.integration_bluetooth
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -45,6 +45,7 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.geometry.Rect
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Matrix
|
||||
@@ -174,6 +175,7 @@ internal fun StepOut(
|
||||
var grown by remember { mutableStateOf(false) }
|
||||
var measured by remember { mutableStateOf<IntSize?>(null) }
|
||||
val first = remember { FocusRequester() }
|
||||
var holdsFocus by remember { mutableStateOf(false) }
|
||||
val glide = LocalFocusGlide.current
|
||||
val opener = remember { arrayOfNulls<GlideSource>(1) }
|
||||
val openNow = androidx.compose.runtime.rememberUpdatedState(open)
|
||||
@@ -241,8 +243,12 @@ internal fun StepOut(
|
||||
LaunchedEffect(open, measured) {
|
||||
if (!open || measured == null || inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect
|
||||
delay(Motion.ms(300).toLong())
|
||||
withFrameNanos { }
|
||||
runCatching { first.requestFocus() }
|
||||
// Another focus group can hold on to focus for a few frames, so the request is repeated until it lands.
|
||||
repeat(30) {
|
||||
withFrameNanos { }
|
||||
if (holdsFocus) return@LaunchedEffect
|
||||
runCatching { first.requestFocus() }
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(open, grown, inputMode.inputMode) {
|
||||
@@ -289,6 +295,7 @@ internal fun StepOut(
|
||||
.heightIn(max = availableHeight)
|
||||
.onSizeChanged { if (measured != it) measured = it }
|
||||
.controllerBack(onDismiss)
|
||||
.onFocusChanged { holdsFocus = it.hasFocus }
|
||||
.focusProperties { exit = { if (openNow.value) FocusRequester.Cancel else FocusRequester.Default } }
|
||||
.focusGroup()
|
||||
.verticalScroll(rememberScrollState())
|
||||
|
||||
@@ -213,10 +213,10 @@ internal fun SortableRows(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MoreLine() {
|
||||
internal fun MoreLine(height: androidx.compose.ui.unit.Dp = TAB_ROW) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Column(Modifier.fillMaxWidth().height(TAB_ROW).testTag("tab-more-line")) {
|
||||
Column(Modifier.fillMaxWidth().height(height).testTag("tab-more-line")) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
|
||||
@@ -36,7 +36,7 @@
|
||||
<string name="wall_settings_match" translatable="false">Match screen</string>
|
||||
<string name="wall_settings_speed" translatable="false">Scroll speed</string>
|
||||
<string-array name="loading_hints">
|
||||
<item>First run downloads Steam. This may take a few minutes.</item>
|
||||
<item>DroidDeck downloads Steam in the background while you set up, so your first launch is quicker.</item>
|
||||
<item>Your controller shows up to Steam as a Steam Deck controller. Switch it to a Steam Controller, DualShock 4, DualSense or Xbox 360 pad in the session settings; it applies next session.</item>
|
||||
<item>Hold Back on your controller to open Steam\'s Quick Access menu. Hold Back for Steam shortcuts must be on in the session settings.</item>
|
||||
<item>Background behavior decides what happens when you leave the app: Native readies Steam for sleep, Auto pauses it, Manual waits for Resume, Never keeps it running.</item>
|
||||
@@ -704,6 +704,9 @@
|
||||
<string name="drawer_prev_page">Previous page</string>
|
||||
<string name="drawer_next_page">Next page</string>
|
||||
<string name="drawer_manage_pages">Arrange pages</string>
|
||||
<string name="drawer_page_more">More</string>
|
||||
<string name="drawer_more_back">Back to %1$s</string>
|
||||
<string name="drawer_more_empty">Nothing is kept here. Arrange pages and move one below the More row.</string>
|
||||
<string name="drawer_pages_reset">Reset</string>
|
||||
<string name="drawer_pages_done">Done</string>
|
||||
<string name="drawer_hud">Performance HUD</string>
|
||||
@@ -864,6 +867,7 @@
|
||||
<string name="drawer_pc_keyboard">PC keyboard</string>
|
||||
<string name="drawer_android_keyboard">Android</string>
|
||||
<string name="drawer_second_screen">Second screen</string>
|
||||
<string name="drawer_resize">Resize the menu</string>
|
||||
<string name="drawer_second_screen_shows">Shows</string>
|
||||
<string name="drawer_android_apps">Android apps</string>
|
||||
<string name="drawer_launch_app">Launch an app</string>
|
||||
@@ -2217,6 +2221,23 @@
|
||||
<string name="fm_favorite_removed">Removed \"%1$s\" from Favorites</string>
|
||||
<string name="fm_empty_directory">Empty directory</string>
|
||||
<string name="fm_up_one_level">Up one level</string>
|
||||
<string name="fm_edit_open">Open</string>
|
||||
<string name="fm_edit_save">Save</string>
|
||||
<string name="fm_edit_read_only">Read only</string>
|
||||
<string name="fm_edit_binary">Binary</string>
|
||||
<string name="fm_edit_modified">Modified</string>
|
||||
<string name="fm_edit_position">Ln %1$d, Col %2$d</string>
|
||||
<string name="fm_edit_find">Find</string>
|
||||
<string name="fm_edit_find_previous">Find previous</string>
|
||||
<string name="fm_edit_find_next">Find next</string>
|
||||
<string name="fm_edit_replace">Replace</string>
|
||||
<string name="fm_edit_replace_all">All</string>
|
||||
<string name="fm_edit_discard_title">Discard changes?</string>
|
||||
<string name="fm_edit_discard_text">Changes to \"%1$s\" will be lost.</string>
|
||||
<string name="fm_edit_discard">Discard</string>
|
||||
<string name="fm_edit_save_failed">Couldn\'t save \"%1$s\"</string>
|
||||
<string name="fm_edit_open_failed">Couldn\'t open \"%1$s\"</string>
|
||||
<string name="fm_edit_too_large">Too large to open (%1$s)</string>
|
||||
<string name="fm_choose_folder">Choose a folder</string>
|
||||
<string name="fm_choose_file">Choose a file</string>
|
||||
<string name="ctrl_tint_steam_blue">Steam blue</string>
|
||||
@@ -4132,6 +4153,8 @@
|
||||
<string name="integration_wifi_denied">Location denied · allow it in App info</string>
|
||||
<string name="integration_brightness_hint">Steam’s slider sets screen brightness</string>
|
||||
<string name="integration_home_hint">Home opens the Steam menu in a session</string>
|
||||
<string name="integration_bluetooth">Bluetooth controllers</string>
|
||||
<string name="integration_bluetooth_hint">Lets DroidDeck connect to Steam Controllers and other Bluetooth pads</string>
|
||||
<string name="integration_shortcuts_hint">Alt+Tab, Win key and Home button stay in the session</string>
|
||||
<string name="integration_shortcuts_maybe_restricted">Greyed out in Android? App info → ⋮ → Allow restricted settings</string>
|
||||
<string name="integration_shortcuts_install_failed">System keys didn\'t install</string>
|
||||
@@ -4405,4 +4428,19 @@
|
||||
<string name="tabs_reset_title">Reset tabs</string>
|
||||
<string name="tabs_reset_hint">Steam, Desktop, Library, Downloads, Settings and Updates on the bar, the rest under More.</string>
|
||||
<string name="tabs_reset_body">Your tab order and what sits under More or is hidden go back to the defaults.</string>
|
||||
<string name="onboarding_title">Getting DroidDeck ready</string>
|
||||
<string name="onboarding_summary">%1$d%% · you can keep using the app</string>
|
||||
<string name="onboarding_step_runtime">Linux runtime</string>
|
||||
<string name="onboarding_step_proton">DroidDeck Proton</string>
|
||||
<string name="onboarding_step_steam">Steam client</string>
|
||||
<string name="onboarding_waiting">Waiting</string>
|
||||
<string name="onboarding_done">Ready</string>
|
||||
<string name="onboarding_failed">Will retry</string>
|
||||
<string name="onboarding_steam_downloading">Downloading the Steam client</string>
|
||||
<string name="onboarding_steam_downloading_mb">Downloading the Steam client (%1$d MB)</string>
|
||||
<string name="onboarding_steam_failed">The Steam client download will retry</string>
|
||||
<string name="onboarding_limit_reason">Android can close Steam’s helper processes. Turn that off now, while the downloads run, and Play is ready the moment they finish.</string>
|
||||
<string name="onboarding_limit_action">Do it for me</string>
|
||||
<string name="onboarding_limit_while_waiting">Set up while you wait</string>
|
||||
<string name="onboarding_chip">Getting ready · %1$d%% · %2$s</string>
|
||||
</resources>
|
||||
@@ -35,6 +35,7 @@ import java.util.concurrent.atomic.AtomicInteger
|
||||
class ProtonMenuAutoTest {
|
||||
private val online = AutoComponents.online
|
||||
private val constrained = AutoComponents.unfavourable
|
||||
private val firstRunHeldBack = AutoComponents.firstRunHeldBack
|
||||
private lateinit var activity: Activity
|
||||
private lateinit var menu: ProtonMenu
|
||||
private lateinit var root: File
|
||||
@@ -49,6 +50,7 @@ class ProtonMenuAutoTest {
|
||||
}
|
||||
AutoComponents.online = { true }
|
||||
AutoComponents.unfavourable = { false }
|
||||
AutoComponents.firstRunHeldBack = { false }
|
||||
SessionState.running = false
|
||||
SessionState.phase = SessionPhase.IDLE
|
||||
SessionState.stopRequested = false
|
||||
@@ -63,6 +65,7 @@ class ProtonMenuAutoTest {
|
||||
menu.protonProblem = null
|
||||
menu.protonStage = null
|
||||
menu.protonPercent = -1
|
||||
menu.experimentalRefresh = { emptyList() }
|
||||
menu.installer = { tool, progress ->
|
||||
progress("Installing ${tool.name}", 50)
|
||||
install("${tool.prefix}-11-12")
|
||||
@@ -77,6 +80,7 @@ class ProtonMenuAutoTest {
|
||||
menu.protonPercent = -1
|
||||
AutoComponents.online = online
|
||||
AutoComponents.unfavourable = constrained
|
||||
AutoComponents.firstRunHeldBack = firstRunHeldBack
|
||||
SessionState.running = false
|
||||
SessionState.phase = SessionPhase.IDLE
|
||||
SessionState.stopRequested = false
|
||||
|
||||
@@ -11,13 +11,13 @@ class AgentStorageTest {
|
||||
@Test fun removingAFolderKeepsWhatItsLinksPointAt() {
|
||||
val base = Files.createTempDirectory("agent-storage")
|
||||
val outside = Files.createDirectories(base.resolve("sdcard"))
|
||||
Files.write(outside.resolve("save.dat"), ByteArray(100))
|
||||
Files.write(outside.resolve("save.dat"), ByteArray(1 shl 20))
|
||||
val item = Files.createDirectories(base.resolve("rootfs/android-sdk"))
|
||||
Files.write(item.resolve("a.jar"), ByteArray(10))
|
||||
val linked = runCatching { Files.createSymbolicLink(item.resolve("saves"), outside) }.isSuccess
|
||||
assumeTrue("symbolic links need privileges on this OS", linked)
|
||||
|
||||
assertTrue(AgentStorage.size(item) < 100)
|
||||
assertTrue(AgentStorage.size(item) < 1 shl 20)
|
||||
AgentStorage.delete(item)
|
||||
assertFalse(Files.exists(item))
|
||||
assertTrue(Files.exists(outside.resolve("save.dat")))
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
package com.droiddeck.launcher.files
|
||||
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.File
|
||||
import java.nio.charset.Charset
|
||||
import java.nio.file.Files
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class TextEditorLogicTest {
|
||||
|
||||
@Test
|
||||
fun nulByteMarksBinary() {
|
||||
val clean = "hello world".toByteArray()
|
||||
assertFalse(editorIsBinary(clean))
|
||||
val withNul = byteArrayOf(1, 2, 0, 3)
|
||||
assertTrue(editorIsBinary(withNul))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun binaryScanStopsAtSampleLimit() {
|
||||
val bytes = ByteArray(9000) { if (it == 8999) 0 else 65 }
|
||||
assertFalse(editorIsBinary(bytes))
|
||||
assertTrue(editorIsBinary(bytes, sample = 9000))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun utf8TextDecodesAsUtf8() {
|
||||
val decoded = decodeEditorText("你好, world".toByteArray(Charsets.UTF_8))
|
||||
assertEquals(EditorCharset.UTF8, decoded.charset)
|
||||
assertFalse(decoded.lossy)
|
||||
assertEquals("你好, world", decoded.text)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gbkBytesFallBackToGb18030() {
|
||||
val gbk = "你好".toByteArray(Charset.forName("GBK"))
|
||||
val decoded = decodeEditorText(gbk)
|
||||
assertEquals(EditorCharset.GB18030, decoded.charset)
|
||||
assertFalse(decoded.lossy)
|
||||
assertEquals("你好", decoded.text)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun undecodableBytesStayLossyUtf8() {
|
||||
val decoded = decodeEditorText(byteArrayOf(0xFF.toByte()))
|
||||
assertEquals(EditorCharset.UTF8, decoded.charset)
|
||||
assertTrue(decoded.lossy)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun literalReplacementCharStaysCleanUtf8() {
|
||||
val decoded = decodeEditorText("�A".toByteArray(Charsets.UTF_8))
|
||||
assertEquals(EditorCharset.UTF8, decoded.charset)
|
||||
assertFalse(decoded.lossy)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun readCappedRefusesOverLimit() {
|
||||
val data = ByteArray(100) { 65 }
|
||||
assertArrayEquals(data, readCapped(ByteArrayInputStream(data), 100L))
|
||||
assertNull(readCapped(ByteArrayInputStream(data), 99L))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tabsExpandToTabStops() {
|
||||
assertEquals("ab c", expandEditorTabs("ab\tc"))
|
||||
assertEquals(" x", expandEditorTabs("\tx"))
|
||||
assertEquals("abcd e", expandEditorTabs("abcd\te"))
|
||||
assertEquals("abc def g", expandEditorTabs("abc\tdef\tg"))
|
||||
assertEquals("a \n b", expandEditorTabs("a\t\n\tb"))
|
||||
assertEquals("plain text", expandEditorTabs("plain text"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lineCountCountsTrailingEmptyLine() {
|
||||
assertEquals(1, lineCountOf(""))
|
||||
assertEquals(1, lineCountOf("abc"))
|
||||
assertEquals(2, lineCountOf("a\nb"))
|
||||
assertEquals(2, lineCountOf("a\n"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun offsetMapsToZeroBasedLineAndOneBasedColumn() {
|
||||
val text = "ab\ncd"
|
||||
assertEquals(0, lineIndexOfOffset(text, 0))
|
||||
assertEquals(0, lineIndexOfOffset(text, 2))
|
||||
assertEquals(1, lineIndexOfOffset(text, 3))
|
||||
assertEquals(1, lineIndexOfOffset(text, 5))
|
||||
assertEquals(1, columnOfOffset(text, 0))
|
||||
assertEquals(3, columnOfOffset(text, 2))
|
||||
assertEquals(2, columnOfOffset(text, 4))
|
||||
assertEquals(3, columnOfOffset(text, 5))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun findMatchesHonorsCaseAndLimit() {
|
||||
val text = "abcABCabc"
|
||||
val all = findEditorMatches(text, "abc", matchCase = false)
|
||||
assertEquals(listOf(0..2, 3..5, 6..8), all)
|
||||
val exact = findEditorMatches(text, "abc", matchCase = true)
|
||||
assertEquals(listOf(0..2, 6..8), exact)
|
||||
assertEquals(2, findEditorMatches(text, "abc", matchCase = false, limit = 2).size)
|
||||
assertEquals(emptyList<IntRange>(), findEditorMatches(text, ""))
|
||||
assertEquals(listOf(0..1), findEditorMatches("aaa", "aa"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun replaceSpansEveryMatch() {
|
||||
val text = "one two one"
|
||||
val matches = findEditorMatches(text, "one", matchCase = true)
|
||||
assertEquals("1 two 1", replaceEditorMatches(text, matches, "1"))
|
||||
assertEquals(text, replaceEditorMatches(text, emptyList(), "x"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun saveTargetResolvesSymbolicLink() {
|
||||
val dir = Files.createTempDirectory("editor-link").toFile()
|
||||
try {
|
||||
val target = File(dir, "real.txt").apply { writeText("hi") }
|
||||
val link = File(dir, "link.txt")
|
||||
Files.createSymbolicLink(link.toPath(), target.toPath())
|
||||
assertEquals(target.canonicalFile, resolveEditorSaveTarget(link))
|
||||
} finally {
|
||||
dir.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun saveTargetKeepsRegularFile() {
|
||||
val dir = Files.createTempDirectory("editor-plain").toFile()
|
||||
try {
|
||||
val plain = File(dir, "plain.txt").apply { writeText("hi") }
|
||||
assertEquals(plain, resolveEditorSaveTarget(plain))
|
||||
} finally {
|
||||
dir.deleteRecursively()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -354,13 +354,15 @@ class BattleNetTest {
|
||||
assertEquals(codes.distinct(), codes)
|
||||
assertTrue("Fen" in codes && "OSI" in codes && "WTCG" in codes)
|
||||
assertFalse(BattleNet.STORE.any { it.uid == "d3cn" || it.uid == "fen" })
|
||||
assertFalse(BattleNet.STORE.any { it.code == "WoWC" || it.code == "WoWF" })
|
||||
assertFalse(BattleNet.STORE.any { it.code == "WoWC" })
|
||||
assertEquals("wow_forever", BattleNet.STORE.first { it.code == "WoWF" }.uid)
|
||||
assertEquals("fenris", BattleNet.STORE.first { it.code == "Fen" }.uid)
|
||||
assertTrue(BattleNet.STORE.all { it.uid.matches(Regex("[a-z0-9_]{1,32}")) })
|
||||
val installed = listOf("fenris", "diablo3_enus", null)
|
||||
val offered = BattleNet.STORE.filter { BattleNet.notInstalled(it, installed) }.map { it.code }
|
||||
assertFalse("Fen" in offered || "D3" in offered)
|
||||
assertTrue("OSI" in offered)
|
||||
assertTrue("OSI" in offered && "WoWF" in offered)
|
||||
assertFalse("WoWF" in BattleNet.STORE.filter { BattleNet.notInstalled(it, listOf("wow_forever")) }.map { it.code })
|
||||
}
|
||||
|
||||
@Test fun aBattleNetGameStartsWithoutSteamThroughItsShortcutUntilThatIsSwitchedOff() {
|
||||
|
||||
@@ -5,6 +5,7 @@ import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
@@ -158,6 +159,7 @@ class CurseForgeAppTest {
|
||||
assertTrue(text.startsWith("(() => { const w = require('electron').BrowserWindow.getAllWindows()"))
|
||||
assertTrue(text.contains("desktop.html"))
|
||||
assertTrue(text.contains("executeJavaScript("))
|
||||
assertTrue(text.contains("let m = globalThis.__droiddeckServices; if (!m || !m[\\\"ProjectAppService\\\"]) m = globalThis.__droiddeckServices = "))
|
||||
assertFalse(text.contains("show()"))
|
||||
val probe = CurseForgeApp.expression("InstalledProjectsAppService", "installAddon", null)
|
||||
assertFalse(probe.contains("await s["))
|
||||
@@ -292,6 +294,37 @@ class CurseForgeAppTest {
|
||||
assertTrue(calls.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aGameFolderCurseForgeAlreadyKnowsSkipsTheFolderDetection() {
|
||||
val flavor = "/root/Games/World of Warcraft/_retail_"
|
||||
val curse = fakeCurse(flavor = flavor)
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
assertEquals("g", CurseForgeApp.instance(context, url, "/root/Games/World of Warcraft", flavor))
|
||||
assertFalse("detectGameFromPath" in curse.methods)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aGameFolderCurseForgeDoesNotKnowIsDetectedOnce() {
|
||||
val flavor = "/root/Games/World of Warcraft/_retail_"
|
||||
val curse = fakeCurse(flavor = flavor)
|
||||
curse.known = false
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
assertEquals("g", CurseForgeApp.instance(context, url, "/root/Games/World of Warcraft", flavor))
|
||||
assertEquals(1, curse.methods.count { it == "detectGameFromPath" })
|
||||
assertEquals(listOf("getGameInstances", "detectGameFromPath", "getGameInstances"), curse.methods.filter { it != "connect" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun curseForgeConnectsOncePerLaunch() {
|
||||
val curse = fakeCurse()
|
||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
||||
val launched = "ws://127.0.0.1:43118/${java.util.UUID.randomUUID()}"
|
||||
CurseForgeApp.projects(context, launched, "g")
|
||||
CurseForgeApp.projects(context, launched, "g")
|
||||
CurseForgeApp.instance(context, launched, "/root", "")
|
||||
assertEquals(1, curse.methods.count { it == "connect" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theInspectorUrlIsRedactedFromCommandLogs() {
|
||||
val line = CurseForgeApp.evalArgv(url, "x", 1_000).joinToString(" ")
|
||||
@@ -305,6 +338,7 @@ class CurseForgeAppTest {
|
||||
val methods = java.util.Collections.synchronizedList(mutableListOf<String>())
|
||||
@Volatile var unreachableAfterDelete = false
|
||||
@Volatile var unreachable = false
|
||||
@Volatile var known = true
|
||||
|
||||
fun add(id: String, folder: String, status: Int) = add(id, listOf(folder), status)
|
||||
|
||||
@@ -328,8 +362,11 @@ class CurseForgeAppTest {
|
||||
projects.forEach { it.put("status", 1) }
|
||||
true
|
||||
}
|
||||
"detectGameFromPath" -> JSONObject().put("gameInstanceGuid", "g")
|
||||
"getGameInstances" -> JSONArray().put(JSONObject().put("guid", "g").put("installPath", flavor))
|
||||
"detectGameFromPath" -> {
|
||||
known = true
|
||||
JSONObject().put("gameInstanceGuid", "g")
|
||||
}
|
||||
"getGameInstances" -> if (known) JSONArray().put(JSONObject().put("guid", "g").put("installPath", flavor)) else JSONArray()
|
||||
"deleteMods" -> {
|
||||
projects.removeAll { p ->
|
||||
(p.getString("installedModId") in expression).also { gone ->
|
||||
@@ -467,7 +504,7 @@ class CurseForgeAppTest {
|
||||
curse.add("18808", "TomTom", 1)
|
||||
val before = CurseForgeApp.projects(context, url, "g", rescan = true).associate { it.id to it.update }
|
||||
assertEquals(mapOf("298842" to true, "18808" to false), before)
|
||||
assertTrue(CurseForgeApp.update(context, url, "g", "298842"))
|
||||
assertNotNull(CurseForgeApp.update(context, url, "g", "298842"))
|
||||
assertTrue("updateMod" in curse.methods)
|
||||
assertTrue(CurseForgeApp.projects(context, url, "g").none { it.update })
|
||||
}
|
||||
@@ -479,7 +516,7 @@ class CurseForgeAppTest {
|
||||
curse.add("298842", "Leatrix_Maps", 1)
|
||||
curse.add("18808", "TomTom", 1)
|
||||
val project = CurseForgeApp.owner(CurseForgeApp.projects(context, url, "g"), "Leatrix_Maps")!!
|
||||
assertTrue(CurseForgeApp.uninstall(context, url, "g", project))
|
||||
assertNotNull(CurseForgeApp.uninstall(context, url, "g", project))
|
||||
assertEquals(listOf("18808"), CurseForgeApp.projects(context, url, "g").map { it.id })
|
||||
assertFalse(File(curse.addOns, "Leatrix_Maps").exists())
|
||||
assertTrue(File(curse.addOns, "TomTom").isDirectory)
|
||||
|
||||
@@ -155,4 +155,37 @@ class LinuxNetworkLinkComponentTest {
|
||||
})
|
||||
assertEquals(before, link)
|
||||
}
|
||||
|
||||
@Test fun parallelPublishersFromSeparateComponentsAllLandAndLeaveNoStagedCopy() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
val link = properties("10.0.0.1/24").route("1.0.0.0", 8).route("128.0.0.0", 1)
|
||||
val failures = java.util.concurrent.atomic.AtomicInteger()
|
||||
val threads = (0 until 8).map {
|
||||
Thread {
|
||||
val component = LinuxNetworkLinkComponent(context, temporary.root)
|
||||
repeat(25) {
|
||||
runCatching {
|
||||
ReflectionHelpers.callInstanceMethod<Unit>(component, "replace",
|
||||
from(java.io.File::class.java, temporary.root.resolve("etc/droiddeck-net").apply { parentFile!!.mkdirs() }),
|
||||
from(String::class.java, "if tun0 $it\n"))
|
||||
}.onFailure { failures.incrementAndGet() }
|
||||
}
|
||||
}.apply { start() }
|
||||
}
|
||||
threads.forEach { it.join() }
|
||||
assertEquals(0, failures.get())
|
||||
assertFalse(temporary.root.resolve("etc/droiddeck-net.staged").exists())
|
||||
assertEquals("if tun0 24\n", temporary.root.resolve("etc/droiddeck-net").readText())
|
||||
}
|
||||
|
||||
@Test fun anUnchangedFileIsNotRewritten() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
val component = LinuxNetworkLinkComponent(context, temporary.root)
|
||||
val file = temporary.root.resolve("etc/resolv.conf").apply { parentFile!!.mkdirs(); writeText("nameserver 1.1.1.1\n") }
|
||||
assertTrue(file.setLastModified(1_000_000L))
|
||||
ReflectionHelpers.callInstanceMethod<Unit>(component, "replace", from(java.io.File::class.java, file), from(String::class.java, "nameserver 1.1.1.1\n"))
|
||||
assertEquals(1_000_000L, file.lastModified())
|
||||
ReflectionHelpers.callInstanceMethod<Unit>(component, "replace", from(java.io.File::class.java, file), from(String::class.java, "nameserver 8.8.8.8\n"))
|
||||
assertEquals("nameserver 8.8.8.8\n", file.readText())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.session.Onboarding.Facts
|
||||
import com.droiddeck.launcher.session.Onboarding.Progress
|
||||
import com.droiddeck.launcher.session.Onboarding.State
|
||||
import com.droiddeck.launcher.session.Onboarding.Step
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class OnboardingTest {
|
||||
private val none = Facts(runtime = false, proton = false, steam = false)
|
||||
|
||||
@Test fun everythingReadyShowsNothing() {
|
||||
val rows = Onboarding.rows(emptyMap(), emptyMap(), Facts())
|
||||
assertFalse(Onboarding.pending(rows))
|
||||
assertEquals(100, Onboarding.overall(rows))
|
||||
}
|
||||
|
||||
@Test fun stepsAreActiveFailedOrWaiting() {
|
||||
val rows = Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 50)), mapOf(Step.PROTON to "no"), none)
|
||||
assertEquals(listOf(State.ACTIVE, State.FAILED, State.WAITING), rows.map { it.state })
|
||||
assertTrue(Onboarding.pending(rows))
|
||||
}
|
||||
|
||||
@Test fun anActiveStepStaysActiveWhenItsFactIsAlreadyTrue() {
|
||||
val rows = Onboarding.rows(mapOf(Step.STEAM to Progress("x", -1)), emptyMap(), Facts())
|
||||
assertEquals(State.ACTIVE, rows.first { it.step == Step.STEAM }.state)
|
||||
}
|
||||
|
||||
@Test fun overallWeighsDownloadsBySize() {
|
||||
val rows = Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 50)), emptyMap(), Facts(runtime = false))
|
||||
assertEquals(30 + 15 + 25, Onboarding.overall(rows))
|
||||
}
|
||||
|
||||
@Test fun reportingClearsAPriorFailure() {
|
||||
Onboarding.fail(Step.STEAM, "boom")
|
||||
Onboarding.report(Step.STEAM, "again", 3)
|
||||
assertTrue(Onboarding.failed.value[Step.STEAM] == null)
|
||||
Onboarding.finish(Step.STEAM)
|
||||
assertTrue(Onboarding.active.value[Step.STEAM] == null)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class SteamClientPrefetchTest {
|
||||
@Test fun readsPercentAndTotalFromTheInstallersStepLine() {
|
||||
val line = "== STEP 14:21:07 downloading Steam: bins_linuxarm64.zip (2/5), 120 of 480 MB"
|
||||
assertEquals(25 to 480, SteamClientPrefetch.parse(line))
|
||||
}
|
||||
|
||||
@Test fun aRetryNoteDoesNotChangeTheReading() {
|
||||
val line = "== STEP 14:21:07 downloading Steam: x.zip (1/3), 10 of 40 MB - retrying in 5s"
|
||||
assertEquals(25 to 40, SteamClientPrefetch.parse(line))
|
||||
}
|
||||
|
||||
@Test fun otherLinesAreIgnored() {
|
||||
assertNull(SteamClientPrefetch.parse("== STEP 14:21:07 the Steam client now follows steamdeck_stable"))
|
||||
assertNull(SteamClientPrefetch.parse("downloading Steam: x (1/1), 5 of 0 MB"))
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,27 @@ class SteamUserDefaultsTest {
|
||||
assertFalse(File(home, "userdata/123/config/droiddeck-user-defaults-initialized").exists())
|
||||
}
|
||||
|
||||
@Test fun libraryHomeUsesBigArtUnlessChosenOtherwise() {
|
||||
val fresh = home("")
|
||||
SessionFiles.seedUserDefaults(fresh)
|
||||
assertTrue(text(fresh).contains("\"LibraryHomeBigArt\"\t\t\"1\""))
|
||||
val chosen = home("\t\"LibraryHomeBigArt\"\t\t\"0\"\n")
|
||||
SessionFiles.seedUserDefaults(chosen)
|
||||
assertTrue(text(chosen).contains("\"LibraryHomeBigArt\"\t\t\"0\""))
|
||||
assertEquals(1, Regex("LibraryHomeBigArt").findAll(text(chosen)).count())
|
||||
}
|
||||
|
||||
@Test fun bigArtLandsInTheRootWhenNestedStoresCloseOnItsLastLine() {
|
||||
val home = home("")
|
||||
File(home, "userdata/123/config/localconfig.vdf").writeText(
|
||||
"\"UserLocalConfigStore\"\n{\n\t\"WebStorage\"\n\t{\n\t\t\"Other\"\t\t\"x\"\n\t}}\n")
|
||||
SessionFiles.seedUserDefaults(home)
|
||||
val t = text(home)
|
||||
val beforeBigArt = t.substring(0, t.indexOf("\"LibraryHomeBigArt\""))
|
||||
assertEquals(beforeBigArt.count { it == '{' }, beforeBigArt.count { it == '}' } + 1)
|
||||
assertTrue(t.indexOf("\"CachedBatteryPreferences\"") < t.indexOf("\"LibraryHomeBigArt\""))
|
||||
}
|
||||
|
||||
@Test fun librarySortsByRecentlyPlayed() {
|
||||
val fresh = home("")
|
||||
SessionFiles.seedUserDefaults(fresh)
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.robolectric.pluginapi.TestEnvironmentLifecyclePlugin
|
||||
|
||||
/**
|
||||
* A plain JVM has no default uncaught-exception handler, so CrashHandler's fallback halts the test JVM (exit 2)
|
||||
* on any background-thread error. Each test starts from a handler that only prints, like the JVM's own.
|
||||
*/
|
||||
class TestJvmUncaughtHandler : TestEnvironmentLifecyclePlugin {
|
||||
override fun onSetupApplicationState() {
|
||||
Thread.setDefaultUncaughtExceptionHandler { thread, error ->
|
||||
System.err.print("Exception in thread \"${thread.name}\" ")
|
||||
error.printStackTrace(System.err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.App
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class UncaughtBackgroundErrorTest {
|
||||
@Test fun anUncaughtErrorOnABackgroundThreadDoesNotEndTheTestRun() {
|
||||
assertTrue(RuntimeEnvironment.getApplication() is App)
|
||||
Thread({ throw IllegalStateException("expected by the test") }, "uncaught-background-error").apply {
|
||||
start()
|
||||
join()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,34 @@ class XboxManifestTest {
|
||||
assertEquals(listOf("Retail.exe"), info.executables)
|
||||
assertEquals("Retail.exe", XboxManifest.executable(root))
|
||||
}
|
||||
@Test fun aGameCorePackageIsReadFromItsConfigBesideTheGeneratedAppxManifest() {
|
||||
val root = temporary.newFolder()
|
||||
java.io.File(root, "Game.exe").writeText("encrypted")
|
||||
java.io.File(root, "Other.exe").writeText("encrypted")
|
||||
java.io.File(root, "MicrosoftGame.config").writeText("""<Game configVersion="1"><Identity Name="Test.Game" Publisher="CN=Test" Version="1.2.3.0"/>
|
||||
<ExecutableList><Executable Name="Game.exe" TargetDeviceFamily="PC"/></ExecutableList><StoreId>9AAAAAAAAAAA</StoreId></Game>""")
|
||||
java.io.File(root, "appxmanifest.xml").writeText("""<?xml version="1.0" encoding="utf-8"?>
|
||||
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10">
|
||||
<Identity Name="Generated.Game" Publisher="CN=Generated" Version="9.9.9.0"/>
|
||||
<Applications><Application Id="Game" Executable="Other.exe" EntryPoint="Game.App"/></Applications></Package>""")
|
||||
val info = XboxManifest.read(root)
|
||||
assertEquals("Test.Game", info.name)
|
||||
assertEquals("1.2.3.0", info.version)
|
||||
assertEquals("9AAAAAAAAAAA", info.storeId)
|
||||
assertEquals("Game.exe", XboxInstaller.executable(root))
|
||||
assertFalse(XboxManifest.needsAppModel(root))
|
||||
}
|
||||
@Test fun aFolderWithoutOneManifestIsStillRefused() {
|
||||
val empty = temporary.newFolder()
|
||||
java.io.File(empty, "Game.exe").writeText("encrypted")
|
||||
assertThrows(IllegalArgumentException::class.java) { XboxManifest.read(empty) }
|
||||
val twice = temporary.newFolder()
|
||||
java.io.File(twice, "Game.exe").writeText("encrypted")
|
||||
java.io.File(twice, "MicrosoftGame.config").writeText("<Game><Executable Name=\"Game.exe\"/></Game>")
|
||||
java.io.File(twice, "microsoftgame.CONFIG").writeText("<Game><Executable Name=\"Game.exe\"/></Game>")
|
||||
org.junit.Assume.assumeTrue(twice.list().orEmpty().size == 3)
|
||||
assertThrows(IllegalArgumentException::class.java) { XboxManifest.read(twice) }
|
||||
}
|
||||
@Test fun legacyPackageManifestNamesItsExecutableTheSameWay() {
|
||||
// A legacy EAppx package carries AppxManifest.xml and has no config; the
|
||||
// launcher must still find the identity and the launch path, or an install
|
||||
|
||||
@@ -133,6 +133,88 @@ class CurseLinkTabTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anInstallHandsCurseForgesSettledListToTheNextReadWithoutARescan() {
|
||||
val target = wow()
|
||||
val link = CurseLink(app)
|
||||
try {
|
||||
link.installed(context, target, 0)
|
||||
assertTrue(link.change(context, target) { CurseForgeApp.install(context, it.inspector, it.guid, "298842") })
|
||||
assertEquals(listOf("298842"), link.installed(context, target, 1).map { it.id })
|
||||
assertEquals(1, methods.count { it == "scanGameInstance" })
|
||||
link.installed(context, target, 2)
|
||||
assertEquals(2, methods.count { it == "scanGameInstance" })
|
||||
} finally {
|
||||
runBlocking { link.close(context).join() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFailedInstallLeavesTheNextReadToRescan() {
|
||||
val target = wow()
|
||||
val link = CurseLink(app)
|
||||
try {
|
||||
link.installed(context, target, 0)
|
||||
assertFalse(link.change(context, target) { null })
|
||||
link.installed(context, target, 1)
|
||||
assertEquals(2, methods.count { it == "scanGameInstance" })
|
||||
} finally {
|
||||
runBlocking { link.close(context).join() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRefreshAfterAnInstallStillRescans() {
|
||||
val target = wow()
|
||||
val link = CurseLink(app)
|
||||
try {
|
||||
link.installed(context, target, 0)
|
||||
assertTrue(link.change(context, target) { CurseForgeApp.install(context, it.inspector, it.guid, "298842") })
|
||||
link.refresh()
|
||||
link.installed(context, target, 1)
|
||||
assertEquals(2, methods.count { it == "scanGameInstance" })
|
||||
} finally {
|
||||
runBlocking { link.close(context).join() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFailedChangeDropsAnEarlierSettledList() {
|
||||
val target = wow()
|
||||
val link = CurseLink(app)
|
||||
try {
|
||||
link.installed(context, target, 0)
|
||||
assertTrue(link.change(context, target) { CurseForgeApp.install(context, it.inspector, it.guid, "298842") })
|
||||
assertFalse(link.change(context, target) { null })
|
||||
link.installed(context, target, 1)
|
||||
assertEquals(2, methods.count { it == "scanGameInstance" })
|
||||
} finally {
|
||||
runBlocking { link.close(context).join() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anOlderChangeFinishingLastDoesNotReplaceTheNewerList() {
|
||||
val target = wow()
|
||||
tocFolder(target.addOns, "Older", "1")
|
||||
tocFolder(target.addOns, "Newer", "2")
|
||||
val older = CurseForgeApp.Project("1", "11", listOf("Older"), false)
|
||||
val newer = CurseForgeApp.Project("2", "22", listOf("Newer"), false)
|
||||
val link = CurseLink(app)
|
||||
try {
|
||||
link.installed(context, target, 0)
|
||||
assertTrue(link.change(context, target) {
|
||||
assertTrue(link.change(context, target) { listOf(older, newer) })
|
||||
listOf(older)
|
||||
})
|
||||
assertEquals(setOf("1", "2"), CurseLink.lastReported(target).keys)
|
||||
assertEquals(listOf("1", "2"), link.installed(context, target, 1).map { it.id })
|
||||
assertEquals(1, methods.count { it == "scanGameInstance" })
|
||||
} finally {
|
||||
runBlocking { link.close(context).join() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFailedScanKeepsTheLastReportInsteadOfClearingIt() {
|
||||
val target = wow()
|
||||
|
||||
@@ -40,8 +40,8 @@ class NavTabsTest {
|
||||
}
|
||||
|
||||
@Test fun aFreshInstallShowsTheDefaultBarMoreAndHiddenTabs() {
|
||||
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", NavTabs.MORE), navigationKeys(state()))
|
||||
assertEquals(listOf("stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state()))
|
||||
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", "stores", NavTabs.MORE), navigationKeys(state()))
|
||||
assertEquals(listOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state()))
|
||||
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "android-apps"))
|
||||
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "agent"))
|
||||
assertFalse(com.droiddeck.launcher.agent.AgentTab.shown)
|
||||
@@ -51,13 +51,13 @@ class NavTabsTest {
|
||||
@Test fun showingMusicOnceKeepsItShownAfterReload() {
|
||||
place("soundtracks", TabPlace.BAR)
|
||||
NavTabs.load(ctx)
|
||||
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", "soundtracks", NavTabs.MORE), navigationKeys(state()))
|
||||
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", "stores", "soundtracks", NavTabs.MORE), navigationKeys(state()))
|
||||
}
|
||||
|
||||
@Test fun shelvedTabsLeaveTheBarAndAddMoreAtTheEnd() {
|
||||
place("desktop", TabPlace.MORE)
|
||||
val s = state()
|
||||
assertEquals(listOf("desktop", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(s))
|
||||
assertEquals(listOf("desktop", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(s))
|
||||
assertEquals(NavTabs.MORE, navigationKeys(s).last())
|
||||
assertFalse("desktop" in navigationKeys(s))
|
||||
}
|
||||
@@ -70,14 +70,14 @@ class NavTabsTest {
|
||||
}
|
||||
|
||||
@Test fun resettingPutsBackTheDefaultLayout() {
|
||||
place("stores", TabPlace.BAR)
|
||||
place("stores", TabPlace.MORE)
|
||||
place("updates", TabPlace.HIDDEN)
|
||||
moveTab("downloads", -1)
|
||||
assertFalse(NavTabs.isDefault())
|
||||
NavTabs.reset(ctx)
|
||||
NavTabs.load(ctx)
|
||||
assertTrue(NavTabs.isDefault())
|
||||
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", NavTabs.MORE), navigationKeys(state()))
|
||||
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", "stores", NavTabs.MORE), navigationKeys(state()))
|
||||
}
|
||||
|
||||
@Test fun anOldLayoutKeepsWhatItsSwitchesShowed() {
|
||||
|
||||
@@ -8,15 +8,45 @@ class SessionDrawerPageTest {
|
||||
val pages = sessionDrawerPages(hasAgent = false)
|
||||
assertEquals(SessionDrawerPage.CONTROLLER, pages.first())
|
||||
assertEquals(SessionDrawerPage.DISPLAY, pages.step(SessionDrawerPage.CONTROLLER, 1))
|
||||
assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.CONTROLLER, -1))
|
||||
assertEquals(SessionDrawerPage.CONTROLLER, pages.step(SessionDrawerPage.SESSION, 1))
|
||||
assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.CONTROLLER, -1))
|
||||
assertEquals(SessionDrawerPage.HUD, pages.step(SessionDrawerPage.DISPLAY, 1))
|
||||
assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.HUD, 1))
|
||||
assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.EFFECTS, 1))
|
||||
assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.VR, 1))
|
||||
assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.EFFECTS, 1))
|
||||
assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.GAMES, 1))
|
||||
}
|
||||
|
||||
@Test fun moreKeepsSteamVrByDefaultAndStandsInForThePagesInsideIt() {
|
||||
val pages = sessionDrawerPages(hasAgent = false)
|
||||
assertEquals(listOf(SessionDrawerPage.VR), pages.inMore())
|
||||
assertEquals(SessionDrawerPage.MORE, pages.strip().last())
|
||||
assertFalse(SessionDrawerPage.VR in pages.strip())
|
||||
assertEquals(SessionDrawerPage.MORE, pages.tabFor(SessionDrawerPage.VR))
|
||||
assertEquals(SessionDrawerPage.GAMES, pages.tabFor(SessionDrawerPage.GAMES))
|
||||
val strip = pages.strip()
|
||||
assertEquals(SessionDrawerPage.MORE, strip.step(SessionDrawerPage.SESSION, 1))
|
||||
assertEquals(SessionDrawerPage.CONTROLLER, strip.step(SessionDrawerPage.MORE, 1))
|
||||
assertEquals(SessionDrawerPage.SESSION, strip.step(pages.tabFor(SessionDrawerPage.VR), -1))
|
||||
}
|
||||
|
||||
@Test fun anOlderSavedOrderKeepsItsPagesAndGetsAMoreTabAfterSession() {
|
||||
val saved = listOf("CONTROLLER", "DISPLAY", "HUD", "EFFECTS", "VR", "GAMES", "AGENT", "SESSION")
|
||||
val out = DrawerPages.arrange(saved)
|
||||
assertEquals(SessionDrawerPage.MORE, out[out.indexOf(SessionDrawerPage.SESSION) + 1])
|
||||
assertTrue(out.indexOf(SessionDrawerPage.VR) < out.indexOf(SessionDrawerPage.EFFECTS) + 2)
|
||||
assertTrue(out.inMore().isEmpty())
|
||||
}
|
||||
|
||||
@Test fun sessionCanBeKeptInsideMore() {
|
||||
val saved = listOf("CONTROLLER", "DISPLAY", "HUD", "EFFECTS", "GAMES", "AGENT", "MORE", "SESSION", "VR")
|
||||
val out = DrawerPages.arrange(saved)
|
||||
assertEquals(listOf(SessionDrawerPage.SESSION, SessionDrawerPage.VR), out.inMore())
|
||||
assertFalse(SessionDrawerPage.SESSION in out.strip())
|
||||
}
|
||||
|
||||
@Test fun moreAndSessionCannotBeHidden() {
|
||||
assertFalse(DrawerPages.hideable(SessionDrawerPage.MORE))
|
||||
}
|
||||
|
||||
@Test fun glassesAddTheirPageAfterController() {
|
||||
val pages = sessionDrawerPages(hasGlasses = true, hasAgent = false)
|
||||
assertEquals(SessionDrawerPage.GLASSES, pages.step(SessionDrawerPage.CONTROLLER, 1))
|
||||
|
||||
@@ -41,7 +41,8 @@ class SteamIntegrationGroupTest {
|
||||
compose.onNodeWithTag("integration-action-brightness").performClick()
|
||||
compose.onNodeWithTag("integration-action-home").performClick()
|
||||
compose.onNodeWithTag("integration-action-shortcuts").performClick()
|
||||
assertEquals(listOf(Feature.BRIGHTNESS, Feature.HOME, Feature.SHORTCUTS), requests)
|
||||
compose.onNodeWithTag("integration-action-bluetooth").performClick()
|
||||
assertEquals(listOf(Feature.BRIGHTNESS, Feature.HOME, Feature.SHORTCUTS, Feature.BLUETOOTH), requests)
|
||||
}
|
||||
|
||||
@Test fun switchesReflectAndroidGrants() {
|
||||
@@ -50,7 +51,8 @@ class SteamIntegrationGroupTest {
|
||||
compose.onNodeWithTag("integration-action-brightness").assert(stateIs("On"))
|
||||
compose.onNodeWithTag("integration-action-shortcuts").assert(stateIs("On"))
|
||||
compose.onNodeWithTag("integration-action-wifi").assert(stateIs("Off"))
|
||||
compose.onNodeWithText("3 of 4 on").assertExists()
|
||||
compose.onNodeWithTag("integration-action-bluetooth").assert(stateIs("Off"))
|
||||
compose.onNodeWithText("3 of 5 on").assertExists()
|
||||
}
|
||||
|
||||
@Test fun shortcutsDoNotNeedHome() {
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
com.droiddeck.launcher.session.TestJvmUncaughtHandler
|
||||
Reference in new issue
Block a user