Compare commits

...
11 changed files with 422 additions and 30 deletions

No files matched your search

+38 -8
View File
@@ -25,6 +25,7 @@
#include <gnu/lib-names.h>
#endif
#include <fcntl.h>
#include <linux/futex.h>
#include <linux/input.h>
#include <linux/joystick.h>
#include <linux/uinput.h>
@@ -711,6 +712,19 @@ ring_header_is_valid(const FakeInputRingHeader *ring) {
ring->capacity == FAKE_INPUT_RING_CAPACITY;
}
__attribute__((visibility("hidden"))) static int ring_wait(const FakeInputRingHeader *ring, uint64_t seen, long ns) {
struct timespec wait = {0, ns};
if (syscall(SYS_futex, &ring->write_seq, FUTEX_WAIT, static_cast<uint32_t>(seen), &wait, nullptr, 0) == 0 ||
errno == EAGAIN || errno == ETIMEDOUT)
return 0;
if (errno == EINTR) return -1;
return nanosleep(&wait, nullptr);
}
__attribute__((visibility("hidden"))) static void ring_wake(const FakeInputRingHeader *ring) {
syscall(SYS_futex, &ring->write_seq, FUTEX_WAKE, INT_MAX, nullptr, nullptr, 0);
}
struct SnapshotState {
uint64_t sequence = 0;
uint64_t write_seq = 0;
@@ -1167,6 +1181,7 @@ __attribute__((visibility("hidden"))) static void flush_uinput(UinputWriter &w)
__atomic_thread_fence(__ATOMIC_RELEASE);
__atomic_store_n(&ring->snapshot_seq, sequence + 2, __ATOMIC_RELEASE);
__atomic_store_n(&ring->write_seq, write_seq, __ATOMIC_RELEASE);
ring_wake(ring);
}
__attribute__((visibility("hidden"))) static ssize_t
@@ -1540,6 +1555,12 @@ __attribute__((visibility("hidden"))) static void sleep_us(int us) {
nanosleep(&interval, nullptr);
}
__attribute__((visibility("hidden"))) static void
report_wait(const FakeInputRingHeader *ring, bool fresh, uint64_t seen, int us) {
if (fresh) ring_wait(ring, seen, us * 1000L);
else sleep_us(us);
}
__attribute__((visibility("hidden"))) static uint64_t monotonic_us() {
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
@@ -1712,7 +1733,8 @@ __attribute__((visibility("hidden"))) static void *deck_report_thread(void *arg)
int32_t axes[8] = {};
DeckExtras extras;
while (live_pad_type() == PAD_TYPE_DECK) {
if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) {
bool fresh = read_snapshot(self->ring, snap);
if (fresh && snap.generation == ring_generation(self->ring)) {
buttons = snap.buttons;
memcpy(axes, snap.axes, sizeof(axes));
}
@@ -1722,7 +1744,7 @@ __attribute__((visibility("hidden"))) static void *deck_report_thread(void *arg)
if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 &&
errno != EAGAIN && errno != EWOULDBLOCK)
break;
sleep_us(controller_report_interval_us(DECK_REPORT_INTERVAL_US));
report_wait(self->ring, fresh, snap.write_seq, controller_report_interval_us(DECK_REPORT_INTERVAL_US));
}
syscall(SYS_close, self->peer);
munmap(self->ring, self->mapping_size);
@@ -1828,7 +1850,8 @@ __attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg)
SonyTouch touch;
const uint64_t start_us = monotonic_us();
while (live_pad_type() == type) {
if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) {
bool fresh = read_snapshot(self->ring, snap);
if (fresh && snap.generation == ring_generation(self->ring)) {
buttons = snap.buttons;
memcpy(axes, snap.axes, sizeof(axes));
}
@@ -1838,7 +1861,7 @@ __attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg)
if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 &&
errno != EAGAIN && errno != EWOULDBLOCK)
break;
sleep_us(controller_report_interval_us(DECK_REPORT_INTERVAL_US));
report_wait(self->ring, fresh, snap.write_seq, controller_report_interval_us(DECK_REPORT_INTERVAL_US));
}
syscall(SYS_close, self->peer);
munmap(self->ring, self->mapping_size);
@@ -2037,7 +2060,8 @@ __attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg)
DeckExtras extras;
const uint64_t start_us = monotonic_us();
while (live_pad_type() == PAD_TYPE_STEAM) {
if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) {
bool fresh = read_snapshot(self->ring, snap);
if (fresh && snap.generation == ring_generation(self->ring)) {
buttons = snap.buttons;
memcpy(axes, snap.axes, sizeof(axes));
}
@@ -2048,7 +2072,7 @@ __attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg)
if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 &&
errno != EAGAIN && errno != EWOULDBLOCK)
break;
sleep_us(controller_report_interval_us(TRITON_REPORT_INTERVAL_US));
report_wait(self->ring, fresh, snap.write_seq, controller_report_interval_us(TRITON_REPORT_INTERVAL_US));
}
syscall(SYS_close, self->peer);
munmap(self->ring, self->mapping_size);
@@ -4016,6 +4040,7 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
errno = ENODEV;
return -1;
}
bool idle = false;
for (int attempt = 0; attempt < 8; ++attempt) {
size_t requested = count / sizeof(struct input_event);
if (fake.keyframe_remaining == 0) {
@@ -4037,7 +4062,10 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
capture_keyframe(fake, snap);
} else {
size_t events = std::min<uint64_t>(requested, snap.write_seq - fake.read_seq);
if (events == 0) break;
if (events == 0) {
idle = true;
break;
}
const uint8_t *ring_events = reinterpret_cast<const uint8_t *>(fake.ring) +
FAKE_INPUT_RING_HEADER_SIZE;
std::vector<struct input_event> input_events(events);
@@ -4083,9 +4111,11 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
errno = EAGAIN;
return -1;
}
const FakeInputRingHeader *ring = fake.ring;
uint64_t seen = fake.read_seq;
guard.unlock();
struct timespec sleep_time = {0, backoff_ns};
int result = nanosleep(&sleep_time, nullptr);
int result = idle ? ring_wait(ring, seen, backoff_ns) : nanosleep(&sleep_time, nullptr);
guard.lock();
if (result < 0) return -1;
if (low_latency(LATENCY_CONTROLLER)) backoff_ns = kLowLatencyRingWaitUs * 1000;
+10
View File
@@ -1,6 +1,9 @@
#include <errno.h>
#include <jni.h>
#include <limits.h>
#include <linux/futex.h>
#include <stdatomic.h>
#include <stdint.h>
#include <sys/syscall.h>
#include <unistd.h>
@@ -11,6 +14,13 @@ Java_com_droiddeck_launcher_input_FakeInputWriter_nativeStoreFence(JNIEnv *env,
atomic_thread_fence(memory_order_release);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_input_FakeInputWriter_nativeWake(JNIEnv *env, jclass clazz, jobject buffer, jint offset) {
(void)clazz;
uint8_t *base = (*env)->GetDirectBufferAddress(env, buffer);
if (base) syscall(SYS_futex, base + offset, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
}
JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_session_ThreadSignals_tgkill(JNIEnv *env, jclass clazz, jint tgid, jint tid, jint signal) {
(void)env;
@@ -233,14 +233,14 @@ object AddedGames {
if (folder.name.lowercase() in steamInstalls || isSteamLibraryFolder(folder.name)) continue
if (folder.path in removed) continue
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
for (game in expand(folder, entries, reuse = true)) if (game.path !in removed) scanGame(context, game, out, reuse = true)
timed(folder) { for (game in expand(folder, entries, reuse = true)) if (game.path !in removed) scanGame(context, game, out, reuse = true) }
}
}
for (entry in AddedExes.list(context)) {
val folder = File(entry.folder)
if (folder.path in removed || !folder.isDirectory) continue
if (StoreGameSidecar.read(folder)?.isInstalled == false) continue
scanGame(context, folder, out, single = entry, reuse = true)
timed(folder) { scanGame(context, folder, out, single = entry, reuse = true) }
}
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out, reuse = true)
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out, reuse = true)
@@ -250,6 +250,15 @@ object AddedGames {
return out.distinctBy { it.folder.canonicalPath }
}
private const val SLOW_FOLDER_MS = 1_000L
private inline fun timed(folder: File, block: () -> Unit) {
val began = android.os.SystemClock.elapsedRealtime()
block()
val took = android.os.SystemClock.elapsedRealtime() - began
if (took >= SLOW_FOLDER_MS) Log.i(TAG, "games: scanning ${folder.path} took ${took}ms")
}
fun single(context: Context, folderPath: String, reuse: Boolean = false): Game? {
val folder = File(folderPath)
if (!folder.isDirectory || folderPath in SessionPrefs.removedAddedGames(context)) return null
@@ -564,8 +573,10 @@ object AddedGames {
class Listed(val appId: Long, val name: String, val launchOptions: String)
fun listingFile(context: Context): File = File(context.filesDir, "session/added-games.json")
fun listed(context: Context): List<Listed>? = runCatching {
val file = File(context.filesDir, "session/added-games.json")
val file = listingFile(context)
if (!file.isFile) return null
val entries = org.json.JSONArray(file.readText())
(0 until entries.length()).mapNotNull { i ->
@@ -575,7 +586,7 @@ object AddedGames {
fun writeListing(context: Context, games: List<Game>,
extra: List<JSONObject> = listOfNotNull(com.droiddeck.launcher.stores.epic.EpicClient.steamListing(context))): File {
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
val file = listingFile(context).apply { parentFile?.mkdirs() }
val json = StringBuilder("[")
games.forEachIndexed { i, g ->
if (i > 0) json.append(',')
@@ -596,10 +607,24 @@ object AddedGames {
if (games.isNotEmpty() || i > 0) json.append(',')
json.append(entry.toString())
}
file.writeText(json.append(']').toString())
val text = json.append(']').toString()
synchronized(listing) {
val partial = File(file.parentFile, file.name + ".part")
try {
partial.writeText(text)
java.nio.file.Files.move(partial.toPath(), file.toPath(),
java.nio.file.StandardCopyOption.ATOMIC_MOVE, java.nio.file.StandardCopyOption.REPLACE_EXISTING)
} catch (e: java.io.IOException) {
Log.w(TAG, "games: listing not replaced: ${e.message}")
partial.delete()
if (!file.isFile) file.writeText(text)
}
}
return file
}
private val listing = Any()
private fun artGuestPath(context: Context, file: File): String? {
val files = context.filesDir.absolutePath
if (file.absolutePath.startsWith("$files/")) return file.absolutePath
@@ -1,17 +1,31 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import android.os.SystemClock
import android.util.Log
import androidx.annotation.VisibleForTesting
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.SteamLiveShortcuts
import java.io.File
import java.util.concurrent.Callable
import java.util.concurrent.Executors
object AddedGamesPublisher {
private const val TAG = "AddedGamesPublisher"
private const val CLIENT_WAIT_MS = 600_000L
private const val POLL_MS = 1_000L
private const val RETRY_MS = 5_000L
@VisibleForTesting
@Volatile
internal var now = false
@VisibleForTesting
@Volatile
internal var live: (Context, List<AddedGames.Game>, (AddedGames.Game) -> Boolean) -> Boolean = SteamLiveShortcuts::sync
private val worker = Executors.newSingleThreadExecutor { r -> Thread(r, "added-games-publish") }
fun later(context: Context, live: () -> Unit = {}) {
@@ -23,10 +37,56 @@ object AddedGamesPublisher {
if (now) work.run() else worker.execute(work)
}
fun republish(context: Context) {
fun republish(context: Context): List<AddedGames.Game> {
val games = AddedGames.scan(context)
AddedGames.writeListing(context, games)
val arch = com.droiddeck.launcher.session.SessionPrefs.activeSteamClientArch(context)
val arch = SessionPrefs.activeSteamClientArch(context)
LibraryCache.save(context, Library.launchableGames(context, added = games, arch = arch), arch == "x86_64")
return games
}
fun sessionListing(context: Context): File {
val app = context.applicationContext
val started = AddedGames.listed(app)?.map { it.appId }?.toSet()
?: return AddedGames.writeListing(app, AddedGames.scan(app).also { log(it) })
val session = SessionState.sessionId
val work = Runnable {
try {
val began = SystemClock.elapsedRealtime()
val games = serial { republish(app) }
Log.i(TAG, "session refresh: ${games.size} game(s) in ${SystemClock.elapsedRealtime() - began} ms")
log(games)
val fresh = games.filter { (it.appId and 0xFFFFFFFFL) !in started }
if (fresh.isNotEmpty()) deliver(app, session, fresh)
} catch (e: Exception) {
Log.w(TAG, "session refresh: ${e.message}")
}
}
if (now) work.run() else Thread(work, "added-games-refresh").apply { priority = Thread.MIN_PRIORITY }.start()
return AddedGames.listingFile(app)
}
internal fun log(games: List<AddedGames.Game>) {
if (games.isNotEmpty()) Log.i(TAG, "added games: " + games.joinToString { "${it.name} (${it.exe.name})" })
}
private fun deliver(app: Context, session: String?, games: List<AddedGames.Game>) {
val until = SystemClock.uptimeMillis() + CLIENT_WAIT_MS
while (current(session)) {
val ready = SessionState.phase == SessionPhase.READY
if (ready && serial { !current(session) || (SessionState.phase == SessionPhase.READY && syncUnremoved(app, games)) }) return
if (now || SystemClock.uptimeMillis() >= until) return
Thread.sleep(if (ready) RETRY_MS else POLL_MS)
}
}
private fun current(session: String?): Boolean =
SessionState.running && !SessionState.stopRequested && SessionState.sessionId == session
private fun syncUnremoved(app: Context, games: List<AddedGames.Game>): Boolean {
val removed = SessionPrefs.removedAddedGames(app).toSet()
return live(app, games) { it.folder.path !in removed }
}
private fun <T> serial(block: () -> T): T = if (now) block() else worker.submit(Callable { block() }).get()
}
@@ -51,11 +51,12 @@ object GameExePicker {
val entries = dir.listFiles()?.sortedBy { it.name.lowercase() } ?: continue
for (f in entries) {
if (visited >= WALK_BUDGET) break@walk
if (isLink(f)) continue
if (f.isDirectory) {
val attrs = attributes(f) ?: continue
if (attrs.isSymbolicLink) continue
if (attrs.isDirectory) {
visited++
if (depth < MAX_DEPTH && !skipDir(f, f.relativeTo(folder).invariantSeparatorsPath)) next.add(f)
} else if (f.isFile && f.name.endsWith(".exe", ignoreCase = true)) {
} else if (attrs.isRegularFile && f.name.endsWith(".exe", ignoreCase = true)) {
visited++
if (!JUNK_EXE_RE.matches(f.nameWithoutExtension)) found.add(f to depth)
}
@@ -98,7 +99,9 @@ object GameExePicker {
return SKIP_PATHS.any { rel == it || rel.endsWith("/$it") }
}
private fun isLink(f: File): Boolean = runCatching { java.nio.file.Files.isSymbolicLink(f.toPath()) }.getOrDefault(false)
private fun attributes(f: File): java.nio.file.attribute.BasicFileAttributes? = runCatching {
java.nio.file.Files.readAttributes(f.toPath(), java.nio.file.attribute.BasicFileAttributes::class.java, java.nio.file.LinkOption.NOFOLLOW_LINKS)
}.getOrNull()
private fun key(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
}
@@ -149,6 +149,8 @@ public class FakeInputWriter {
private static native void nativeStoreFence();
private static native void nativeWake(ByteBuffer ring, int offset);
public static void storeFence() {
nativeStoreFence();
}
@@ -455,6 +457,7 @@ public class FakeInputWriter {
writeSnapshotLocked(ring);
nativeStoreFence();
ring.putLong(RING_WRITE_SEQ_OFFSET, writeSeq);
nativeWake(ring, RING_WRITE_SEQ_OFFSET);
}
return true;
}
@@ -693,12 +693,14 @@ class SessionService : Service() {
.onFailure { Log.w(TAG, "Epic install directory setup failed", it) }
}
if (steamHere || noSteamGame) {
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
val listing = SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
val listing = if (steamHere) SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGamesPublisher.sessionListing(this) } else {
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
com.droiddeck.launcher.frontend.AddedGamesPublisher.log(added)
SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
}
guest.add("DD_ADDED_GAMES=" + listing.path)
if (OfflineMode.active(this)) guest.add("DD_STEAM_OFFLINE=1")
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("DD_LOSSLESS_OWNED=1")
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
}
guest.add("DD_LAUNCH_DIR=" + sessionRoot.path)
// Proton builds up to 11.12 report X11 text fields under this name.
@@ -19,25 +19,33 @@ object SteamLiveShortcuts {
private const val EVAL_TIMEOUT_MS = 20_000L
private const val THAW_WAIT_MS = 15_000L
fun sync(context: Context, games: List<AddedGames.Game>, include: (AddedGames.Game) -> Boolean = { it.source != Library.ADDED }) {
fun sync(context: Context, games: List<AddedGames.Game>, include: (AddedGames.Game) -> Boolean = { it.source != Library.ADDED }): Boolean {
val wanted = games.filter(include)
if (wanted.isEmpty() || !clientRunning()) return
if (wanted.isEmpty()) return true
if (!clientRunning()) return false
val list = JSONArray()
for (g in wanted) list.put(JSONObject().put("name", g.name).put("exe", g.guestExe).put("dir", g.guestDir).put("appid", g.appId and 0xFFFFFFFFL).put("launch", g.launchOptions))
val js = """
(async () => {
const want = ${list};
let added = 0;
let added = 0, missed = 0;
for (const w of want) {
if (await ${KNOWN}(w.appid, w.name, w.exe)) continue;
if (await ${ADD}(w.name, w.exe, w.dir, true, ${JSONObject.quote(compatTool(context))}, w.launch)) added++;
if (await ${ADD}(w.name, w.exe, w.dir, true, ${JSONObject.quote(compatTool(context))}, w.launch)) added++; else missed++;
}
return added;
return JSON.stringify({ added, missed });
})()
""".trimIndent()
val result = evaluate(context, js) ?: return
Log.i(TAG, "live shortcuts: $result added")
if (result != "0") StoresState.logLine("Steam: $result shortcut(s) added to the running client")
return synced(evaluate(context, js))
}
internal fun synced(result: String?): Boolean {
val counts = result?.let { runCatching { JSONObject(it) }.getOrNull() } ?: return false
val added = counts.optInt("added")
val missed = counts.optInt("missed")
Log.i(TAG, "live shortcuts: $added added" + if (missed > 0) ", $missed not added" else "")
if (added > 0) StoresState.logLine("Steam: $added shortcut(s) added to the running client")
return missed == 0
}
fun ensure(context: Context, name: String, exe: String, dir: String, compat: Boolean, appId: Long? = null): Long? {
@@ -145,4 +145,15 @@ class AddedGamesCandidatesTest {
SessionPrefs.setAddedGamesDirs(app, listOf(games.path))
assertEquals("My Game [Repack]", AddedGames.scan(app).single().name)
}
@Test fun linksAndFoldersNamedLikeAnExeAreNotCandidates() {
val elsewhere = tmp.newFolder("Elsewhere")
exe(elsewhere, "Other.exe")
val game = tmp.newFolder("Linked")
exe(game, "bin/Linked.exe")
File(game, "Folder.exe").mkdirs()
java.nio.file.Files.createSymbolicLink(File(game, "other").toPath(), elsewhere.toPath())
java.nio.file.Files.createSymbolicLink(File(game, "Alias.exe").toPath(), File(elsewhere, "Other.exe").toPath())
assertEquals(listOf("bin/Linked.exe"), names(game))
}
}
@@ -0,0 +1,213 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.SteamLiveShortcuts
import java.io.File
import java.util.Collections
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AddedGamesSessionListingTest {
private val app get() = RuntimeEnvironment.getApplication()
@get:Rule val tmp = TemporaryFolder()
@After fun restore() {
AddedGamesPublisher.now = false
AddedGamesPublisher.live = SteamLiveShortcuts::sync
SessionState.running = false
SessionState.stopRequested = false
SessionState.sessionId = null
SessionState.phase = SessionPhase.IDLE
}
private val stale = """[{"name":"Old","exe":"/root/Games/Old/Old.exe","folder":"/root/Games/Old","dir":"/root/Games/Old","appid":2147483649,"seen":0}]"""
private fun gamesFolder(vararg names: String): File {
val games = tmp.newFolder("PC")
for (n in names) File(games, "$n/$n.exe").apply { parentFile!!.mkdirs() }.writeText("game")
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
SessionPrefs.setAddedGamesDirs(app, listOf(games.path))
return games
}
private fun session(phase: SessionPhase) {
SessionState.sessionId = "session-test"
SessionState.stopRequested = false
SessionState.phase = phase
SessionState.running = true
}
private fun until(what: String, check: () -> Boolean) {
val end = System.currentTimeMillis() + 30_000
while (!check()) {
assertTrue(what, System.currentTimeMillis() < end)
Thread.sleep(20)
}
}
private fun scanLock(): Any =
AddedGames::class.java.getDeclaredField("scanning").apply { isAccessible = true }.get(null)!!
private fun refreshes() = Thread.getAllStackTraces().keys.filter { it.name == "added-games-refresh" }
@Test fun aSessionStartsFromTheLastListingWhileTheLibraryScanHoldsTheLock() {
gamesFolder("Alpha")
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val done = CountDownLatch(1)
var returned: File? = null
var seen = ""
synchronized(scanLock()) {
Thread {
returned = AddedGamesPublisher.sessionListing(app)
seen = listing.readText()
done.countDown()
}.start()
assertTrue("the session start waited for the library scan", done.await(5, TimeUnit.SECONDS))
}
assertEquals(listing.path, returned!!.path)
assertEquals(stale, seen)
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
val fresh = listing.readText()
assertTrue(fresh.contains("\"Alpha\""))
assertFalse(fresh.contains("\"Old\""))
assertFalse(File(listing.parentFile, listing.name + ".part").exists())
}
@Test fun aFirstSessionScansBeforeStarting() {
gamesFolder("Alpha")
AddedGamesPublisher.now = false
val listing = AddedGames.listingFile(app)
listing.delete()
assertEquals(listing.path, AddedGamesPublisher.sessionListing(app).path)
assertTrue(listing.readText().contains("\"Alpha\""))
assertTrue(refreshes().isEmpty())
assertFalse(File(listing.parentFile, listing.name + ".part").exists())
}
@Test fun aListingThatCannotBeReplacedKeepsTheOldOne() {
val listing = AddedGames.listingFile(app).apply { parentFile?.mkdirs() }
listing.writeText("[]")
val blocked = File(listing.parentFile, listing.name + ".part").apply { mkdirs() }
gamesFolder("Alpha")
AddedGames.writeListing(app, AddedGames.scan(app))
assertEquals("[]", listing.readText())
assertFalse(blocked.exists())
}
@Test fun anUnreadableListingIsRescannedBeforeStarting() {
gamesFolder("Alpha")
AddedGamesPublisher.now = false
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText("[{\"name\":") }
AddedGamesPublisher.sessionListing(app)
assertTrue(listing.readText().contains("\"Alpha\""))
assertTrue(refreshes().isEmpty())
}
@Test fun aGameRemovedWhileTheClientStartsIsNotAddedToIt() {
val games = gamesFolder("Alpha", "Beta")
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val delivered = Collections.synchronizedList(ArrayList<String>())
AddedGamesPublisher.live = { _, found, include -> delivered.addAll(found.filter(include).map { it.name }); true }
session(SessionPhase.STARTING_STEAM)
AddedGamesPublisher.sessionListing(app)
until("the refresh did not write the listing") { listing.readText().contains("\"Beta\"") }
SessionPrefs.setAddedGameRemoved(app, File(games, "Beta").path, true)
SessionState.phase = SessionPhase.READY
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertEquals(listOf("Alpha"), delivered.toList())
}
@Test fun aDeliveryTheClientRefusesIsRetriedUntilItIsTaken() {
gamesFolder("Alpha")
AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val attempts = Collections.synchronizedList(ArrayList<List<String>>())
AddedGamesPublisher.live = { _, found, include -> attempts.add(found.filter(include).map { it.name }); attempts.size > 1 }
session(SessionPhase.READY)
AddedGamesPublisher.sessionListing(app)
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertEquals(listOf(listOf("Alpha"), listOf("Alpha")), attempts.toList())
}
@Test fun anEndedSessionStopsTheRetries() {
gamesFolder("Alpha")
AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val attempts = Collections.synchronizedList(ArrayList<String>())
AddedGamesPublisher.live = { _, found, _ -> attempts.addAll(found.map { it.name }); SessionState.running = false; false }
session(SessionPhase.READY)
AddedGamesPublisher.sessionListing(app)
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertEquals(listOf("Alpha"), attempts.toList())
}
@Test fun aDeliveryQueuedForAnEndedSessionIsNotSentToTheNextOne() {
gamesFolder("Alpha")
AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val delivered = Collections.synchronizedList(ArrayList<String>())
AddedGamesPublisher.live = { _, found, include -> delivered.addAll(found.filter(include).map { it.name }); true }
session(SessionPhase.READY)
val first = CountDownLatch(1)
val firstHeld = CountDownLatch(1)
val second = CountDownLatch(1)
val secondHeld = CountDownLatch(1)
AddedGamesPublisher.later(app) { firstHeld.countDown(); first.await() }
try {
assertTrue(firstHeld.await(30, TimeUnit.SECONDS))
AddedGamesPublisher.sessionListing(app)
val refresh = refreshes().single()
until("the refresh did not wait for its scan") { refresh.state == Thread.State.WAITING }
AddedGamesPublisher.later(app) { secondHeld.countDown(); second.await() }
first.countDown()
assertTrue(secondHeld.await(30, TimeUnit.SECONDS))
until("the refresh did not queue its delivery") {
refresh.state == Thread.State.WAITING && refresh.stackTrace.any { it.methodName == "deliver" }
}
SessionState.sessionId = "session-next"
} finally {
first.countDown()
second.countDown()
}
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertTrue(delivered.isEmpty())
}
@Test fun theRefreshWaitsForEarlierPublicationsBeforeWriting() {
gamesFolder("Alpha")
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val hold = CountDownLatch(1)
val holding = CountDownLatch(1)
AddedGamesPublisher.later(app) { holding.countDown(); hold.await() }
try {
assertTrue(holding.await(30, TimeUnit.SECONDS))
AddedGamesPublisher.sessionListing(app)
val refresh = refreshes().single()
until("the refresh neither finished nor waited") { refresh.state == Thread.State.WAITING || !refresh.isAlive }
assertTrue("the refresh wrote while an earlier publication was running", refresh.isAlive)
assertEquals(stale, listing.readText())
} finally {
hold.countDown()
}
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertTrue(listing.readText().contains("\"Alpha\""))
}
}
@@ -0,0 +1,27 @@
package com.droiddeck.launcher.stores
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class SteamLiveShortcutsSyncTest {
@Test fun everyGameKnownOrAddedIsDelivered() {
assertTrue(SteamLiveShortcuts.synced("""{"added":2,"missed":0}"""))
assertTrue(SteamLiveShortcuts.synced("""{"added":0,"missed":0}"""))
}
@Test fun aGameTheClientRefusedIsNotDelivered() {
assertFalse(SteamLiveShortcuts.synced("""{"added":1,"missed":1}"""))
assertFalse(SteamLiveShortcuts.synced("""{"added":0,"missed":3}"""))
}
@Test fun noAnswerIsNotDelivered() {
assertFalse(SteamLiveShortcuts.synced(null))
assertFalse(SteamLiveShortcuts.synced("1"))
}
}