Compare commits

...
Author SHA1 Message Date
xXJsonDeruloXx 0ef37b16c8 Merge main into feat/stores-motion 2026-10-09 14:49:00 -04:00
The412Banner 6e5932cb68 Stores: seal the GOG, Epic and Amazon sign-in files with an Android Keystore key (#486)
The stores' sign-ins (files/stores/<store>/credentials.json: access and refresh
tokens, account id and name) were plain JSON. Other apps could not read them, but
every program in the Linux session runs as the app and could. They are now sealed
with AES-256-GCM under a non-exportable AndroidKeyStore key (StrongBox when the
device has one), so the session only ever sees ciphertext.

- Format: a versioned envelope {v, alg, iv, ct}, written atomically and readable
  only by the app. No new dependencies (javax.crypto and KeyStore).
- Migration: an existing plaintext file is sealed at the next start, checked by
  decrypting it, then the plaintext is removed; users stay signed in.
- No Keystore on the device: the file stays plain and the log says so once per
  start.
- A sealed file that can never be opened (tampered, key gone or invalidated,
  broken envelope) is removed and that store asks for sign-in again. A transient
  Keystore error keeps the file and retries.
2026-10-09 14:42:23 -04:00
xXJsonDeruloXx bed4c1040b perf(stores): keep chip motion responsive while libraries change 2026-10-09 14:29:34 -04:00
xXJsonDeruloXx 3f45835ed6 feat(stores): the store a pad's focus is on shows without A, and a press never lands on where it sent focus 2026-10-09 13:37:03 -04:00
xXJsonDeruloXx 29abf954ce fix(ui): the focus ring follows a control until it stops and meets one still rising into place 2026-10-09 13:37:03 -04:00
The412Banner 38e3fa2a33 Logs: every log in app-private storage, shared as one scrubbed zip (#484)
Session folders, tool and installer logs and the stores' log now all live under the
app's private files/logs instead of Download/DroidDeck, and every existing "Share
logs" action bundles them into one zip that goes through a final scrub.

- Where: LinuxRuntime.logDir() = files/logs; sessions keep their dated folders and
  30-session pruning, tools/ and stores/ beside them. The "Logs" setting keeps its
  meaning. Game save backups stay in Download/DroidDeck/Saves.
- Migration: at first start the old session folders, tools/ and loose logs move from
  Download/DroidDeck into files/logs (Saves untouched), and every moved folder is
  scrubbed under the current rules.
- Scrubbing: one rule set (SecretScrub) for the stores' log and the zip. The scrub
  marker carries the rules version, so a rules change re-scrubs every folder at the
  next start (in the background, a few at a time). Steam login account names and
  emails, account-name fields, OAuth codes, tokens in URLs and private LAN
  addresses are removed; Windows exception codes and server addresses are kept.
- Share: one zip of the current session folder plus the last 7 days of stores/ and
  tools/, written to cache/share and handed to the share sheet.
2026-10-09 13:28:03 -04:00
xXJsonDeruloXx fa3037de68 style(stores): the sign-in page is the store's name and Sign in 2026-10-09 13:25:51 -04:00
xXJsonDeruloXx 9419f1efda style(stores): drop the sign-in page's store eyebrow, which the title already names 2026-10-09 13:23:51 -04:00
xXJsonDeruloXx d73c4e50c2 feat(stores): sign-in pages in the Steam tab's style and an are-you-sure for sign out 2026-10-09 13:22:25 -04:00
xXJsonDeruloXx bcaeb27780 feat(stores): modes step out of the store chip, each store in its own colour, search in the header 2026-10-09 13:16:11 -04:00
xXJsonDeruloXx fc515aa0e4 fix(ui): a step-out's backdrop never takes the pad's focus 2026-10-09 13:16:11 -04:00
xXJsonDeruloXx f164af81e7 perf(stores): GOG remembers its non-games and the library cache loads off the main thread 2026-10-09 13:16:11 -04:00
xXJsonDeruloXx 90af0b9c0c fix(stores): a game page no longer leaves the pad's focus on a dead card and crashes the next press 2026-10-09 13:16:10 -04:00
Kurt Himebauch 67cf1cdd9c fix(stores): lay out the pane's rows in a column 2026-10-09 12:32:10 -04:00
Kurt Himebauch 571751f15c feat(stores): bring the launcher's motion to the stores pages 2026-10-09 12:17:35 -04:00
Kurt Himebauch 768ed0c505 feat(ui): let PageFlood carry a tile's art 2026-10-09 12:17:35 -04:00
Kurt Himebauch 9f94140bbf refactor(ui): share End session's step-out as StepOut 2026-10-09 12:17:35 -04:00
50 changed files with 3065 additions and 434 deletions

No files matched your search

+2 -2
View File
@@ -21,7 +21,7 @@ Before Steam launches, you must turn off **Restrict child processes** in Develop
## Community
Join the [DroidDeck Discord](https://discord.gg/JRGAvawjsm) for help, Preview builds, and device reports. Bug reports go in its **#bug-reports** forum; attach the session folder from `Download/DroidDeck/` so the logs come with it.
Join the [DroidDeck Discord](https://discord.gg/JRGAvawjsm) for help, Preview builds, and device reports. Bug reports go in its **#bug-reports** forum; attach the zip from **Share logs** (Setup, or the session drawer) so the logs come with it.
## Build
@@ -29,7 +29,7 @@ Run `tools/build_local.sh` with Docker, Java 17, the Android SDK/NDK, and `zstd`
## Limits
Compatibility and performance vary by device; hardware validation is limited. Desktop compositing uses software rendering. Firefox sandboxing is reduced under proot. See the session logs in `Download/DroidDeck/` when diagnosing problems.
Compatibility and performance vary by device; hardware validation is limited. Desktop compositing uses software rendering. Firefox sandboxing is reduced under proot. Logs are kept app-private (`files/logs/`, the last 30 sessions); **Share logs** packs the newest session, with the stores and tool logs, into one scrubbed zip.
## Credits and licence
@@ -866,8 +866,12 @@ class MainActivity : ComponentActivity() {
SessionPrefs.setMicAsked(this)
}
if (wanted.isNotEmpty()) requestPermissions(wanted.toTypedArray(), 1)
// A store sign-in an earlier build left in plain text is sealed with the Keystore key.
Thread({ com.droiddeck.launcher.stores.StoreAccounts.encryptAll(this) }, "store-credentials").start()
// A session folder left without its ending - the process was killed - gets it now.
if (!SessionState.running) Thread({
com.droiddeck.launcher.session.LogMigration.run(this)
SessionLogShare.clear(this)
SessionArtifacts.finishAbandoned(this)
SessionArtifacts.scrubOlder(this)
SessionArtifacts.prune(this)
@@ -912,6 +916,7 @@ class MainActivity : ComponentActivity() {
/** On the Components page the pad's LB / RB step through GPU drivers, FEX, DXVK and VKD3D-Proton, wrapping around. */
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A) com.droiddeck.launcher.ui.HeldKeys.confirm = event.action == KeyEvent.ACTION_DOWN
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
val all = listOf(com.droiddeck.launcher.ui.GPU_TAB) + ComponentsManager.COMPONENTS
@@ -920,7 +925,15 @@ class MainActivity : ComponentActivity() {
}
return true
}
return super.dispatchKeyEvent(event)
// Compose throws when its focus tree has lost the focused node; one key is dropped
// instead of the app.
return try {
super.dispatchKeyEvent(event)
} catch (e: IllegalStateException) {
if (e.message?.contains("active focus target") != true) throw e
android.util.Log.w("MainActivity", "key ${event.keyCode} dropped: ${e.message}")
true
}
}
override fun onResume() {
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.agent
import com.droiddeck.launcher.session.SessionPaths
import android.Manifest
import android.content.ContentProvider
import android.content.ContentValues
@@ -107,7 +108,7 @@ class AgentBridgeProvider : ContentProvider() {
private fun state(context: Context): JSONObject {
val runtimeVersion = LinuxRuntimeInstaller.installedVersion(context)
val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: latestSessionDirectory()
val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: SessionPaths.sessionFolders(context).lastOrNull()
val session = JSONObject()
.put("id", SessionState.sessionId ?: dir?.name ?: JSONObject.NULL)
.put("phase", SessionState.phase.name)
@@ -163,12 +164,6 @@ class AgentBridgeProvider : ContentProvider() {
.put("session", session)
}
private fun latestSessionDirectory(): File? {
val parent = LinuxRuntime.debugLogDir()
return parent.listFiles { file -> file.isDirectory && file.name.startsWith("session-") }
?.maxWithOrNull(compareBy<File> { it.lastModified() }.thenBy { it.name })
}
private fun stop(context: Context): JSONObject {
if (SessionState.running) {
SessionService.stop(context)
@@ -75,9 +75,24 @@ object LogRedactor {
* user who signs in with a plain account name, not an email, had it in every log. The single
* space then a non-space keeps "OnLoginStateChange 0 1 0 0" (no account yet) as it is.
*/
private val LOGIN_STATE = Regex("(OnLoginStateChange )(\\S+)")
private val LOGIN_STATE = Regex("(?i)(OnLoginStateChange:? )([^\\s<]\\S*)")
private val LOGIN_USERS = Regex("(OnLoginUsersChanged )(\\S.*)$")
/**
* An account name as a field: `AccountName`, `account_name`, `username` (`"AccountName"
* "someone"` in a VDF, `account_name=...`, `"username": "..."`) and `login` - the last only
* as `login=`, a quoted key or a VDF pair, so "Login: OnLoginStateChange ..." keeps its label.
* A quoted value is blanked whole; one already blanked is left as it is.
*/
private const val ACCOUNT_VALUE = "(\"[^\"<\\r\\n]+\"|'[^'<\\r\\n]+'|[^\\s\"'<>&;,}]+)"
private val ACCOUNT_KV = Regex(
"(?i)(?<![A-Za-z0-9_])(account[_-]?name|user[_-]?name|epicusername)" +
"([\"']?\\s*[=:]\\s*|[\"']\\s+)" + ACCOUNT_VALUE
)
private val LOGIN_KV = Regex(
"(?i)(?<![A-Za-z0-9_])(login)(\\s*=\\s*|[\"']\\s*[=:]\\s*|[\"']\\s+)" + ACCOUNT_VALUE
)
/** The device's Steam accounts and persona names as patterns (see [learnAccounts]). */
@Volatile
private var accounts: List<Regex> = emptyList()
@@ -205,13 +220,49 @@ object LogRedactor {
* only when that matches, so a folder scrubbed under older rules is scrubbed again on the way
* out.
*/
const val RULES_VERSION = 2
const val RULES_VERSION = 3
/**
* A private IPv4 address (10/8, 172.16/12, 192.168/16, link-local 169.254/16): the home
* network's layout, e.g. its router as the resolver. Blanked in a shared zip only; public
* server addresses stay. Not part of a longer dotted number (a version like 10.0.19041.1).
*/
private val LAN_IPV4 = Regex(
"(?<![\\d.])(?:10\\.\\d{1,3}|192\\.168|172\\.(?:1[6-9]|2\\d|3[01])|169\\.254)\\.\\d{1,3}\\.\\d{1,3}(?!\\.?\\d)"
)
/** [src]'s lines, scrubbed, to [out]. */
fun scrubTo(src: java.io.File, out: java.io.Writer) {
src.forEachLine { line -> out.write(redact(line)); out.write("\n") }
}
/**
* The last pass for a file going into a shared zip: [redact], then the rules the stores' log
* uses too ([SecretScrub]) - URLs without query, fragment and user:password and with any
* token-bearing path segment blanked, token values and Authorization / Cookie headers blanked
* - and private IPv4 addresses as `<lan-address>`. A line already clean comes out unchanged.
*/
fun redactForShare(line: String): String {
if (line.isEmpty()) return line
return try {
val out = SecretScrub.scrub(redact(line), SecretScrub.Urls.KEEP_PATH, "<redacted:token>")
LAN_IPV4.replace(out, "<lan-address>")
} catch (t: Throwable) {
"<redaction failed; line withheld>"
}
}
/** [src]'s lines through [redactForShare], to [out]: the pass every text file in a shared zip gets. */
fun scrubForShare(src: java.io.File, out: java.io.Writer) {
src.forEachLine { line -> out.write(redactForShare(line)); out.write("\n") }
}
/** `<redacted:account>`, inside [value]'s quotes when it had them. */
private fun quoted(value: String): String {
val q = value.first().takeIf { it == '"' || it == '\'' }?.toString().orEmpty()
return "$q<redacted:account>$q"
}
/** [line] with every credential shape replaced. Null- and exception-safe by construction. */
fun redact(line: String): String {
if (line.isEmpty()) return line
@@ -240,6 +291,8 @@ object LogRedactor {
for (r in own) out = r.replace(out, "<redacted:ip>")
out = LOGIN_STATE.replace(out) { "${it.groupValues[1]}<redacted:account>" }
out = LOGIN_USERS.replace(out) { "${it.groupValues[1]}<redacted:account>" }
out = ACCOUNT_KV.replace(out) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" }
out = LOGIN_KV.replace(out) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" }
for (r in accounts) out = r.replace(out, "<redacted:account>")
out = EMAIL.replace(out, "<redacted:email>")
out = RESIDUAL.replace(out) { "${it.groupValues[1]}=<redacted:token>" }
@@ -0,0 +1,72 @@
package com.droiddeck.launcher.core
/**
* The one set of rules that keeps URLs and tokens out of anything the app writes or shares: the
* stores' log ([com.droiddeck.launcher.stores.StoreLog.redactLine]) and the last pass over every
* text file in a shared log zip ([LogRedactor.redactForShare]).
*
* - Every URL loses its query, fragment and `user:password@`. [Urls.SHORT] then keeps only the host
* and a plain first path segment (the stores' lines, where a GOG secure link carries its token in
* the path); [Urls.KEEP_PATH] keeps the path but blanks any segment that carries a token.
* - Outside URLs, the values of token-like keys (`token`, `__token__`, `f_token`, `hdnts`, access /
* refresh / id tokens; exchange and authorization codes of four characters or more, and a bare
* `code=` where it is one: in a query string or on a line with OAuth keys such as `client_id`,
* `redirect_uri` or `state`, never an 8-hex exception code like Proton's `code=c0000005`) and of
* Authorization / Cookie headers are blanked with [mark].
*
* A line already scrubbed comes out unchanged.
*/
object SecretScrub {
enum class Urls { SHORT, KEEP_PATH }
private val URL = Regex("""[A-Za-z][A-Za-z0-9+.\-]*://[^\s"'<>]+""")
private val SAFE_SEGMENT = Regex("""[A-Za-z0-9._\-]{1,40}""")
private val TOKEN_SEGMENT = Regex("""(?i)(token|hdnts|hmac|signature|sig|exp)=""")
private val TOKEN = Regex("""(?i)(?<![A-Za-z0-9_])(__token__|f_token|hdnts|access_token|refresh_token|id_token|token)(["']?\s*[=:]\s*["']?)[^\s&;,"'<>}]+""")
/** Codes that are only ever OAuth grants. */
private val GRANT_CODE = Regex("""(?i)(?<![A-Za-z0-9_])(exchange_code|authorization_?code)(["']?\s*=\s*["']?)[^\s&;,"'<>}]{4,}""")
/** A bare `code=`: a grant only right after `?` / `&` (a query string) or beside OAuth keys ([OAUTH_CONTEXT]). */
private val CODE = Regex("""(?i)(?<![A-Za-z0-9_])(code)(["']?\s*=\s*["']?)([^\s&;,"'<>}]{4,})""")
private val OAUTH_CONTEXT = Regex("""(?i)(?<![A-Za-z0-9_])(client_id|client_secret|redirect_uri|state|grant_type|response_type|access_token|refresh_token|id_token)["']?\s*[=:]""")
/** A Windows exception or status code (`code=c0000005`, `code=0x80000003`): never a grant. */
private val STATUS_CODE = Regex("""(?i)(0x)?[0-9a-f]{8}""")
private val HEADER = Regex("""(?i)\b(authorization|cookie|set-cookie)(\s*[:=]\s*).+""")
fun scrub(text: String, urls: Urls, mark: String): String {
var out = URL.replace(text) { m -> if (urls == Urls.SHORT) short(m.value) else keepPath(m.value, mark) }
out = TOKEN.replace(out) { m -> m.groupValues[1] + m.groupValues[2] + mark }
out = GRANT_CODE.replace(out) { m -> m.groupValues[1] + m.groupValues[2] + mark }
val oauth = OAUTH_CONTEXT.containsMatchIn(text)
val src = out
out = CODE.replace(src) { m ->
val inQuery = m.range.first > 0 && src[m.range.first - 1] in "?&"
val grant = !STATUS_CODE.matches(m.groupValues[3]) && (oauth || inQuery)
if (grant) m.groupValues[1] + m.groupValues[2] + mark else m.value
}
out = HEADER.replace(out) { m -> m.groupValues[1] + m.groupValues[2] + mark }
return out
}
private fun split(url: String): Triple<String, String, String?> {
val schemeEnd = url.indexOf("://")
val rest = url.substring(schemeEnd + 3).substringBefore('#').substringBefore('?')
val slash = rest.indexOf('/')
val authority = (if (slash >= 0) rest.substring(0, slash) else rest).substringAfterLast('@')
return Triple(url.substring(0, schemeEnd), authority, if (slash >= 0) rest.substring(slash + 1) else null)
}
private fun short(url: String): String {
val (scheme, authority, path) = split(url)
if (path == null) return "$scheme://$authority"
val first = path.substringBefore('/')
if (first.isEmpty()) return "$scheme://$authority/"
val shown = if (SAFE_SEGMENT.matches(first)) first else "…"
return "$scheme://$authority/$shown" + if (path.length > first.length && shown != "…") "/…" else ""
}
private fun keepPath(url: String, mark: String): String {
val (scheme, authority, path) = split(url)
val clean = path?.split('/')?.joinToString("/") { seg -> if (TOKEN_SEGMENT.containsMatchIn(seg)) mark else seg }
return "$scheme://$authority" + (clean?.let { "/$it" } ?: "")
}
}
@@ -1020,7 +1020,8 @@ fun FileManagerScreen(
// The ROMs folder chosen on the main screen: what the session shows as /root/ROMs.
SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let(::File)?.takeIf { it.isDirectory }
?.let { add(locItem(stringResource(R.string.fm_rail_roms), Icons.Filled.SportsEsports, it)) }
File("/storage/emulated/0/Download/DroidDeck").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_session_logs), Icons.Filled.Description, it)) }
// The app's own logs folder: private, which this file manager (the app itself) can read.
com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context).takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_session_logs), Icons.Filled.Description, it)) }
File("/storage/emulated/0/Pictures").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_pictures), Icons.Filled.Image, it)) }
}
val favItems = remember(favTick) { FavoritesStore.list(context).map(::File).filter { it.exists() } }
@@ -87,7 +87,7 @@ object FlatpakManager {
?.maxByOrNull { it.first }?.second
}
/** Runs [argv] in the runtime, its output also in Download/DroidDeck/flatpak-<verb>.log. */
/** Runs [argv] in the runtime, its output also in files/logs/tools/flatpak-<verb>.log. */
private fun runGuest(context: Context, argv: List<String>, fakeRoot: Boolean, onLine: (String) -> Unit): Int {
val name = "flatpak-" + (argv.getOrNull(2)?.takeIf { argv.getOrNull(1) == HELPER } ?: "setup")
return GuestCommand.run(context, argv, fakeRoot, name, onLine = onLine)
@@ -17,7 +17,7 @@ object GuestCommand {
/**
* Runs [argv] and hands each output line to [onLine]; returns the exit status. [fakeRoot] is
* for the package tools, which refuse any uid but 0. With [logName], everything the command
* says also goes to Download/DroidDeck/tools/<logName>.log beside the session logs, so a problem can
* says also goes to files/logs/tools/<logName>.log beside the session logs, so a problem can
* be handed over like a session's. With [linkDir], hard links (which Android denies apps)
* become symlinks to files proot keeps there (its link2symlink).
*/
@@ -25,7 +25,7 @@ object GuestCommand {
linkDir: File? = null, onLine: (String) -> Unit): Int {
val log = logName?.let {
try {
File(File(LinuxRuntime.debugLogDir(), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
} catch (e: Exception) { null }
}
log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}")
@@ -44,10 +44,20 @@ public final class LinuxRuntime {
public static final String GUEST_RUNTIME_DIR = "/run/droiddeck";
private static final String SYSTEM_FONTS = "/system/fonts";
private static final String GUEST_SYSTEM_FONTS = "/usr/local/share/fonts/android";
/** Where every Linux session's debug log lands: public, so a user can just hand the folder over. */
/** The folder under Downloads where builds before private logs wrote them; read only to move them. */
public static final String DEBUG_LOG_DIR = "DroidDeck";
public static File debugLogDir() {
/**
* Where every log lands: app-private, {@code files/logs}. Session folders, tools/ (one-off
* commands) and stores/ sit under it; the files directory is bound into every session at the
* same path, so the guest writes there too. Share logs is how a folder leaves the device.
*/
public static File logDir(Context context) {
return new File(context.getFilesDir(), "logs");
}
/** {@code Download/DroidDeck}, where earlier builds wrote logs. Only LogMigration reads it. */
public static File legacyLogDir() {
return new File(android.os.Environment.getExternalStoragePublicDirectory(
android.os.Environment.DIRECTORY_DOWNLOADS), DEBUG_LOG_DIR);
}
@@ -0,0 +1,73 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
/**
* Once, on the first start of a build with private logs: the session folders, tools/ and the loose
* tool logs that earlier builds left in `Download/DroidDeck/` move into `files/logs/`. Best effort:
* an item that cannot be moved stays where it is. Moved session folders lose their old scrub markers
* ([SessionArtifacts.unmarkMoved]), so [SessionArtifacts.scrubOlder] scrubs them under the current rules. Nothing else in that folder is touched - game
* save backups (Saves/) stay public - and after this pass the app never reads it again.
*/
object LogMigration {
private const val TAG = "LogMigration"
private const val MARKER = ".moved-from-downloads"
@Synchronized
fun run(context: Context) {
val target = LinuxRuntime.logDir(context).apply { mkdirs() }
val marker = File(target, MARKER)
if (marker.exists()) return
val legacy = LinuxRuntime.legacyLogDir()
val items = if (legacy.isDirectory) legacy.listFiles() else emptyArray()
// Unreadable (no storage access yet): try again next start rather than give up on them.
if (items == null) { Log.w(TAG, "$legacy cannot be listed; logs there stay until it can"); return }
var moved = 0
val movedFolders = ArrayList<File>()
for (f in items) {
val isLog = SessionPaths.isSessionFolder(f) ||
(f.isDirectory && f.name == SessionPaths.TOOLS_DIR) ||
(f.isFile && f.name.endsWith(".log"))
if (!isLog) continue
val dest = File(if (f.isFile) File(target, SessionPaths.TOOLS_DIR).apply { mkdirs() } else target, f.name)
if (dest.exists() && f.name != SessionPaths.TOOLS_DIR) continue
if (move(f, dest)) {
moved++
if (SessionPaths.isSessionFolder(dest)) movedFolders.add(dest)
} else Log.w(TAG, "could not move ${f.name}; left in place")
}
// Earlier builds scrubbed these under older rules (or not at all) and marked them done:
// without their markers, the pass over older folders that follows at the same start puts
// them through the current redactor.
SessionArtifacts.unmarkMoved(movedFolders)
try { marker.writeText("moved $moved item(s)\n") } catch (e: Exception) { Log.w(TAG, "could not mark the move: ${e.message}") }
if (moved > 0) Log.i(TAG, "moved $moved log item(s) from $legacy into $target")
}
/** A rename where it works (same volume), else a copy then the source's removal; false = left as it was. */
private fun move(src: File, dest: File): Boolean {
if (src.renameTo(dest)) return true
return try {
copy(src, dest)
FileUtils.delete(src)
true
} catch (e: Exception) {
Log.w(TAG, "copy of ${src.name} failed: ${e.message}")
false
}
}
private fun copy(src: File, dest: File) {
if (src.isDirectory) {
dest.mkdirs()
src.listFiles()?.forEach { copy(it, File(dest, it.name)) }
} else {
dest.parentFile?.mkdirs()
src.inputStream().use { input -> dest.outputStream().use { input.copyTo(it) } }
}
}
}
@@ -31,16 +31,20 @@ object SessionArtifacts {
/** Written last; a folder without it did not get its ending. */
const val COMPLETE_MARKER = ".complete"
/** Every file in the folder has been through the redactor, own addresses and accounts included (-2: accounts added). */
private const val SCRUBBED_MARKER = ".scrubbed-2"
/**
* Every file in the folder has been through the redactor under its current rules. Named after
* [LogRedactor.RULES_VERSION], so a folder scrubbed under older rules is scrubbed again.
*/
private val SCRUBBED_MARKER = ".scrubbed-r${LogRedactor.RULES_VERSION}"
private val OLD_SCRUBBED_MARKER = Regex("""\.scrubbed-(r?\d+)""")
/**
* Written by a session's own ending, and only when every file in the folder, subfolders
* included (whatever the session script copied into steam/ and droiddeck-esync/ as well as what
* the app wrote), went through the redactor without a failure. It lists each of those files
* with its size and modification time, under the redactor's rules version: a share copies a
* file as it is only when all three still match ([scrubbedFiles]), and scrubs anything else -
* a file added or changed since, a hidden one, or every file of a folder without it.
* with its size and modification time, under the redactor's rules version ([scrubbedFiles]).
* A share no longer relies on it: every text file goes through the share pass on the way into
* the zip regardless.
*/
const val SCRUBBED_TREE_MARKER = ".scrubbed-tree"
@@ -67,24 +71,48 @@ object SessionArtifacts {
}
/**
* Once, for session folders written before every file was scrubbed and before the device's own
* addresses were (network.txt listed them; the client's IPv6 check logs "external address"
* into steam/connection_log.txt): the whole folder, steam/ included, through the redactor.
* A marker records it. Runs at app start with [finishAbandoned].
* Every session folder not yet scrubbed under the redactor's current rules - written before
* every file was scrubbed, before the device's own addresses or the Steam account were, or
* moved in from Download/ ([LogMigration] strips their markers first, [unmarkMoved]): the
* whole folder, steam/ and every other subfolder included, through the redactor, and the
* current marker written in place of the old ones. Runs at app start with [finishAbandoned].
*
* A folder holds some 30 MB of Steam logs, about half a minute's work, so folders go through
* a few at a time; one the process does not get to keeps its old marker and is taken up at
* the next start.
*/
@Synchronized
fun scrubOlder(context: Context) {
val current = SessionPaths.current()
val dirs = LinuxRuntime.debugLogDir().listFiles { f ->
val dirs = LinuxRuntime.logDir(context).listFiles { f ->
SessionPaths.isSessionFolder(f) && f != current && !File(f, SCRUBBED_MARKER).exists()
} ?: return
}?.toList() ?: return
if (dirs.isEmpty()) return
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
dirs.forEach { dir ->
Record(dir).let { r -> scrubFolder(dir, r); File(dir, "steam").takeIf { it.isDirectory }?.let { scrubFolder(it, r) } }
try { File(dir, SCRUBBED_MARKER).writeText("scrubbed ${now()}\n") } catch (e: Exception) {}
val workers = (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 4)
val pool = java.util.concurrent.Executors.newFixedThreadPool(workers) { r ->
Thread({ android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); r.run() }, "scrub-logs")
}
val done = try {
pool.invokeAll(dirs.map { dir -> java.util.concurrent.Callable { scrubAndMark(dir) } })
.count { f -> try { f.get() } catch (e: Exception) { false } }
} finally {
pool.shutdown()
}
val failed = dirs.size - done
Log.i(TAG, "logs: scrubbed $done folders under r${LogRedactor.RULES_VERSION}" +
if (failed > 0) ", $failed not fully (again at the next start)" else "")
}
/**
* Folders [LogMigration] just moved in lose every scrub marker an earlier build left, so
* [scrubOlder], which runs right after it, puts them through the current rules whatever those
* markers claimed.
*/
fun unmarkMoved(dirs: List<File>) {
dirs.filter { SessionPaths.isSessionFolder(it) }.forEach { dir ->
dir.listFiles { f -> OLD_SCRUBBED_MARKER.matches(f.name) || f.name == SCRUBBED_TREE_MARKER }?.forEach { it.delete() }
}
Log.i(TAG, "scrubbed ${dirs.size} older session folder(s)")
}
/**
@@ -143,15 +171,17 @@ object SessionArtifacts {
* Records [record]'s folder as scrubbed - every file went through without a failure - or
* leaves it unmarked, so the next share and the pass over older folders scrub it again.
*/
private fun markScrubbed(record: Record) {
private fun markScrubbed(record: Record): Boolean {
val dir = record.dir
val tree = File(dir, SCRUBBED_TREE_MARKER)
// A marker from older rules vouches for nothing now, whether or not this pass succeeded.
dir.listFiles { f -> OLD_SCRUBBED_MARKER.matches(f.name) }?.forEach { it.delete() }
if (record.failed) {
tree.delete()
Log.w(TAG, "$dir is not fully scrubbed; it is scrubbed again when shared")
return
return false
}
try {
return try {
File(dir, SCRUBBED_MARKER).writeText("scrubbed ${now()}\n")
val lines = StringBuilder("rules ${LogRedactor.RULES_VERSION}\n")
record.files.forEach { (f, s) ->
@@ -159,8 +189,11 @@ object SessionArtifacts {
.append(f.relativeTo(dir).path).append('\n')
}
tree.writeText(lines.toString())
true
} catch (e: Exception) {
tree.delete()
File(dir, SCRUBBED_MARKER).delete()
false
}
}
@@ -181,9 +214,8 @@ object SessionArtifacts {
}.toSet()
}
/** The end-of-session scrub of [dir] on its own (steam/ already in place), for tests. */
@androidx.annotation.VisibleForTesting
internal fun scrubAndMark(dir: File) = markScrubbed(scrubTree(Record(dir)))
/** The end-of-session scrub of [dir] on its own (steam/ already in place); also the pass over older and moved folders. */
internal fun scrubAndMark(dir: File): Boolean = markScrubbed(scrubTree(Record(dir)))
/**
* [record]'s folder and every folder under it (steam/, droiddeck-esync/): the session script
@@ -223,7 +255,7 @@ object SessionArtifacts {
*/
@Synchronized
fun finishAbandoned(context: Context) {
val parent = LinuxRuntime.debugLogDir()
val parent = LinuxRuntime.logDir(context)
val abandoned = parent.listFiles { f ->
SessionPaths.isSessionFolder(f) && !File(f, COMPLETE_MARKER).exists()
}?.sortedWith(SessionPaths.chronological) ?: return
@@ -282,9 +314,7 @@ object SessionArtifacts {
val current = SessionPaths.current()
val gone = SessionPaths.sessionFolders(context).filter { it != current }
gone.forEach { com.droiddeck.launcher.core.FileUtils.delete(it) }
com.droiddeck.launcher.core.FileUtils.delete(File(LinuxRuntime.debugLogDir(), SessionPaths.TOOLS_DIR))
// Before tools/, those logs sat loose beside the session folders.
LinuxRuntime.debugLogDir().listFiles { f -> f.isFile && f.name.endsWith(".log") }?.forEach { it.delete() }
com.droiddeck.launcher.core.FileUtils.delete(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR))
Log.i(TAG, "cleared ${gone.size} session folder(s)")
return gone.size
}
@@ -361,25 +361,9 @@ object SessionFiles {
).joinToString(newline)
/**
* Where the session writes its log. Downloads is the point - a failed run is handed over as a
* folder rather than dug out of app-private storage - but the session script redirects its own
* output there with `exec`, and a redirection a non-interactive shell cannot open ends that
* shell. So a public directory is used only once it is proven writable; otherwise the app's
* own files directory, which is bound into the session anyway, stands in.
* Where the session writes its log: app-private `files/logs`, bound into the session at the same
* path, so the session script's own redirection always opens. A folder leaves the device only
* through Share logs, which scrubs every file again on the way into the zip.
*/
fun logDirectory(context: Context): File {
val public = LinuxRuntime.debugLogDir()
if (public.isDirectory || public.mkdirs()) {
val probe = File(public, ".writable")
try {
if (probe.createNewFile() || probe.isFile) {
probe.delete()
return public
}
} catch (ignored: Exception) {
}
}
Log.w(TAG, "$public is not writable (storage permission?); logging to files/logs")
return File(context.filesDir, "logs").apply { mkdirs() }
}
fun logDirectory(context: Context): File = LinuxRuntime.logDir(context).apply { mkdirs() }
}
@@ -18,9 +18,11 @@ import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
/**
* Zips the most recent session's log folder and hands it to Android's share sheet. Works where
* the folder could not be written to Downloads (no storage permission, or a device that refuses
* it) and landed in the app's private files instead, which a user cannot otherwise reach.
* Share logs: one zip, made when asked, of a session folder (the newest by default) with the last
* seven days of the stores' log and the one-off command logs beside it, handed to Android's share
* sheet. Logs live in app-private `files/logs`; this is how they leave the device. Every text file
* goes through [LogRedactor.redactForShare] on the way in, so even a file written before a rule
* existed is clean in the zip. The zip sits in `cache/share/` until the next share or app start.
*/
object SessionLogShare {
private val main = Handler(Looper.getMainLooper())
@@ -62,7 +64,7 @@ object SessionLogShare {
val files = folder.walkTopDown().filter { it.isFile }
.filterNot { it.parentFile?.name == "steam" && it.length() > STEAM_LOG_MAX_BYTES }.toList()
if (files.isEmpty()) return null
val out = File(context.cacheDir, "shared-logs").apply { deleteRecursively(); mkdirs() }
val out = shareDir(context).apply { deleteRecursively(); mkdirs() }
val zip = File(out, "DroidDeck-${folder.name}.zip")
// Scrubbed on the way into the zip: a session shared while it runs has not had its end-of-
// session pass yet, and the redactor changes nothing in a line that is already clean.
@@ -71,11 +73,11 @@ object SessionLogShare {
// since, goes in as it is; anything else (added or changed since, hidden, or any file of a
// session still running) is scrubbed again. Scrubbing tens of MB of the client's logs on
// every share kept the share sheet from appearing for ten seconds or more.
val scrubbed = SessionArtifacts.scrubbedFiles(folder)
val live = liveSteamLogs(context, folder)
// The stores' own log (last 7 days, app-private, already redacted), under stores/.
val storeLogs = com.droiddeck.launcher.stores.StoreLogFiles.files(context)
val total = (files + live + storeLogs).sumOf { it.length() }.coerceAtLeast(1L)
val logs = LinuxRuntime.logDir(context)
val stores = recent(File(logs, STORES_DIR))
val tools = recent(File(logs, SessionPaths.TOOLS_DIR))
val total = (files + live + stores + tools).sumOf { it.length() }.coerceAtLeast(1L)
var done = 0L
var shown = -1
fun advance(f: File) {
@@ -84,18 +86,20 @@ object SessionLogShare {
if (percent != shown) { shown = percent; onProgress?.invoke(percent / 100f) }
}
ZipOutputStream(zip.outputStream().buffered()).use { z ->
files.forEach { f -> addEntry(z, folder.name + "/" + f.relativeTo(folder).path, f, f.relativeTo(folder).path in scrubbed); advance(f) }
live.forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f, false); advance(f) }
storeLogs.forEach { f -> addEntry(z, folder.name + "/stores/" + f.name, f, false); advance(f) }
files.forEach { f -> addEntry(z, folder.name + "/" + f.relativeTo(folder).path, f); advance(f) }
live.forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f); advance(f) }
stores.forEach { f -> addEntry(z, "$STORES_DIR/" + f.name, f); advance(f) }
tools.forEach { f -> addEntry(z, SessionPaths.TOOLS_DIR + "/" + f.name, f); advance(f) }
}
return zip
}
private fun addEntry(z: ZipOutputStream, name: String, f: File, scrubbed: Boolean) {
private fun addEntry(z: ZipOutputStream, name: String, f: File) {
z.putNextEntry(ZipEntry(name))
if (!scrubbed && LogRedactor.isText(f)) {
// Every text file, every time: the folder's own scrub may predate a rule.
if (LogRedactor.isText(f)) {
val w = z.bufferedWriter()
LogRedactor.scrubTo(f, w)
LogRedactor.scrubForShare(f, w)
w.flush()
} else {
f.inputStream().use { it.copyTo(z) }
@@ -119,6 +123,25 @@ object SessionLogShare {
/** The client's content and bootstrap logs grow large over months and say nothing about a session. */
private const val STEAM_LOG_MAX_BYTES = 8L * 1024 * 1024
/** The stores' engine log, one file a day, under files/logs. */
const val STORES_DIR = "stores"
private const val RECENT_DAYS = 7
private fun shareDir(context: Context): File = File(context.cacheDir, "share")
/** The files in [dir] changed in the last [RECENT_DAYS] days. */
private fun recent(dir: File): List<File> {
val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L
return dir.listFiles { f -> f.isFile && f.lastModified() >= since }?.sortedBy { it.name }.orEmpty()
}
/** Deletes the last share's zip; at app start, so a zip never outlives the share it was made for. */
fun clear(context: Context) {
shareDir(context).deleteRecursively()
// Where builds before this one put it.
File(context.cacheDir, "shared-logs").deleteRecursively()
}
fun shareIntent(context: Context, zip: File): Intent {
val uri = FileProvider.getUriForFile(context, context.packageName + ".logs", zip)
val send = Intent(Intent.ACTION_SEND)
@@ -8,19 +8,20 @@ import java.util.Date
import java.util.Locale
/**
* One folder per session under `Download/DroidDeck/`, holding everything that session recorded,
* One folder per session under app-private `files/logs/`, holding everything that session recorded,
* named for the day, that day's session number and what was run, so the one a report is about can
* be picked out without opening any:
*
* ```
* Download/DroidDeck/2026-09-30-03-steam/
* files/logs/2026-09-30-03-steam/
* device.txt what this device is, and every setting the session ran with
* session.log the guest session: proot, gamescope, the client's stdout
* wayland.log the app's compositor
* steam.log the Steam client's own log, scrubbed (Steam mode)
* steam/ the rest of the client's logs, scrubbed (Steam mode)
* desktop.log KWin, Plasma and the programs on it (desktop mode)
* Download/DroidDeck/tools/ one-off commands: Flatpak installs, AppImage imports
* files/logs/tools/ one-off commands: Flatpak installs, AppImage imports
* files/logs/stores/ the stores' engine log, one file a day
* ```
*
* Folders from before this naming (`session-20260930-180642`) are still recognised, shared and
@@ -137,8 +138,7 @@ object SessionPaths {
/** Every session folder in the places logs are written, oldest first. */
fun sessionFolders(context: Context): List<File> =
listOf(com.droiddeck.launcher.runtime.LinuxRuntime.debugLogDir(), File(context.filesDir, "logs"))
.flatMap { parent -> parent.listFiles { f -> isSessionFolder(f) }?.toList() ?: emptyList() }
(com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context).listFiles { f -> isSessionFolder(f) }?.toList() ?: emptyList())
.sortedWith(chronological)
internal fun slug(text: String): String =
@@ -493,7 +493,7 @@ object SessionPrefs {
}
/**
* Whether a session writes its folder under Download/DroidDeck. Off, the same logs are kept in
* Whether a session keeps its folder under files/logs. Off, the same logs are kept in
* the app's cache for the session's lifetime (the scripts need somewhere to write) and thrown
* away at the end, so nothing accumulates in Downloads.
*/
@@ -398,7 +398,7 @@ object WinComponents {
* Downloads the component's package (.msi) or installer (.exe) into the runtime and has
* droiddeck-msi-install lay it out in [staging]. Returns the installer's result (product,
* version, counts, notes), or null and why. Everything the installer prints also goes to
* Download/DroidDeck/tools.
* files/logs/tools.
*/
private fun installPackage(context: Context, c: Component, step: Step, staging: File, onProgress: (Progress) -> Unit): Pair<JSONObject?, String> {
val root = LinuxRuntime.rootDir(context)
@@ -0,0 +1,105 @@
package com.droiddeck.launcher.stores
import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import org.json.JSONObject
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
/**
* The stores' sign-in files at rest: AES-256-GCM under a key that lives in the AndroidKeyStore and
* never leaves it, as a small versioned envelope `{"v":1,"alg":"AES/GCM","iv":...,"ct":...}`
* (base64). The session's Linux side shares the app's files directory but not its Keystore, so
* what it can see of a sign-in is the envelope only.
*/
object CredentialCipher {
const val VERSION = 1
const val ALG = "AES/GCM"
private const val TRANSFORMATION = "AES/GCM/NoPadding"
private const val TAG_BITS = 128
/** Where the key comes from: the AndroidKeyStore on a device, a plain key in tests. */
fun interface KeyProvider {
/** The key, created on first use. Throws when no key can be had (no Keystore on this ROM). */
fun key(): SecretKey
/** The key that sealed earlier files: never a new one. Throws [KeyMissing] when there is none. */
fun existing(): SecretKey = key()
}
/** The Keystore answered and holds no key: nothing sealed before can open again. */
class KeyMissing : java.security.GeneralSecurityException("no key")
/**
* Whether [e], from [open], means the file can never open: it does not authenticate (tampered,
* or sealed under another key), the key is permanently invalidated or gone, or the file is not
* an envelope. Anything else - the Keystore busy or erroring, an I/O error - may pass.
*/
fun isPermanent(e: Throwable): Boolean = e is javax.crypto.AEADBadTagException ||
e is android.security.keystore.KeyPermanentlyInvalidatedException ||
e is KeyMissing || e is org.json.JSONException || e is IllegalArgumentException
/**
* An AES-256 key in the AndroidKeyStore: not exportable, encrypt/decrypt with GCM only, no user
* authentication (background downloads and launch-time code fetches use it with the screen
* off). StrongBox where the device has it, the TEE otherwise.
*/
object Keystore : KeyProvider {
private const val ALIAS = "droiddeck-store-credentials"
private const val PROVIDER = "AndroidKeyStore"
@Synchronized
override fun existing(): SecretKey {
val ks = KeyStore.getInstance(PROVIDER).apply { load(null) }
return ks.getKey(ALIAS, null) as? SecretKey ?: throw KeyMissing()
}
@Synchronized
override fun key(): SecretKey {
val ks = KeyStore.getInstance(PROVIDER).apply { load(null) }
(ks.getKey(ALIAS, null) as? SecretKey)?.let { return it }
if (Build.VERSION.SDK_INT >= 28) {
try { return generate(strongBox = true) } catch (e: Exception) { /* no StrongBox: the TEE */ }
}
return generate(strongBox = false)
}
private fun generate(strongBox: Boolean): SecretKey {
val spec = KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setKeySize(256)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setUserAuthenticationRequired(false)
.apply { if (strongBox && Build.VERSION.SDK_INT >= 28) setIsStrongBoxBacked(true) }
.build()
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, PROVIDER).run { init(spec); generateKey() }
}
}
/** [plain] sealed into the envelope. The cipher picks the IV (the Keystore requires it). */
fun seal(plain: String, keys: KeyProvider): JSONObject {
val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.ENCRYPT_MODE, keys.key()) }
val ct = cipher.doFinal(plain.toByteArray(Charsets.UTF_8))
return JSONObject().put("v", VERSION).put("alg", ALG)
.put("iv", b64(cipher.iv)).put("ct", b64(ct))
}
/** The text inside [envelope]. Throws when it is not ours, of another version, or does not authenticate. */
fun open(envelope: JSONObject, keys: KeyProvider): String {
require(envelope.optInt("v", -1) == VERSION && envelope.optString("alg") == ALG) { "unknown envelope" }
val iv = Base64.decode(envelope.getString("iv"), Base64.NO_WRAP)
val ct = Base64.decode(envelope.getString("ct"), Base64.NO_WRAP)
val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.DECRYPT_MODE, keys.existing(), GCMParameterSpec(TAG_BITS, iv)) }
return String(cipher.doFinal(ct), Charsets.UTF_8)
}
/** Whether [json] is an envelope rather than plain credentials. */
fun isEnvelope(json: JSONObject): Boolean = json.has("v") && json.has("ct") && json.has("iv")
private fun b64(bytes: ByteArray) = Base64.encodeToString(bytes, Base64.NO_WRAP)
}
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.stores
import android.content.Context
import android.util.Log
import androidx.annotation.VisibleForTesting
import org.json.JSONObject
import java.io.File
@@ -9,40 +10,147 @@ import java.io.File
* Each store's sign-in, kept in the app's private files: `filesDir/stores/<store>/credentials.json`.
* Tokens never go to shared storage and never into a log; the file holds whatever the store's auth
* flow handed back (access and refresh tokens, expiry, the account's display name, and for Amazon
* the device registration), as one JSON object the store's own client reads and writes.
* the device registration), as one JSON object the store's own client reads and writes - sealed
* with [CredentialCipher] under a key in the AndroidKeyStore. Every read and write of a sign-in
* goes through here.
*
* - A plain file an earlier build wrote is sealed the first time it is read ([encryptAll] at app
* start), verified by opening it again, and the plain text is replaced.
* - Where the Keystore does not work (some ROMs), the file stays plain, the log says so once, and
* the next start tries again.
* - A sealed file that can never open again (the key is gone: data cleared, a backup restored on
* another device) is deleted and the store reads as signed out; one that fails for a reason that
* may pass is kept and tried again (see [read]).
*/
object StoreAccounts {
private const val TAG = "StoreAccounts"
private const val FILE = "credentials.json"
@VisibleForTesting
@Volatile
internal var keys: CredentialCipher.KeyProvider = CredentialCipher.Keystore
/** The Keystore failed once in this process: files stay plain until the next start tries again. */
@VisibleForTesting
@Volatile
internal var keystoreFailed = false
/** The store's private folder: credentials, caches, the engine's scratch. */
fun dir(context: Context, store: Store): File = File(File(context.filesDir, "stores"), store.id).apply { mkdirs() }
fun credentialsFile(context: Context, store: Store): File = File(dir(context, store), FILE)
/** The stored credentials, or null when signed out or unreadable (never logged: the text is the secret). */
/** Stores whose sealed sign-in could not be opened this time for a reason that may pass (see [read]). */
private val unavailable = java.util.concurrent.ConcurrentHashMap.newKeySet<Store>()
@Volatile
private var unavailableLogged = false
/**
* The stored credentials, or null when signed out or unreadable (never logged: the text is the
* secret).
*
* A sealed file is deleted - the store signs in again - only when it can never open: it does
* not authenticate (tampered, or another key: data cleared, restored on another device), the
* key is permanently invalidated or gone from the Keystore, or it is not an envelope at all. Any
* other failure (the Keystore busy or erroring, an I/O error) keeps the file, marks the store
* [isUnavailable] - signed in, its actions failing for now - and the next read tries again.
*/
@Synchronized
fun read(context: Context, store: Store): JSONObject? {
val f = credentialsFile(context, store)
if (!f.isFile) return null
return try { JSONObject(f.readText()) } catch (e: Exception) { Log.w(TAG, "${store.id}: credentials unreadable (${e.javaClass.simpleName})"); null }
if (!f.isFile) { unavailable.remove(store); return null }
val text = try { f.readText() } catch (e: Exception) { return markUnavailable(store, e) }
val json = try { JSONObject(text) } catch (e: Exception) { return unreadable(f, store, e) }
if (!CredentialCipher.isEnvelope(json)) {
unavailable.remove(store)
seal(f, json)?.let { Log.i(TAG, "stores: credentials encrypted ${store.id}") }
return json
}
return try {
JSONObject(CredentialCipher.open(json, keys)).also { unavailable.remove(store) }
} catch (e: Exception) {
if (CredentialCipher.isPermanent(e)) unreadable(f, store, e) else markUnavailable(store, e)
}
}
/** The store's sign-in is on disk but could not be opened this time (see [read]). */
fun isUnavailable(store: Store): Boolean = store in unavailable
private fun unreadable(f: File, store: Store, e: Exception): JSONObject? {
Log.w(TAG, "stores: credentials for ${store.id} cannot be opened (${e.javaClass.simpleName}); signed out")
f.delete()
unavailable.remove(store)
return null
}
private fun markUnavailable(store: Store, e: Exception): JSONObject? {
unavailable.add(store)
if (!unavailableLogged) {
unavailableLogged = true
Log.w(TAG, "stores: credentials unreadable this start (${e.javaClass.simpleName})")
}
return null
}
@Synchronized
fun write(context: Context, store: Store, json: JSONObject) {
unavailable.remove(store)
val f = credentialsFile(context, store)
val tmp = File(f.path + ".tmp")
tmp.writeText(json.toString())
tmp.setReadable(false, false); tmp.setReadable(true, true)
if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) }
if (seal(f, json) == null) put(f, json.toString())
}
@Synchronized
fun clear(context: Context, store: Store) {
unavailable.remove(store)
credentialsFile(context, store).delete()
File(credentialsFile(context, store).path + ".tmp").delete()
}
/** The account's display name when signed in (the store's own name for it, or a stand-in), else null. */
/** At app start: every plain sign-in an earlier build left is sealed now. */
fun encryptAll(context: Context) {
Store.entries.forEach { store ->
// An older build's temp file held the plain text too.
File(credentialsFile(context, store).path + ".tmp").delete()
read(context, store)
}
}
/**
* The account's display name when signed in (the store's own name for it, or a stand-in), else
* null. A sign-in that could not be opened this time ([isUnavailable]) still counts, under the
* store's name, so the sign-in card does not ask for what is still there.
*/
fun signedInAs(context: Context, store: Store): String? {
val json = read(context, store) ?: return null
val json = read(context, store) ?: return if (isUnavailable(store)) store.label else null
if (json.optString("access_token", "").isEmpty()) return null
return json.optString("display_name", "").ifEmpty { json.optString("username", "") }.ifEmpty { store.label }
}
/**
* [json] sealed into [f], checked by opening what was written. Null - and [f] as it was - when
* the Keystore cannot seal or the check fails.
*/
private fun seal(f: File, json: JSONObject): File? {
if (keystoreFailed) return null
val text = json.toString()
val envelope = try {
CredentialCipher.seal(text, keys).also { check(CredentialCipher.open(it, keys) == text) { "check failed" } }
} catch (e: Exception) {
keystoreFailed = true
Log.w(TAG, "stores: keystore unavailable, credentials stay plain (${e.javaClass.simpleName})")
return null
}
put(f, envelope.toString())
return f
}
/** [text] into [f] through a temp file and a rename, readable and writable by the app alone. */
private fun put(f: File, text: String) {
val tmp = File(f.path + ".tmp")
tmp.writeText(text)
tmp.setReadable(false, false); tmp.setReadable(true, true)
tmp.setWritable(false, false); tmp.setWritable(true, true)
if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) }
}
}
@@ -47,6 +47,11 @@ class StoreLoginActivity : ComponentActivity() {
private const val TAG = "StoreLogin"
const val EXTRA_STORE = "store"
private const val KEY_STATE = "oauth_state"
/**
* The colour the Stores page flooded to before opening this page, read once: the page opens
* on it, with no window animation, and its chrome rises in, as a session opens on Play's blue.
*/
@Volatile internal var floodColor: Int? = null
private const val CHROME_UA = "Mozilla/5.0 (Linux; Android 14; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.6533.103 Mobile Safari/537.36"
fun generateState(): String {
@@ -80,6 +85,8 @@ class StoreLoginActivity : ComponentActivity() {
private lateinit var titleText: TextView
private var oauthState: String? = null
private val captured = AtomicBoolean(false)
/** Opened behind a flood: it opens and closes with no window animation. */
private var flooded = false
private fun dp(value: Int): Int = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value.toFloat(), resources.displayMetrics).toInt()
@@ -88,8 +95,20 @@ class StoreLoginActivity : ComponentActivity() {
store = Store.byId(intent.getStringExtra(EXTRA_STORE))
oauthState = savedInstanceState?.getString(KEY_STATE) ?: generateState()
flow = store?.let { LoginFlows.forStore(it, oauthState!!) }
floodColor?.let { c ->
floodColor = null
flooded = true
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(c))
@Suppress("DEPRECATION") overridePendingTransition(0, 0)
}
if (flow == null) { finish(); return }
setContentView(buildChrome())
val chrome = buildChrome()
setContentView(chrome)
if (flooded) {
chrome.alpha = 0f
chrome.translationY = dp(14).toFloat()
chrome.animate().alpha(1f).translationY(0f).setStartDelay(60).setDuration(320).start()
}
val webView = newWebView(flow!!.userAgent, isPopup = false)
webViewRef = webView
contentHost.addView(webView, 0, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
@@ -105,6 +124,12 @@ class StoreLoginActivity : ComponentActivity() {
webView.loadUrl(flow!!.startUrl)
}
override fun finish() {
super.finish()
// Back to the Stores page, which is still covered in the flood and drains it from there.
@Suppress("DEPRECATION") if (flooded) overridePendingTransition(0, 0)
}
private fun buildChrome(): View {
val root = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setBackgroundColor(0xFF0A0B0D.toInt()) }
val bar = LinearLayout(this).apply {
@@ -125,40 +125,12 @@ object StoreLog {
}
}
private val URL_PATTERN = Regex("""[A-Za-z][A-Za-z0-9+.\-]*://[^\s"'<>]+""")
private val SAFE_SEGMENT = Regex("""[A-Za-z0-9._\-]{1,40}""")
private val SECRET = Regex("""(?i)(?<![A-Za-z0-9_])(__token__|f_token|hdnts|access_token|refresh_token|id_token|token)(["']?\s*[=:]\s*["']?)[^\s&;,"'}]+""")
private val CODE = Regex("""(?i)(?<![A-Za-z0-9_])(code|exchange_code|authorizationCode)(["']?\s*=\s*["']?)[^\s&;,"'}]+""")
private val AUTH_HEADER = Regex("""(?i)(authorization|cookie)(\s*[:=]\s*).*""")
/**
* What any store line may say, for the Downloads log and logcat alike: every URL cut to
* `scheme://host/first-segment/…` (the segment kept only when it is a plain name - a GOG secure
* link carries its token in the path), no query, fragment or userinfo; and outside URLs, the
* values of token-like keys and of Authorization / Cookie headers blanked.
* What any store line may say, for the stores' log and logcat alike: URLs cut to their host and a
* plain first path segment, token values and Authorization / Cookie headers blanked - the shared
* rules of [com.droiddeck.launcher.core.SecretScrub], which a shared log zip applies too.
*/
@JvmStatic
fun redactLine(text: String): String {
var out = URL_PATTERN.replace(text) { m -> shortUrl(m.value) }
out = SECRET.replace(out) { m -> m.groupValues[1] + m.groupValues[2] + "…" }
out = CODE.replace(out) { m -> m.groupValues[1] + m.groupValues[2] + "…" }
out = AUTH_HEADER.replace(out) { m -> m.groupValues[1] + m.groupValues[2] + "…" }
return out
}
private fun shortUrl(url: String): String {
val schemeEnd = url.indexOf("://")
val scheme = url.substring(0, schemeEnd)
var rest = url.substring(schemeEnd + 3)
rest = rest.substringBefore('#').substringBefore('?')
val slash = rest.indexOf('/')
val authority = (if (slash >= 0) rest.substring(0, slash) else rest).substringAfterLast('@')
if (slash < 0) return "$scheme://$authority"
val path = rest.substring(slash + 1)
val first = path.substringBefore('/')
val more = path.length > first.length
if (first.isEmpty()) return "$scheme://$authority/"
val shown = if (SAFE_SEGMENT.matches(first)) first else "…"
return "$scheme://$authority/$shown" + if (more && shown != "…") "/…" else ""
}
fun redactLine(text: String): String =
com.droiddeck.launcher.core.SecretScrub.scrub(text, com.droiddeck.launcher.core.SecretScrub.Urls.SHORT, "…")
}
@@ -118,6 +118,11 @@ object StoresState {
fun isSignedIn(store: Store): Boolean = accounts.containsKey(store)
/** A store action's error line when it found no usable sign-in: gone, or on disk but unreadable for now. */
fun notSignedInLine(store: Store): String =
if (StoreAccounts.isUnavailable(store)) "${store.shortLabel} sign-in could not be read: try again."
else "${store.shortLabel} session expired: sign in again."
/** Stores whose sign-in has run out (a launch could not get a code): their chip dims until the user signs in again. */
val expired = mutableStateMapOf<Store, Boolean>()
@@ -153,6 +158,11 @@ object StoresState {
if (force || !shelves.containsKey(store)) backend.loadShelves(app, force)
}
/** A store not signed into: its public storefront only, for its sign-in page to show. */
fun preview(context: Context, store: Store) {
if (!shelves.containsKey(store)) backends[store]?.loadShelves(context.applicationContext, false)
}
fun signIn(context: Context, store: Store) {
expired.remove(store)
backends[store]?.signIn(context) ?: logLine("${store.label}: this build has no sign-in for it yet")
@@ -45,17 +45,21 @@ object AmazonBackend : StoreBackend {
override fun syncLibrary(context: Context, force: Boolean) {
val app = context.applicationContext
val cached = AmazonLibrary.cached(app)
if (cached.isNotEmpty()) StoresState.post { publish(app, cached) }
StoresState.post { StoresState.status[store] = "Fetching your library…" }
Thread({
val result = AmazonLibrary.sync(app, force) { line -> StoresState.post { StoresState.status[store] = line } }
// The cache off the main thread; with it on screen a background sync keeps quiet.
val cached = AmazonLibrary.cached(app)
val quiet = cached.isNotEmpty() && !force
StoresState.post {
if (cached.isNotEmpty()) publish(app, cached)
if (!quiet) StoresState.status[store] = "Fetching your library…"
}
val result = AmazonLibrary.sync(app, force) { line -> if (!quiet) StoresState.post { StoresState.status[store] = line } }
StoresState.post {
StoresState.status.remove(store)
when (result) {
is AmazonLibrary.SyncResult.Ok -> { publish(app, result.games); StoresState.problems.remove(store) }
is AmazonLibrary.SyncResult.Failed -> StoresState.problems[store] = result.message
AmazonLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = "Amazon session expired: sign in again."
AmazonLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = StoresState.notSignedInLine(store)
AmazonLibrary.SyncResult.Throttled -> publish(app, AmazonLibrary.cached(app))
AmazonLibrary.SyncResult.Busy -> {}
}
@@ -6,6 +6,7 @@ import android.util.Log
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreNet
import com.droiddeck.launcher.stores.StoresState
import org.json.JSONArray
import org.json.JSONObject
import java.util.concurrent.Callable
@@ -70,7 +71,7 @@ object AmazonLibrary {
}
onStatus("Checking sign-in…")
val creds = AmazonCredentialStore.load(app) ?: return SyncResult.NotLoggedIn
val token = AmazonCredentialStore.getValidAccessToken(app) ?: return SyncResult.Failed("Amazon session expired: sign in again.")
val token = AmazonCredentialStore.getValidAccessToken(app) ?: return SyncResult.Failed(StoresState.notSignedInLine(Store.AMAZON))
onStatus("Fetching game list…")
val all = AmazonApiClient.getEntitlements(token, creds.deviceSerial)
if (all.isNullOrEmpty()) return if (cachedList.isEmpty()) SyncResult.Failed("No games found in your Amazon library") else SyncResult.Ok(cachedList)
@@ -41,11 +41,15 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
override fun syncLibrary(context: Context, force: Boolean) {
val app = context.applicationContext
val cached = EpicLibrary.cached(app)
if (cached.isNotEmpty()) StoresState.post { StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], cached.map { EpicLibrary.toCatalogItem(app, it) }) }
StoresState.post { StoresState.status[store] = "Fetching your library…" }
Thread({
val result = EpicLibrary.sync(app, force) { line -> StoresState.post { StoresState.status[store] = line } }
// The cache off the main thread; with it on screen a background sync keeps quiet.
val cached = EpicLibrary.cached(app).map { EpicLibrary.toCatalogItem(app, it) }
val quiet = cached.isNotEmpty() && !force
StoresState.post {
if (cached.isNotEmpty()) StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], cached)
if (!quiet) StoresState.status[store] = "Fetching your library…"
}
val result = EpicLibrary.sync(app, force) { line -> if (!quiet) StoresState.post { StoresState.status[store] = line } }
StoresState.post {
StoresState.status.remove(store)
when (result) {
@@ -53,8 +57,8 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], result.games.map { EpicLibrary.toCatalogItem(app, it) }); StoresState.problems.remove(store)
}
is EpicLibrary.SyncResult.Failed -> StoresState.problems[store] = result.message
EpicLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = "Epic session expired: sign in again."
EpicLibrary.SyncResult.Throttled -> if (!StoresState.library.containsKey(store)) StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], cached.map { EpicLibrary.toCatalogItem(app, it) })
EpicLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = StoresState.notSignedInLine(store)
EpicLibrary.SyncResult.Throttled -> if (!StoresState.library.containsKey(store)) StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], cached)
EpicLibrary.SyncResult.Busy -> {}
}
}
@@ -31,18 +31,22 @@ object GogBackend : StoreBackend {
override fun syncLibrary(context: Context, force: Boolean) {
val app = context.applicationContext
// The cache first, so the tab has something while the sync runs.
val cached = GogLibrary.cached(app)
if (cached.isNotEmpty()) StoresState.post { StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], cached.map { GogLibrary.toCatalogItem(app, it) }) }
StoresState.post { StoresState.status[store] = "Fetching your library…" }
Thread({
val result = GogLibrary.sync(app, force) { line -> StoresState.post { StoresState.status[store] = line } }
// The cache first, so the tab has something while the sync runs; read here, not on the
// main thread. With a cache on screen a background sync keeps quiet: only Refresh shows its bar.
val cached = GogLibrary.cached(app).map { GogLibrary.toCatalogItem(app, it) }
val quiet = cached.isNotEmpty() && !force
StoresState.post {
if (cached.isNotEmpty()) StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], cached)
if (!quiet) StoresState.status[store] = "Fetching your library…"
}
val result = GogLibrary.sync(app, force) { line -> if (!quiet) StoresState.post { StoresState.status[store] = line } }
StoresState.post {
StoresState.status.remove(store)
when (result) {
is GogLibrary.SyncResult.Ok -> { StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], result.games.map { GogLibrary.toCatalogItem(app, it) }); StoresState.problems.remove(store) }
is GogLibrary.SyncResult.Failed -> StoresState.problems[store] = result.message
GogLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = "GOG session expired: sign in again."
GogLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = StoresState.notSignedInLine(store)
GogLibrary.SyncResult.Busy -> {}
}
}
@@ -23,6 +23,9 @@ object GogLibrary {
// v2: the card art moved from the store page's backdrop to the Galaxy library art; an older cache is re-fetched.
private const val CACHE_KEY = "library_cache_v2"
private const val LAST_SYNC_KEY = "library_synced_at"
// Owned products that are not Windows games (DLC, films, soundtracks, other platforms): never in
// the cache, so without this every sync would fetch each of them again.
private const val SKIPPED_KEY = "library_skipped"
private const val THROTTLE_MS = 6L * 60L * 60L * 1000L
private val syncing = AtomicBoolean(false)
@@ -75,18 +78,22 @@ object GogLibrary {
val stale = System.currentTimeMillis() - p.getLong(LAST_SYNC_KEY, 0L) >= THROTTLE_MS
val heavy = force || cachedList.isEmpty() || stale
val cachedIds = cachedList.mapTo(HashSet()) { it.gameId }
val idsToFetch = if (heavy) ids else ids.filter { it !in cachedIds }
val skipped = java.util.Collections.newSetFromMap(java.util.concurrent.ConcurrentHashMap<String, Boolean>())
if (!heavy) skipped.addAll(p.getStringSet(SKIPPED_KEY, emptySet()).orEmpty())
val idsToFetch = if (heavy) ids else ids.filter { it !in cachedIds && it !in skipped }
val fetchSet = idsToFetch.toHashSet()
val merged = LinkedHashMap<String, GogGame>()
for (g in cachedList) if (g.gameId in ownedSet && g.gameId !in fetchSet) merged[g.gameId] = g
if (idsToFetch.isEmpty()) {
val list = merged.values.toList()
skipped.retainAll(ownedSet)
p.edit().putStringSet(SKIPPED_KEY, HashSet(skipped)).apply()
saveCache(p, list)
return SyncResult.Ok(list.sortedBy { it.title.lowercase() }, 0)
}
onStatus("Syncing ${idsToFetch.size} game${if (idsToFetch.size == 1) "" else "s"}…")
val pool = Executors.newFixedThreadPool(5)
val futures = idsToFetch.map { id -> pool.submit(Callable<GogGame?> { fetchGame(p, id, token) }) }
val futures = idsToFetch.map { id -> pool.submit(Callable<GogGame?> { fetchGame(p, id, token, skipped) }) }
pool.shutdown()
var fetched = 0
for ((idx, f) in futures.withIndex()) {
@@ -96,6 +103,8 @@ object GogLibrary {
}
val finalList = merged.values.toList()
saveCache(p, finalList)
skipped.retainAll(ownedSet)
p.edit().putStringSet(SKIPPED_KEY, HashSet(skipped)).apply()
if (heavy) p.edit().putLong(LAST_SYNC_KEY, System.currentTimeMillis()).apply()
Log.i(TAG, "sync: owned=${ids.size} fetched=$fetched cached=${finalList.size} heavy=$heavy")
return SyncResult.Ok(finalList.sortedBy { it.title.lowercase() }, fetched)
@@ -108,16 +117,18 @@ object GogLibrary {
}
/** One product's details, or null for anything that is not a Windows game (DLC, movies, other platforms). */
private fun fetchGame(prefs: SharedPreferences, id: String, token: String): GogGame? {
private fun fetchGame(prefs: SharedPreferences, id: String, token: String, skipped: MutableSet<String>): GogGame? {
// Not a game this app installs: remembered, so the next sync does not ask again.
fun skip(): GogGame? { skipped.add(id); return null }
try {
val productJson = StoreNet.get("https://api.gog.com/products/$id?expand=downloads,description", bearer = token) ?: return null
val prod = JSONObject(productJson)
if (prod.optBoolean("is_secret", false)) return null
if (prod.optBoolean("is_secret", false)) return skip()
val gameType = prod.optString("game_type", "")
if (gameType.isNotEmpty() && gameType != "game" && gameType != "pack") return null
if (gameType.isNotEmpty() && gameType != "game" && gameType != "pack") return skip()
var title = prod.optJSONObject("title")?.optString("*")
if (title.isNullOrEmpty()) title = prod.optString("title")
if (title.isNullOrEmpty()) return null
if (title.isNullOrEmpty()) return skip()
// Card art from the v2 game record, the way the Galaxy client draws its library: the dark
// Galaxy background for the wide card and the box art for the tall one. The product's
// `images.background` is the store page's fade-out backdrop (it ends in white on a
@@ -164,7 +175,7 @@ object GogLibrary {
prod.optJSONObject("downloads")?.optJSONArray("installers")?.let { arr ->
for (di in 0 until arr.length()) if (arr.optJSONObject(di)?.optString("os", "") == "windows") { hasWindowsInstaller = true; break }
}
if (!hasWindowsBuild && !hasWindowsInstaller) return null
if (!hasWindowsBuild && !hasWindowsInstaller) return skip()
var verticalCover: String? = boxArt.ifEmpty { prefs.getString("vcover_$id", null) }
if (verticalCover.isNullOrEmpty()) {
@@ -147,6 +147,10 @@ private fun follow(): AnimationSpec<Float> = Motion.sp(1f, 2400f)
/** How long after a focus move the ring keeps its stretchy springs and keeps checking where it is. */
private const val SETTLE_MS = 450L
/** How long the control must stand still before the ring stops checking where it is. */
private const val STILL_MS = 120L
/** The longest the ring keeps checking after a move, for a control that never stands still. */
private const val TRACK_MAX_MS = 2_000L
/** Moves closer together than this are a held direction: the ring runs along as one, no stretch. */
private const val REPEAT_MS = 180L
@@ -213,17 +217,23 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
launch { corner.animateTo(r, Motion.tw(90)) }
dot(here).forEachIndexed { i, v -> launch { edges[i].animateTo(v, Motion.tw(90)) } }
}
// Across as a dot, every edge together, on a timed ease.
// Across as a dot, every edge together, on a timed ease, steering each frame for
// where the control is now: one still rising into place is met where it ends up.
val distance = hypot(b.center.x - here.x, b.center.y - here.y) / density.density
val travel = (180 + distance * 0.12f).toInt().coerceIn(220, 380)
dot(b.center).forEachIndexed { i, v ->
jobs[i] = launch { edges[i].animateTo(v, Motion.tw(travel, easing = FastOutSlowInEasing)) }
}
val p = Animatable(0f)
val flight = launch { p.animateTo(1f, Motion.tw(travel, easing = FastOutSlowInEasing)) }
// Takes the control's shape as it arrives, not after: no resting as a dot.
delay(Motion.ms((travel * 0.78f).toInt()).toLong())
while (flight.isActive && p.value < 0.78f) {
val to = (glide.boundsOf(s) ?: b).center
dot(Offset(here.x + (to.x - here.x) * p.value, here.y + (to.y - here.y) * p.value)).forEachIndexed { i, v -> edges[i].snapTo(v) }
withFrameNanos { }
}
flight.cancel()
val at = glide.boundsOf(s) ?: b
launch { solid.animateTo(0f, Motion.tw(150)) }
launch { corner.animateTo(endCorner, Motion.sp(0.8f, 600f)) }
listOf(b.left, b.top, b.right, b.bottom).forEachIndexed { i, v ->
listOf(at.left, at.top, at.right, at.bottom).forEachIndexed { i, v ->
jobs[i] = launch { edges[i].animateTo(v, Motion.sp(0.7f, 750f)) }
}
}
@@ -267,8 +277,11 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
var first = src !== shown
val start = System.nanoTime()
var last: Rect? = null
var seen: Rect? = null
var stillSince = start
while (true) {
val b = glide.boundsOf(src)
if (b != seen) { seen = b; stillSince = System.nanoTime() }
if (b == null) {
if (first) scope.launch { alpha.animateTo(0f, Motion.tw(140)) }
} else if (first) {
@@ -318,9 +331,12 @@ internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable
if (last == null) scope.launch { alpha.animateTo(1f, Motion.tw(120)) }
last = b
}
// Layer animations (a tile growing, a row sliding) move it without a relayout, so
// look again each frame for a moment after anything changes.
if ((System.nanoTime() - start) / 1_000_000 > SETTLE_MS) break
// Layer animations (a tile growing, a row sliding, a page rising in) move it without
// a relayout, so look again each frame until it has stood still a moment: a fixed
// window let the ring park mid-rise and jump over when something next laid out.
val now = System.nanoTime()
val settled = (now - start) / 1_000_000 > SETTLE_MS && (now - stillSince) / 1_000_000 > STILL_MS
if (settled || (now - start) / 1_000_000 > TRACK_MAX_MS) break
withFrameNanos { }
}
}
@@ -193,8 +193,9 @@ private fun RailItem(
if (count > 0) Text(
if (count > 9) "9+" else count.toString(),
fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.onSignal, maxLines = 1,
// Pops with the Downloads chip's count as an install's dot lands there.
modifier = Modifier.align(Alignment.TopEnd).padding(top = if (iconOnly) 4.dp else 6.dp, end = if (iconOnly) 5.dp else 12.dp)
.clip(RoundedCornerShape(8.dp)).background(pal.signal).padding(horizontal = 5.dp, vertical = 1.dp),
.landingPop().clip(RoundedCornerShape(8.dp)).background(pal.signal).padding(horizontal = 5.dp, vertical = 1.dp),
)
}
}
@@ -22,7 +22,13 @@ import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.geometry.isSpecified
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.clipPath
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.unit.dp
@@ -67,7 +73,13 @@ internal const val PAGE_RETURN_MS = 900
* The focus ring stays out of it until it is done.
*/
@Composable
internal fun PageFlood(from: Origin, leaving: Boolean, content: @Composable () -> Unit) {
internal fun PageFlood(
from: Origin,
leaving: Boolean,
/** What the tile shows instead of the control's fill: a game card's art, cropped to the tile as it grows. */
art: Painter? = null,
content: @Composable () -> Unit,
) {
val pal = LocalPalette.current
val glide = LocalFocusGlide.current
// Left, top, right, bottom: 0 on the control, 1 on the pane's edge.
@@ -113,7 +125,7 @@ internal fun PageFlood(from: Origin, leaving: Boolean, content: @Composable () -
Box(Modifier.fillMaxSize().clipToBounds().onSizeChanged { size = Size(it.width.toFloat(), it.height.toFloat()) }) {
Box(Modifier.fillMaxSize().graphicsLayer { alpha = shown.value; translationY = (1f - shown.value) * 14.dp.toPx() }) { content() }
Canvas(Modifier.fillMaxSize()) {
if (tile.value > 0.01f) drawTile(from, edges.map { it.value }, pal.surface, pal.line2, tile.value)
if (tile.value > 0.01f) drawTile(from, edges.map { it.value }, pal.surface, pal.line2, tile.value, art)
}
}
}
@@ -122,7 +134,7 @@ internal fun PageFlood(from: Origin, leaving: Boolean, content: @Composable () -
* The control's tile with its edges [v] of the way to the pane's (left, top, right, bottom):
* sinking with the page behind, blobby in flight, square once it fills the pane.
*/
private fun DrawScope.drawTile(from: Origin, v: List<Float>, fill: Color, line: Color, alpha: Float) {
private fun DrawScope.drawTile(from: Origin, v: List<Float>, fill: Color, line: Color, alpha: Float, art: Painter? = null) {
val (l, t, r, b) = v
val mean = v.sumOf { it.coerceIn(0f, 1f).toDouble() }.toFloat() / 4f
// The control sinks with the page behind it (scaled to 0.95 about the pane's centre).
@@ -139,6 +151,17 @@ private fun DrawScope.drawTile(from: Origin, v: List<Float>, fill: Color, line:
val blob = sin(PI * mean).toFloat().coerceAtLeast(0f)
val corner = lerp(from.corner * (1f - mean), minOf(w, h) * 0.42f, blob)
drawRoundRect(fill, Offset(left, top), Size(w, h), CornerRadius(corner), alpha = alpha)
val pic = art?.intrinsicSize?.takeIf { it.isSpecified && it.width > 0f && it.height > 0f }
if (art != null && pic != null && w > 0f && h > 0f) {
// The art covers the tile at every size (a centre crop), so a portrait card opens into the
// wide pane without stretching.
val k = maxOf(w / pic.width, h / pic.height)
val dw = pic.width * k
val dh = pic.height * k
clipPath(Path().apply { addRoundRect(RoundRect(left, top, left + w, top + h, CornerRadius(corner))) }) {
translate(left + (w - dw) / 2f, top + (h - dh) / 2f) { with(art) { draw(Size(dw, dh), alpha = alpha) } }
}
}
// The control's outline, kept while it is still the size of one.
val edge = (1f - mean * 3f).coerceIn(0f, 1f)
if (edge > 0f) drawRoundRect(line, Offset(left, top), Size(w, h), CornerRadius(corner), alpha = alpha * edge, style = Stroke(1.dp.toPx()))
@@ -1003,45 +1003,6 @@ private val StepBoxCorner = 16.dp
private val StepFillet = 10.dp
private val StepBoxMaxWidth = 264.dp
/**
* The stair-step outline: the pill [p] on top, a box under it from [left] to the pill's right edge
* and down to [bottom], the pull between them [pullTop] (the box's top). Right edges are flush and
* the inside corner where the pull meets the box is rounded the other way. While the box is still
* no wider than the pill it is just the pill, stretched down.
*/
private fun stepPath(path: Path, p: Rect, left: Float, bottom: Float, pullTop: Float, box: Float, fillet: Float) {
path.reset()
val r = p.right; val tl = p.left; val tt = p.top
val pb = maxOf(bottom, p.bottom)
val l = minOf(left, tl)
val pt = minOf(pullTop, pb)
val sw = tl - l
val h = (pb - pt).coerceAtLeast(0f)
val rt = minOf(p.height / 2f, p.width / 2f)
val rbr = minOf(box, (pb - tt) / 2f)
val rbl = minOf(lerp(minOf(box, (pb - tt) / 2f), minOf(box, h / 2f), (sw / box).coerceIn(0f, 1f)), (r - l) / 2f)
val rpl = minOf(box, sw / 2f, h / 2f)
val f = minOf(fillet, sw / 2f)
val yl = minOf(pt + rpl, pb - rbl)
fun corner(rect: Rect, start: Float, sweep: Float, endX: Float, endY: Float) {
if (rect.width < 0.5f) path.lineTo(endX, endY) else path.arcTo(rect, start, sweep, false)
}
path.moveTo(tl + rt, tt)
path.lineTo(r - rt, tt)
corner(Rect(r - 2 * rt, tt, r, tt + 2 * rt), -90f, 90f, r, tt + rt)
path.lineTo(r, pb - rbr)
corner(Rect(r - 2 * rbr, pb - 2 * rbr, r, pb), 0f, 90f, r - rbr, pb)
path.lineTo(l + rbl, pb)
corner(Rect(l, pb - 2 * rbl, l + 2 * rbl, pb), 90f, 90f, l, pb - rbl)
path.lineTo(l, yl)
corner(Rect(l, pt, l + 2 * rpl, pt + 2 * rpl), 180f, 90f, l + rpl, pt)
path.lineTo(tl - f, pt)
corner(Rect(tl - 2 * f, pt - 2 * f, tl, pt), 90f, -90f, tl, pt - f)
path.lineTo(tl, tt + rt)
corner(Rect(tl, tt, tl + 2 * rt, tt + 2 * rt), 180f, 90f, tl + rt, tt)
path.close()
}
/**
* Stop's confirm, grown out of the Stop pill at [pill] (px, in the sheet): a pull the pill's width
* drops out of it and a wider box steps out to the left under it for the choices, right edges
@@ -115,6 +115,11 @@ import androidx.compose.ui.window.PopupProperties
private val RowShape = RoundedCornerShape(12.dp)
private val GroupShape = RoundedCornerShape(14.dp)
/** Whether a pad's A is held right now, as the activity sees it: a focus move waits for its release. */
internal object HeldKeys {
@Volatile var confirm = false
}
internal fun Modifier.controllerConfirm(enabled: Boolean = true, onClick: () -> Unit): Modifier = onPreviewKeyEvent { event ->
val keyEvent = event.nativeKeyEvent
if (keyEvent.keyCode != KeyEvent.KEYCODE_BUTTON_A) {
@@ -126,6 +126,20 @@ internal fun CapsuleWall(
games: List<Library.SteamGame>,
driftMs: Int = if (games.isEmpty()) 75_000 else 40_000,
modifier: Modifier = Modifier,
) = TiltedWall(games.size, driftMs, modifier) { i, m ->
Capsule(if (games.isEmpty()) null else games[i], RoundedCornerShape(10.dp), m)
}
/**
* [CapsuleWall]'s tilted, drifting columns for any [count] of capsules; [capsule] draws number i
* (0 until [count], or 0 for each blank one when [count] is 0) at the modifier it is given.
*/
@Composable
internal fun TiltedWall(
count: Int,
driftMs: Int,
modifier: Modifier = Modifier,
capsule: @Composable (index: Int, modifier: Modifier) -> Unit,
) {
val capW = 112.dp
val capH = 168.dp
@@ -165,8 +179,7 @@ internal fun CapsuleWall(
},
) {
repeat(perRun * 2) { i ->
val g = if (games.isEmpty()) null else games[(c * 5 + (i % perRun) * 3) % games.size]
Capsule(g, RoundedCornerShape(10.dp), Modifier.size(capW, capH))
capsule(if (count == 0) 0 else (c * 5 + (i % perRun) * 3) % count, Modifier.size(capW, capH))
}
}
}
@@ -0,0 +1,326 @@
package com.droiddeck.launcher.ui
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationVector1D
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Matrix
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
// End session's confirm, for any control: a pull drops out of the control and a wider box steps
// out under it for the choices, one edge flush with the control. Stop draws it from its pill on
// the drawer; the stores draw it from Install, the Library tab and a download's cancel.
/**
* The stair-step outline: the pill [p] on top, a box under it from [left] to the pill's right edge
* and down to [bottom], the pull between them [pullTop] (the box's top). Right edges are flush and
* the inside corner where the pull meets the box is rounded the other way. While the box is still
* no wider than the pill it is just the pill, stretched down. [pillCorner] is the control's own
* corner: a pill's is half its height.
*/
internal fun stepPath(
path: Path, p: Rect, left: Float, bottom: Float, pullTop: Float, box: Float, fillet: Float,
pillCorner: Float = minOf(p.height / 2f, p.width / 2f),
) {
path.reset()
val r = p.right; val tl = p.left; val tt = p.top
val pb = maxOf(bottom, p.bottom)
val l = minOf(left, tl)
val pt = minOf(pullTop, pb)
val sw = tl - l
val h = (pb - pt).coerceAtLeast(0f)
val rt = minOf(pillCorner, p.height / 2f, p.width / 2f)
val rbr = minOf(box, (pb - tt) / 2f)
val rbl = minOf(lerpF(minOf(box, (pb - tt) / 2f), minOf(box, h / 2f), (sw / box).coerceIn(0f, 1f)), (r - l) / 2f)
val rpl = minOf(box, sw / 2f, h / 2f)
val f = minOf(fillet, sw / 2f)
val yl = minOf(pt + rpl, pb - rbl)
fun corner(rect: Rect, start: Float, sweep: Float, endX: Float, endY: Float) {
if (rect.width < 0.5f) path.lineTo(endX, endY) else path.arcTo(rect, start, sweep, false)
}
path.moveTo(tl + rt, tt)
path.lineTo(r - rt, tt)
corner(Rect(r - 2 * rt, tt, r, tt + 2 * rt), -90f, 90f, r, tt + rt)
path.lineTo(r, pb - rbr)
corner(Rect(r - 2 * rbr, pb - 2 * rbr, r, pb), 0f, 90f, r - rbr, pb)
path.lineTo(l + rbl, pb)
corner(Rect(l, pb - 2 * rbl, l + 2 * rbl, pb), 90f, 90f, l, pb - rbl)
path.lineTo(l, yl)
corner(Rect(l, pt, l + 2 * rpl, pt + 2 * rpl), 180f, 90f, l + rpl, pt)
path.lineTo(tl - f, pt)
corner(Rect(tl - 2 * f, pt - 2 * f, tl, pt), 90f, -90f, tl, pt - f)
path.lineTo(tl, tt + rt)
corner(Rect(tl, tt, tl + 2 * rt, tt + 2 * rt), 180f, 90f, tl + rt, tt)
path.close()
}
/** [stepPath] for a box that steps out to the right of the pill, out to [right], left edges flush. */
internal fun stepPathRight(
path: Path, p: Rect, right: Float, bottom: Float, pullTop: Float, box: Float, fillet: Float,
pillCorner: Float = minOf(p.height / 2f, p.width / 2f),
) {
// Drawn as the left-hand outline about the pill's centre, which maps the pill onto itself,
// then mirrored back: x -> (p.left + p.right) - x.
val axis = p.left + p.right
stepPath(path, p, axis - right, bottom, pullTop, box, fillet, pillCorner)
path.transform(Matrix().apply { this[0, 0] = -1f; this[3, 0] = axis })
}
private fun lerpF(a: Float, b: Float, t: Float) = a + (b - a) * t
/** Which way the box steps out of its control. */
internal enum class StepSide {
/** Out to the left, right edges flush (a control at the right: Stop, a row's cancel). */
Left,
/** Out to the right, left edges flush (a control at the left: Install, a tab). */
Right,
}
/** The choices' side of a [StepOut]: each piece fades in on its own beat, and [first] takes focus. */
internal class StepOutScope(private val items: List<Animatable<Float, AnimationVector1D>>, val first: FocusRequester, val open: Boolean) {
/** Piece [i] (0 first) of the box: it fades and rises in after the box has stepped out. */
fun Modifier.stepItem(i: Int): Modifier = graphicsLayer {
val v = items[i.coerceIn(0, items.lastIndex)].value
alpha = v
translationY = (1f - v) * 6.dp.toPx()
}
}
/** Room between the control and the box that steps out under it: the pull. */
private val OutPull = 6.dp
private val OutBoxCorner = 16.dp
private val OutFillet = 10.dp
/**
* A confirm or a short list grown out of the control at [pill] (px, in this element's space, which
* should fill the screen area it may cover): a pull the control's width drops out of it, then a
* box steps out to [side] for [content]. [onDismiss] (B, a tap outside) asks to fold it; it folds
* back width first once [open] is false, then [onClosed]. Exactly StopConfirm's springs.
*/
@OptIn(ExperimentalComposeUiApi::class)
@Composable
internal fun StepOut(
open: Boolean,
pill: Rect,
side: StepSide,
accent: Color,
onDismiss: () -> Unit,
onClosed: () -> Unit,
pillCorner: Dp? = null,
maxWidth: Dp = 300.dp,
items: Int = 4,
handle: @Composable () -> Unit,
content: @Composable StepOutScope.() -> Unit,
) {
val colors = MaterialTheme.colorScheme
val density = LocalDensity.current
val inputMode = LocalInputModeManager.current
val edge = remember { Animatable(0f) }
val bottom = remember { Animatable(0f) }
val tint = remember { Animatable(0f) }
val dim = remember { Animatable(0f) }
val pieces = remember { List(items) { Animatable(0f) } }
var grown by remember { mutableStateOf(false) }
var measured by remember { mutableStateOf<IntSize?>(null) }
val first = remember { FocusRequester() }
val pull = with(density) { OutPull.toPx() }
val corner = pillCorner?.let { with(density) { it.toPx() } } ?: minOf(pill.height, pill.width) / 2f
BoxWithConstraints(Modifier.fillMaxSize()) {
val hostWidth = constraints.maxWidth.toFloat()
val room = if (side == StepSide.Left) pill.right else hostWidth - pill.left
val maxW = with(density) { maxWidth.toPx() }.coerceAtMost(room).coerceAtLeast(pill.width)
LaunchedEffect(open, measured) {
// Asked to close before it ever measured: nothing to fold.
if (!open && !grown) { onClosed(); return@LaunchedEffect }
val c = measured ?: return@LaunchedEffect
val rest = if (side == StepSide.Left) pill.left else pill.right
val out = if (side == StepSide.Left) (pill.right - c.width).coerceAtLeast(0f) else (pill.left + c.width).coerceAtMost(hostWidth)
val boxBottom = pill.bottom + pull + c.height
if (open) {
if (!grown) {
edge.snapTo(rest); bottom.snapTo(pill.bottom); tint.snapTo(0f)
pieces.forEach { it.snapTo(0f) }
grown = true
}
coroutineScope {
launch { dim.animateTo(1f, Motion.tw(260)) }
launch { tint.animateTo(1f, Motion.tw(200)) }
launch { bottom.animateTo(boxBottom, Motion.sp(0.7f, 380f)) }
launch { delay(Motion.ms(110).toLong()); edge.animateTo(out, Motion.sp(0.55f, 300f)) }
pieces.forEachIndexed { i, a ->
launch { delay(Motion.ms(260 + i * 55).toLong()); a.animateTo(1f, Motion.tw(220)) }
}
if (inputMode.inputMode == InputMode.Keyboard) launch {
delay(Motion.ms(300).toLong())
withFrameNanos { }
runCatching { first.requestFocus() }
}
}
} else {
coroutineScope {
pieces.forEach { launch { it.animateTo(0f, Motion.tw(90)) } }
launch { delay(Motion.ms(60).toLong()); dim.animateTo(0f, Motion.tw(300)) }
launch { delay(Motion.ms(60).toLong()); edge.animateTo(rest, Motion.sp(1f, 420f)) }
launch { delay(Motion.ms(160).toLong()); bottom.animateTo(pill.bottom, Motion.sp(1f, 380f)) }
launch { delay(Motion.ms(200).toLong()); tint.animateTo(0f, Motion.tw(200)) }
}
grown = false
onClosed()
}
}
// Opened by touch and then answered with a pad: the pad starts in the box, not behind it.
LaunchedEffect(open, grown, inputMode.inputMode) {
if (open && grown && inputMode.inputMode == InputMode.Keyboard) { withFrameNanos { }; runCatching { first.requestFocus() } }
}
// The rest of the screen dims behind it, and a tap there folds it. Never a pad's stop.
Box(
Modifier.fillMaxSize().graphicsLayer { alpha = dim.value }.background(Color(0x59000000))
.focusProperties { canFocus = false }
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, enabled = open, onClick = onDismiss),
)
val path = remember { Path() }
val boxCorner = with(density) { OutBoxCorner.toPx() }
val fillet = with(density) { OutFillet.toPx() }
val rim = with(density) { 1.4.dp.toPx() }
val restFill = colors.surface
val hotFill = lerp(colors.surface, accent, 0.22f)
Canvas(Modifier.fillMaxSize()) {
if (!grown) return@Canvas
if (side == StepSide.Left) stepPath(path, pill, edge.value, bottom.value, pill.bottom + pull, boxCorner, fillet, corner)
else stepPathRight(path, pill, edge.value, bottom.value, pill.bottom + pull, boxCorner, fillet, corner)
drawPath(path, lerp(hotFill, restFill, tint.value))
drawPath(path, accent.copy(alpha = lerpF(0.9f, 0.55f, tint.value)), style = Stroke(rim))
}
// The control's label rides on top, as the pull's handle.
if (grown) Box(
contentAlignment = Alignment.Center,
modifier = Modifier.offset { IntOffset(pill.left.roundToInt(), pill.top.roundToInt()) }
.size(with(density) { pill.width.toDp() }, with(density) { pill.height.toDp() }),
) { handle() }
val x = if (side == StepSide.Left) pill.right - (measured?.width?.toFloat() ?: maxW) else pill.left
Column(
modifier = Modifier
.offset { IntOffset(x.roundToInt(), (pill.bottom + pull).roundToInt()) }
.widthIn(min = with(density) { pill.width.toDp() }, max = with(density) { maxW.toDp() })
.onSizeChanged { if (measured != it) measured = it }
.controllerBack(onDismiss)
// A pad stays in the box until it is answered or folded, as it did in Stop's dialog.
.focusProperties { exit = { FocusRequester.Cancel } }
.focusGroup()
.padding(start = 14.dp, end = 14.dp, top = 12.dp, bottom = 12.dp),
) { StepOutScope(pieces, first, open).content() }
}
}
/**
* One choice in a [StepOut]: a capsule that fills when focused, like Stop's Cancel and Stop. [danger]
* draws it in red; [icon] and [trailing] make it a row (a place to install to and its free space).
*/
@Composable
internal fun StepChoice(
label: String,
modifier: Modifier = Modifier,
danger: Boolean = false,
icon: ImageVector? = null,
trailing: String? = null,
selected: Boolean = false,
enabled: Boolean = true,
onClick: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(20.dp)
val accent = if (danger) colors.error else pal.signal
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = modifier.heightIn(min = 40.dp).clip(shape)
.background(if (hot || selected) accent.copy(alpha = if (danger) 0.18f else 0.14f) else Color.Transparent)
.glideBorder(hot, shape, accent, if (selected) accent.copy(alpha = 0.5f) else Color.Transparent)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, role = Role.Button, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = 16.dp),
) {
if (icon != null) Icon(icon, null, tint = if (hot) accent else colors.onBackground, modifier = Modifier.size(20.dp))
Text(
label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = if (danger) colors.error else colors.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = if (trailing != null) Modifier.weight(1f) else Modifier,
)
if (trailing != null) Text(trailing, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1)
}
}
/** A [StepOut]'s heading line, the first piece to fade in. */
@Composable
internal fun StepOutScope.StepTitle(text: String) {
Text(
text, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.stepItem(0).padding(start = 4.dp, bottom = 10.dp),
)
}
/** The choices of a [StepOut] stacked, each the box's width. */
@Composable
internal fun StepList(content: @Composable ColumnScope.() -> Unit) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp), content = content)
}
@@ -1,5 +1,7 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -94,11 +96,11 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { com.droiddeck.launcher.stores.download.DownloadQueue.cancel(ctx, download.key) }
}
item?.owned == true && StoresState.isUnfinished(item) -> {
PrimaryButton(stringResource(R.string.stores_resume_install), main = true) { StoresState.requestInstall(ctx, item) }
InstallButton(stringResource(R.string.stores_resume_install)) { StoresState.requestInstall(ctx, item) }
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
}
item?.owned == true -> PrimaryButton(
if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install), main = true,
item?.owned == true -> InstallButton(
if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install),
) { StoresState.requestInstall(ctx, item) }
item != null && item.isFree -> PrimaryButton(stringResource(R.string.stores_get_free), main = true) { openStoreUrl(ctx, item) }
item != null -> PrimaryButton(if (item.hasPrice && item.finalPrice.isNotBlank()) stringResource(R.string.stores_buy_price, item.finalPrice) else stringResource(R.string.stores_view_on, store.shortLabel), main = true) { openStoreUrl(ctx, item) }
@@ -116,3 +118,18 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
Text(description, fontSize = 13.sp, lineHeight = 19.sp, color = colors.onSurfaceVariant, maxLines = 6, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 12.dp))
}
}
/**
* Install (or Resume install) that says where it sits when pressed: where to install grows out of
* it, and the download it starts leaves it as a dot for the Downloads chip.
*/
@Composable
private fun InstallButton(label: String, onInstall: () -> Unit) {
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
Box(Modifier.onGloballyPositioned { placed[0] = it }) {
PrimaryButton(label, main = true) {
StoresMotion.markInstall(placed[0]?.takeIf { it.isAttached }?.boundsInRoot(), label)
onInstall()
}
}
}
@@ -1,11 +1,40 @@
package com.droiddeck.launcher.ui
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.expandHorizontally
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleOut
import androidx.compose.animation.shrinkHorizontally
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.Canvas
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.composed
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import androidx.compose.ui.draw.alpha
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.clickable
import androidx.compose.material.icons.automirrored.outlined.Undo
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Pause
@@ -77,37 +106,81 @@ internal fun StoresDownloadsPane(s: FrontEndState, a: FrontEndActions) {
@Composable
private fun DownloadList(s: FrontEndState, a: FrontEndActions) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val scope = rememberCoroutineScope()
val entries = StoresState.downloads
if (entries.isEmpty()) {
Box(Modifier.fillMaxWidth().padding(vertical = 40.dp), contentAlignment = Alignment.Center) {
Text(stringResource(R.string.stores_downloads_empty), fontSize = 13.sp, color = colors.onSurfaceVariant)
}
return
}
// Clearing: the finished rows go into the divider's X one by one, bottom first, and only then
// leave the queue.
var clearing by remember { mutableStateOf(false) }
// Under way on top; finished below a line whose X clears them all (rows only - a failed
// download's kept files stay until its game page's Clear).
val (active, finished) = entries.partition { it.isActive }
val finishedShown = if (clearing) emptyList() else finished
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
// The list changes only when rows come, go or change state; each row reads its own progress.
active.forEachIndexed { i, row -> key(row.key) { Rise(1 + i.coerceAtMost(5)) { DownloadCard(StoresState.download(row.key) ?: row, s, a) } } }
if (finished.isNotEmpty()) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(top = if (active.isEmpty()) 0.dp else 4.dp)) {
Box(Modifier.weight(1f).height(1.dp).background(LocalPalette.current.line))
RoundAction(Icons.Outlined.Close, stringResource(R.string.stores_dl_clear_all), size = 30.dp) { DownloadQueue.dismissFinished() }
AnimatedVisibility(entries.isEmpty(), enter = fadeIn(Motion.tw(300, 300)), exit = fadeOut(Motion.tw(120))) {
Box(Modifier.fillMaxWidth().padding(vertical = 40.dp), contentAlignment = Alignment.Center) {
Text(stringResource(R.string.stores_downloads_empty), fontSize = 13.sp, color = colors.onSurfaceVariant)
}
finished.forEach { row ->
key(row.key) {
val d = StoresState.download(row.key) ?: row
if (d.state == DownloadState.FAILED) DownloadCard(d, s, a) else FinishedRow(d, s, a)
}
// The list changes only when rows come, go or change state; each row reads its own progress.
// A row pours out of the count's side (the right), and leaves the way it came; one that
// installed stays a beat for its bar to gather into Play first.
AnimatedRows(
active, key = { it.key },
enter = { i, later ->
val wait = if (later) 0 else 90 * i.coerceAtMost(4)
expandHorizontally(Motion.tw(360, wait), expandFrom = Alignment.End) + expandVertically(Motion.tw(320, wait), expandFrom = Alignment.Top) +
fadeIn(Motion.tw(300, wait + 60))
},
exit = { row, _, _ ->
if (StoresState.download(row.key)?.state == DownloadState.INSTALLED)
fadeOut(Motion.tw(220, GATHER_HOLD_MS)) + shrinkVertically(Motion.tw(300, GATHER_HOLD_MS))
else shrinkHorizontally(Motion.tw(260), shrinkTowards = Alignment.End) + shrinkVertically(Motion.tw(300, 120)) + fadeOut(Motion.tw(200, 80))
},
) { row, _ -> DownloadCard(StoresState.download(row.key) ?: row, s, a) }
AnimatedVisibility(
finishedShown.isNotEmpty(),
enter = expandVertically(Motion.tw(260)) + fadeIn(Motion.tw(220)),
exit = fadeOut(Motion.tw(200, 60 * finished.size.coerceAtMost(8) + 160)) + shrinkVertically(Motion.tw(220, 60 * finished.size.coerceAtMost(8) + 200)),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(top = if (active.isEmpty()) 0.dp else 4.dp)) {
Box(Modifier.weight(1f).height(1.dp).background(pal.line))
RoundAction(Icons.Outlined.Close, stringResource(R.string.stores_dl_clear_all), size = 30.dp) {
if (!clearing) {
val n = finished.size.coerceAtMost(8)
clearing = true
scope.launch {
delay(Motion.ms(60 * n + 420).toLong())
DownloadQueue.dismissFinished()
clearing = false
}
}
}
}
}
AnimatedRows(
finishedShown, key = { it.key },
// One that just finished joins after its row above has gathered; the rest are simply there.
enter = { i, later -> if (later) expandVertically(Motion.tw(300, GATHER_HOLD_MS)) + fadeIn(Motion.tw(220, GATHER_HOLD_MS + 50)) else fadeIn(Motion.tw(300, 60 * i.coerceAtMost(5))) },
// Into the X at the top right, bottom row first.
exit = { _, i, n ->
val wait = 60 * (n - 1 - i).coerceIn(0, 8)
scaleOut(Motion.tw(220, wait), targetScale = 0.2f, transformOrigin = TransformOrigin(1f, 0f)) +
fadeOut(Motion.tw(200, wait + 40)) + shrinkVertically(Motion.tw(240, wait + 80))
},
) { row, later ->
val d = StoresState.download(row.key) ?: row
if (d.state == DownloadState.FAILED) DownloadCard(d, s, a) else FinishedRow(d, s, a, bloom = later)
}
}
}
/** A finished download: its name and store, and Play when it installed. */
/** How long a row that installed holds for its bar to gather into Play before it moves under the line. */
private const val GATHER_HOLD_MS = 900
/** A finished download: its name and store, and Play when it installed - blooming out of a dot when it just did. */
@Composable
private fun FinishedRow(d: DownloadEntry, s: FrontEndState, a: FrontEndActions) {
private fun FinishedRow(d: DownloadEntry, s: FrontEndState, a: FrontEndActions, bloom: Boolean = false) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
Row(
@@ -117,10 +190,24 @@ private fun FinishedRow(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
Text(d.name, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
SourceChip(d.store.id, small = true)
Text(stringResource(if (d.state == DownloadState.INSTALLED) R.string.stores_installed_chip else R.string.stores_dl_cancelled), fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, modifier = Modifier.weight(1f))
if (d.state == DownloadState.INSTALLED) RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { launchStoreGame(ctx, d.store, d.id, s, a) }
if (d.state == DownloadState.INSTALLED) Box(Modifier.bloomIn(bloom, GATHER_HOLD_MS + 150)) {
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { launchStoreGame(ctx, d.store, d.id, s, a) }
}
}
}
/** Grows out of a dot (sp 0.5 / 300) after [waitMs], when [on]; otherwise just there. */
private fun Modifier.bloomIn(on: Boolean, waitMs: Int): Modifier = composed {
val k = remember { Animatable(if (on && Motion.scale > 0f) 0f else 1f) }
LaunchedEffect(Unit) {
if (k.value < 1f) {
delay(Motion.ms(waitMs).toLong())
k.animateTo(1f, Motion.sp(0.5f, 300f))
}
}
graphicsLayer { scaleX = k.value; scaleY = k.value; alpha = k.value.coerceIn(0f, 1f) }
}
/**
* A row's action as a round icon button - the label is its description - sized like the old
* compact buttons and focusable by pad. [primary] fills it with the accent, [danger] in red.
@@ -146,18 +233,62 @@ internal fun RoundAction(
) { androidx.compose.material3.Icon(icon, description, tint = tint, modifier = Modifier.size(size * 0.5f)) }
}
/** Cancel in two taps: the stop icon, then a red delete and a keep that undoes it (back by itself after a few seconds). */
/**
* Cancel as End session's confirm: the X drops a pull and Keep and Delete step out to its left,
* in red. Keep's rim runs out the four seconds after which it folds back by itself.
*/
@Composable
private fun CancelAction(onDelete: () -> Unit) {
var armed by remember { mutableStateOf(false) }
androidx.compose.runtime.LaunchedEffect(armed) { if (armed) { kotlinx.coroutines.delay(4000); armed = false } }
if (!armed) RoundAction(Icons.Outlined.Close, stringResource(R.string.stores_dl_cancel)) { armed = true }
else {
RoundAction(Icons.Outlined.Delete, stringResource(R.string.stores_dl_cancel_confirm), danger = true) { armed = false; onDelete() }
RoundAction(Icons.AutoMirrored.Outlined.Undo, stringResource(R.string.stores_notification_keep)) { armed = false }
val colors = MaterialTheme.colorScheme
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
val keep = stringResource(R.string.stores_notification_keep)
val delete = stringResource(R.string.stores_dl_cancel_confirm)
Box(Modifier.onGloballyPositioned { placed[0] = it }) {
RoundAction(Icons.Outlined.Close, stringResource(R.string.stores_dl_cancel)) {
val at = placed[0]?.takeIf { it.isAttached }?.boundsInRoot() ?: return@RoundAction
StoresMotion.ask(StepAsk(
anchor = at, side = StepSide.Left, accent = colors.error, items = 2,
handle = { androidx.compose.material3.Icon(Icons.Outlined.Close, null, tint = colors.error, modifier = Modifier.size(18.dp)) },
) {
val left = remember { Animatable(1f) }
LaunchedEffect(Unit) {
// Wall-clock seconds, as before; the rim follows them when animations run.
if (Motion.scale > 0f) launch { left.animateTo(0f, androidx.compose.animation.core.tween((CANCEL_HOLD_MS / Motion.scale).toInt(), easing = LinearEasing)) }
delay(CANCEL_HOLD_MS.toLong())
StoresMotion.fold()
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) {
StepChoice(keep, enabled = open, modifier = Modifier.stepItem(0).focusRequester(first).timeRim({ left.value }, colors.onBackground)) { StoresMotion.fold() }
StepChoice(delete, danger = true, enabled = open, modifier = Modifier.stepItem(1)) { StoresMotion.fold(); onDelete() }
}
})
}
}
}
private const val CANCEL_HOLD_MS = 4000
/** A capsule's outline drawn for [left] (1 to 0) of its length, clockwise from the top centre: time running out. */
private fun Modifier.timeRim(left: () -> Float, color: Color): Modifier = drawWithContent {
drawContent()
val v = left()
if (v <= 0f) return@drawWithContent
val w = 1.5.dp.toPx()
val r = size.height / 2f
val outline = androidx.compose.ui.graphics.Path().apply {
moveTo(size.width / 2f, w / 2f)
lineTo(size.width - r, w / 2f)
arcTo(Rect(size.width - 2 * r + w / 2f, w / 2f, size.width - w / 2f, size.height - w / 2f), -90f, 180f, false)
lineTo(r, size.height - w / 2f)
arcTo(Rect(w / 2f, w / 2f, 2 * r - w / 2f, size.height - w / 2f), 90f, 180f, false)
lineTo(size.width / 2f, w / 2f)
}
val measure = androidx.compose.ui.graphics.PathMeasure().apply { setPath(outline, false) }
val part = androidx.compose.ui.graphics.Path()
measure.getSegment(0f, measure.length * v, part, true)
drawPath(part, color.copy(alpha = 0.8f), style = androidx.compose.ui.graphics.drawscope.Stroke(w))
}
@Composable
private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions) {
val ctx = LocalContext.current
@@ -216,7 +347,10 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
CancelAction { DownloadQueue.cancel(ctx, d.key) }
}
DownloadState.FAILED -> RoundAction(Icons.Filled.Refresh, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.retry(ctx, d.key) }
DownloadState.INSTALLED -> RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { launchStoreGame(ctx, d.store, d.id, s, a) }
// Just installed (this row is on its way under the line): Play blooms where the bar gathered.
DownloadState.INSTALLED -> Box(Modifier.bloomIn(true, 420)) {
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { launchStoreGame(ctx, d.store, d.id, s, a) }
}
DownloadState.CANCELLED -> {}
}
}
@@ -227,29 +361,87 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
/**
* One segment per stage - Manifest, Download, Verify, Install - equal widths: a passed or skipped
* stage full, the active one filling with its own progress (a sliver while it has nothing to count),
* the rest empty.
* the rest empty. Fills ride a spring; a stage that completes swells and settles (the bloop); a
* paused one breathes; and once the download has installed the four gather into one green line
* that draws up into a dot, where Play blooms.
*/
@Composable
private fun StageBar(d: DownloadEntry) {
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
val stages = listOf(DownloadStage.MANIFEST, DownloadStage.DOWNLOAD, DownloadStage.VERIFY, DownloadStage.INSTALL)
Row(horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier.fillMaxWidth()) {
for (st in stages) {
val active = d.state != DownloadState.INSTALLED && d.stage == st
val fill = when {
active -> d.stageFraction.let { if (it < 0f) 0.04f else it }
// A stage a store skips or folds into another (Epic checks chunks while it fetches,
// Amazon writes while it downloads) reads complete once a later one has started.
d.passed(st) || st.ordinal < d.stage.ordinal || d.stage == DownloadStage.DONE -> 1f
else -> 0f
}
Box(Modifier.weight(1f)) {
ProgressBarThin(
fill, paused = active && d.state == DownloadState.PAUSED, verify = active && st == DownloadStage.VERIFY,
height = 6.dp, done = !active && fill >= 1f,
)
}
val installed = d.state == DownloadState.INSTALLED
val actives = stages.map { st -> !installed && d.stage == st }
val fills = stages.mapIndexed { i, st ->
when {
actives[i] -> d.stageFraction.let { if (it < 0f) 0.04f else it }
// A stage a store skips or folds into another (Epic checks chunks while it fetches,
// Amazon writes while it downloads) reads complete once a later one has started.
d.passed(st) || st.ordinal < d.stage.ordinal || d.stage == DownloadStage.DONE -> 1f
else -> 0f
}
}
val done = fills.mapIndexed { i, f -> !actives[i] && f >= 1f }
val shown = fills.mapIndexed { i, f -> animateFloatAsState(f, Motion.sp(0.8f, 300f), label = "stage$i") }
val bloops = remember { List(4) { Animatable(1f) } }
val wasDone = remember { done.toBooleanArray() }
done.forEachIndexed { i, dn ->
LaunchedEffect(i, dn) {
if (dn && !wasDone[i] && Motion.scale > 0f) {
bloops[i].animateTo(1.6f, Motion.tw(90))
bloops[i].animateTo(1f, Motion.sp(0.45f, 600f))
}
wasDone[i] = dn
}
}
val gather = remember { Animatable(0f) }
LaunchedEffect(installed) { if (installed) gather.animateTo(1f, Motion.tw(520, easing = androidx.compose.animation.core.CubicBezierEasing(0.6f, 0f, 0.15f, 1f))) }
val paused = d.state == DownloadState.PAUSED
val breath = breathing(paused)
val verifyColor = Color(0xFF9B6DFF)
val pausedColor = Color(0xFFFFC24D)
Canvas(Modifier.fillMaxWidth().height(10.dp)) {
val h = 6.dp.toPx()
val cy = size.height / 2f
val g = gather.value
if (g < 0.5f) {
// The segments: the gaps close and every fill turns done-green as the gather starts.
val join = (g * 2f).coerceIn(0f, 1f)
val gap = 3.dp.toPx() * (1f - join)
val segW = (size.width - gap * 3f) / 4f
for (i in 0 until 4) {
val x = i * (segW + gap)
drawRoundRect(colors.surfaceVariant, Offset(x, cy - h / 2f), Size(segW, h), CornerRadius(h / 2f))
val base = when {
done[i] -> pal.good
actives[i] && paused -> pausedColor.copy(alpha = breath)
actives[i] && stages[i] == DownloadStage.VERIFY -> verifyColor
else -> pal.signal
}
val fill = androidx.compose.ui.util.lerp(shown[i].value.coerceIn(0f, 1f), 1f, join)
val hh = h * bloops[i].value
if (fill > 0f) drawRoundRect(
androidx.compose.ui.graphics.lerp(base, pal.good, join), Offset(x, cy - hh / 2f), Size(segW * fill, hh), CornerRadius(hh / 2f),
)
}
} else {
// One line drawing up into a dot at its right end.
val p = ((g - 0.5f) * 2f).coerceIn(0f, 1f)
val dot = 10.dp.toPx()
val left = androidx.compose.ui.util.lerp(0f, size.width - dot, p)
val hh = androidx.compose.ui.util.lerp(h, dot, p)
drawRoundRect(pal.good, Offset(left, cy - hh / 2f), Size(size.width - left, hh), CornerRadius(hh / 2f), alpha = 1f - p * 0.4f)
}
}
}
/** 1, or while [on] (and animations run), an alpha going 1 → 0.5 → 1 over the rail's live-dot period. */
@Composable
private fun breathing(on: Boolean): Float {
if (!on || Motion.scale == 0f) return 1f
val t = rememberInfiniteTransition(label = "breath")
val v by t.animateFloat(1f, 0.5f, infiniteRepeatable(androidx.compose.animation.core.tween(800), RepeatMode.Reverse), label = "breathe")
return v
}
private fun eta(seconds: Long): String = when {
@@ -0,0 +1,390 @@
package com.droiddeck.launcher.ui
import android.os.SystemClock
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.spring
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.lerp
import com.droiddeck.launcher.stores.Store
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlin.math.PI
import kotlin.math.atan2
import kotlin.math.max
import kotlin.math.sin
// The Stores section's moves, in the launcher's own vocabulary: an install bloops into a dot that
// flies to the Downloads chip, sign-in floods in the store's colour and comes home to the chip's
// dot, and the confirms step out of the control that asked (StepOut). Everything here is in root
// coordinates; the Stores page draws it in its own space.
internal object StoresMotion {
/** The Install (or Resume install) button last pressed, its label and when: a download that starts soon after flies from it. */
var installFrom: Rect? = null
private set
var installLabel: String = ""
private set
private var installAt = 0L
fun markInstall(bounds: Rect?, label: String) {
installFrom = bounds
installLabel = label
installAt = SystemClock.uptimeMillis()
}
/** The button just pressed, if it was pressed in the last few seconds; not consumed. */
fun recentInstall(): Rect? = installFrom.takeIf { SystemClock.uptimeMillis() - installAt < 5_000 }
/** The button a download that just started came from, once; stale after 20 s (a slow manifest). */
fun takeInstall(): Rect? = installFrom.takeIf { SystemClock.uptimeMillis() - installAt < 20_000 }.also { installAt = 0L }
/** Where the Downloads chip sits, for a download's dot to land in. */
var downloadsChip by mutableStateOf<Rect?>(null)
/** Bumped each time a dot lands: the chip's count and the rail's badge pop on it. */
var landed by mutableIntStateOf(0)
/** Dots in flight to the Downloads chip. */
val flights = mutableStateListOf<Flight>()
fun fly(from: Rect) {
if (Motion.scale == 0f || downloadsChip == null) { landed++; return }
flights += Flight(from, SystemClock.uptimeMillis())
}
/** The confirm or list stepping out of a control on the Stores page now, and whether it is open. */
var step by mutableStateOf<StepAsk?>(null)
private set
var stepOpen by mutableStateOf(false)
private set
fun ask(a: StepAsk) {
step?.onDismiss()
step = a
stepOpen = true
}
/** Drops whatever is stepped out or flooding, at once: the page it belonged to has gone. */
fun drop() {
step?.let { step = null; it.onDismiss() }
stepOpen = false
signIn = null
}
/** Folds the current one back into its control. */
fun fold() { stepOpen = false }
internal fun closed(a: StepAsk) {
if (step === a) step = null
a.onDismiss()
}
/** A store's sign-in flooding the page, or draining back out of it. */
var signIn by mutableStateOf<SignInFlood?>(null)
/** Per store, bumped to send its chip's dot one pulse ring (signed in, picked). */
val pulses = androidx.compose.runtime.mutableStateMapOf<Store, Int>()
fun pulse(store: Store) { pulses[store] = (pulses[store] ?: 0) + 1 }
/** Where each store's dot sits on its chip, for a sign-in to come home to. */
val dots = HashMap<Store, Rect>()
/** The card a game page is about to open from. */
private var card: CardMark? = null
private var cardAt = 0L
fun markCard(c: CardMark) {
card = c
cardAt = SystemClock.uptimeMillis()
}
/** The card game [key] was just opened from, once; a page opened another way shows without a flood. */
fun takeCard(key: String): CardMark? = card?.takeIf { it.key == key && SystemClock.uptimeMillis() - cardAt < 1_000 }.also { card = null }
}
/** A game card at [bounds] (root px) with corner [corner] (px) and its art, for the page it opens to flood out of. */
internal class CardMark(val key: String, val bounds: Rect, val corner: Float, val art: String?)
internal class Flight(val from: Rect, val id: Long)
/**
* A confirm or short list for [StepOut] on the Stores page, asked by a control that sits at [anchor]
* (root px). [content] gets a close that folds it; [onDismiss] runs once it has folded, however.
*/
internal class StepAsk(
val anchor: Rect,
val side: StepSide,
val accent: Color,
val pillCorner: androidx.compose.ui.unit.Dp? = null,
val items: Int = 4,
val onDismiss: () -> Unit = {},
val handle: @Composable () -> Unit,
val content: @Composable StepOutScope.() -> Unit,
)
internal class SignInFlood(val store: Store, val from: Rect, val start: Color, val color: Color) {
/** Covered and handed to the login page; waiting for the page to come back. */
var away by mutableStateOf(false)
/** Back from the login page: draining into [to]. */
var drainTo by mutableStateOf<Rect?>(null)
}
/** The dots flying to the Downloads chip, drawn over the page whose root offset is [origin]. */
@Composable
internal fun FlightLayer(origin: Offset) {
for (f in StoresMotion.flights.toList()) key(f.id) { FlightDot(f, origin) }
}
/**
* One install's dot: the button squashes into a 14dp dot (width first, a little bloop), which then
* flies on an arc to the Downloads chip, stretched along its path like the focus ring's drop.
*/
@Composable
private fun FlightDot(f: Flight, origin: Offset) {
val pal = LocalPalette.current
val t = remember { Animatable(0f) }
LaunchedEffect(Unit) {
t.animateTo(1f, Motion.tw(150, easing = FastOutSlowInEasing))
t.animateTo(2f, Motion.tw(300, easing = FastOutSlowInEasing))
StoresMotion.landed++
StoresMotion.flights.remove(f)
}
Canvas(Modifier.fillMaxSize()) {
val r = 7.dp.toPx()
val from = f.from.translate(-origin)
val chip = (StoresMotion.downloadsChip ?: return@Canvas).translate(-origin)
val a = from.center
// The count sits at the chip's right end.
val b = Offset(chip.right - 22.dp.toPx(), chip.center.y)
val v = t.value
if (v < 1f) {
// Squash: the width goes first, then the height, into the dot; a bloop at the end.
val w = lerp(from.width, 2 * r, (v * 1.4f).coerceAtMost(1f))
val h = lerp(from.height, 2 * r, ((v - 0.25f) / 0.75f).coerceIn(0f, 1f))
val k = 1f - 0.15f * sin(PI * v).toFloat()
drawRoundRect(pal.signal, Offset(a.x - w * k / 2, a.y - h * k / 2), Size(w * k, h * k), CornerRadius(minOf(w, h) * k / 2))
} else {
val p = v - 1f
val c = Offset((a.x + b.x) / 2, minOf(a.y, b.y) - 80.dp.toPx())
val q = 1f - p
val pos = Offset(q * q * a.x + 2 * q * p * c.x + p * p * b.x, q * q * a.y + 2 * q * p * c.y + p * p * b.y)
val d = Offset(2 * q * (c.x - a.x) + 2 * p * (b.x - c.x), 2 * q * (c.y - a.y) + 2 * p * (b.y - c.y))
val stretch = sin(PI * p).toFloat()
val angle = atan2(d.y, d.x) * 180f / PI.toFloat()
rotate(angle, pos) {
val w = 2 * r * (1f + 0.5f * stretch)
val h = 2 * r * (1f - 0.25f * stretch)
drawOval(pal.signal, Offset(pos.x - w / 2, pos.y - h / 2), Size(w, h))
}
}
}
}
/** Pops (1.3 to 1, with one ring) each time a download's dot lands; for the count on the chip and the rail. */
internal fun Modifier.landingPop(): Modifier = composed {
val pal = LocalPalette.current
val scale = remember { Animatable(1f) }
val ring = remember { Animatable(1f) }
val seen = remember { intArrayOf(StoresMotion.landed) }
LaunchedEffect(StoresMotion.landed) {
if (StoresMotion.landed == seen[0]) return@LaunchedEffect
seen[0] = StoresMotion.landed
coroutineScope {
launch { scale.snapTo(1.3f); scale.animateTo(1f, Motion.sp(0.45f, 500f)) }
launch { ring.snapTo(0f); ring.animateTo(1f, Motion.tw(400)) }
}
}
this.drawBehind {
if (ring.value < 1f) {
val rr = max(size.width, size.height) / 2f * lerp(0.4f, 1.6f, ring.value)
drawCircle(pal.signal.copy(alpha = 0.5f * (1f - ring.value)), rr, center, style = Stroke(1.5.dp.toPx()))
}
}.graphicsLayer { scaleX = scale.value; scaleY = scale.value }
}
/**
* A pressed button in [start] stretching out over this element in [color] (LaunchFlood's move:
* each edge on its own loose spring, the furthest first, blobby in flight). [from] is in this
* element's px. Calls [onCovered] once, when nothing but [color] shows; then holds.
*/
@Composable
internal fun ColorFlood(from: Rect, start: Color, color: Color, onCovered: () -> Unit) {
val edges = remember { List(4) { Animatable(0f) } }
val reached = remember { BooleanArray(4) }
var size by remember { mutableStateOf(Size.Zero) }
LaunchedEffect(size != Size.Zero) {
if (size == Size.Zero) return@LaunchedEffect
val travel = listOf(from.left, from.top, size.width - from.right, size.height - from.bottom).map { it.coerceAtLeast(0f) }
val far = travel.max().coerceAtLeast(1f)
coroutineScope {
edges.forEachIndexed { i, edge ->
val lead = travel[i] / far
launch {
delay(Motion.ms((120 * (1f - lead)).toInt()).toLong())
// Overshoots past the edge, off the element, so the wobble is felt in the pull.
edge.animateTo(1f, if (Motion.scale == 0f) Motion.sp() else spring(dampingRatio = 0.48f, stiffness = lerp(110f, 190f, lead))) {
if (value >= 1f) reached[i] = true
}
reached[i] = true
}
}
snapshotFlow { edges.indices.all { reached[it] || edges[it].value >= 1f } }.first { it }
onCovered()
}
}
Canvas(Modifier.fillMaxSize().onSizeChangedCompat { size = it }) {
val v = edges.mapIndexed { i, e -> if (reached[i]) 1f else e.value }
drawFloodShape(from, from.minDimension / 2f, v, lerp(start, color, (v.average().toFloat() * 2f).coerceIn(0f, 1f)))
}
}
/**
* [color] over the whole element drawing down into [to] (px, here), critically damped, the near
* edges first (PageFlood's way back), then fading out on it; [onDone] after.
*/
@Composable
internal fun ColorDrain(color: Color, to: Rect, toCorner: Float, onDone: () -> Unit) {
val edges = remember { List(4) { Animatable(1f) } }
val alpha = remember { Animatable(1f) }
var size by remember { mutableStateOf(Size.Zero) }
LaunchedEffect(size != Size.Zero) {
if (size == Size.Zero) return@LaunchedEffect
val travel = listOf(to.left, to.top, size.width - to.right, size.height - to.bottom).map { it.coerceAtLeast(0f) }
val far = travel.max().coerceAtLeast(1f)
coroutineScope {
edges.mapIndexed { i, edge ->
val lead = travel[i] / far
launch {
delay(Motion.ms((120 * (1f - lead)).toInt()).toLong())
edge.animateTo(0f, if (Motion.scale == 0f) Motion.sp() else spring(dampingRatio = 1f, stiffness = lerp(170f, 260f, lead)))
}
}.forEach { it.join() }
}
alpha.animateTo(0f, Motion.tw(160))
onDone()
}
Canvas(Modifier.fillMaxSize().onSizeChangedCompat { size = it }) {
drawFloodShape(to, toCorner, edges.map { it.value }, color.copy(alpha = color.alpha * alpha.value))
}
}
private fun Modifier.onSizeChangedCompat(onSize: (Size) -> Unit) =
onSizeChanged { onSize(Size(it.width.toFloat(), it.height.toFloat())) }
/** A rect from [r] with its edges [v] of the way to this scope's (left, top, right, bottom): blobby in flight. */
private fun DrawScope.drawFloodShape(r: Rect, restCorner: Float, v: List<Float>, color: Color) {
val left = lerp(r.left, 0f, v[0])
val top = lerp(r.top, 0f, v[1])
val right = lerp(r.right, size.width, v[2])
val bottom = lerp(r.bottom, size.height, v[3])
val w = (right - left).coerceAtLeast(0f)
val h = (bottom - top).coerceAtLeast(0f)
val mean = v.sumOf { it.coerceIn(0f, 1f).toDouble() }.toFloat() / 4f
val blob = sin(PI * mean).toFloat().coerceAtLeast(0f)
val corner = lerp(restCorner * (1f - mean), minOf(w, h) * 0.42f, blob)
drawRoundRect(color, Offset(left, top), Size(w, h), CornerRadius(corner))
}
/** Sends one pulse ring out of a dot each time [trigger] changes after the first composition. */
internal fun Modifier.pulseRing(trigger: Int, color: Color): Modifier = composed {
val ring = remember { Animatable(1f) }
val seen = remember { intArrayOf(trigger) }
LaunchedEffect(trigger) {
if (trigger == seen[0]) return@LaunchedEffect
seen[0] = trigger
if (Motion.scale == 0f) return@LaunchedEffect
ring.snapTo(0f)
ring.animateTo(1f, Motion.tw(600))
}
drawBehind {
if (ring.value < 1f) drawCircle(
color.copy(alpha = 0.6f * (1f - ring.value)), size.minDimension / 2f * lerp(0.4f, 1.6f, ring.value) * 1.4f, center,
style = Stroke(1.5.dp.toPx()),
)
}
}
/**
* [items] in a column where a row that comes enters with [enter] and a row that goes stays on to
* leave with [exit] (a Column has no item animations of its own). [content] gets the row and
* whether it came after the list was first shown.
*/
@Composable
internal fun <T> AnimatedRows(
items: List<T>,
key: (T) -> Any,
enter: (index: Int, later: Boolean) -> EnterTransition,
exit: (item: T, index: Int, count: Int) -> ExitTransition,
content: @Composable (item: T, later: Boolean) -> Unit,
) {
val order = remember { mutableListOf<Any>() }
val last = remember { mutableMapOf<Any, T>() }
val states = remember { mutableMapOf<Any, MutableTransitionState<Boolean>>() }
val later = remember { mutableMapOf<Any, Boolean>() }
val mounted = remember { booleanArrayOf(false) }
val now = items.associateBy(key)
// Keep a leaving row where it was among the ones that stay.
val merged = ArrayList<Any>()
var j = 0
for (k in now.keys) {
val pos = order.indexOf(k)
if (pos >= 0) {
while (j < pos) { val o = order[j]; if (o !in now && o !in merged) merged += o; j++ }
j = maxOf(j, pos + 1)
}
merged += k
}
while (j < order.size) { val o = order[j]; if (o !in now && o !in merged) merged += o; j++ }
now.forEach { (k, v) -> last[k] = v }
val shown = merged.filter { k ->
val st = states.getOrPut(k) { MutableTransitionState(false).also { later[k] = mounted[0] } }
st.targetState = k in now
val gone = k !in now && st.isIdle && !st.currentState
if (gone) { states.remove(k); last.remove(k); later.remove(k) }
!gone
}
order.clear(); order.addAll(shown)
SideEffect { mounted[0] = true }
shown.forEachIndexed { i, k ->
val item = last[k] ?: return@forEachIndexed
val st = states[k] ?: return@forEachIndexed
key(k) {
AnimatedVisibility(st, enter = enter(i, later[k] == true), exit = exit(item, i, shown.size)) { content(item, later[k] == true) }
}
}
}
File diff suppressed because it is too large. Load diff
@@ -358,8 +358,11 @@ internal fun AdbTextField(
onFocusChange: (Boolean) -> Unit = {},
onNext: (() -> Unit)? = null,
onDone: (() -> Unit)? = null,
/** Takes focus (and the keyboard) once, as soon as it is shown: a field that opened on request. */
focusOnShow: Boolean = false,
) {
val context = LocalContext.current
val focusAsked = remember { booleanArrayOf(false) }
val palette = LocalPalette.current
val onValueChangeLatest = rememberUpdatedState(onValueChange)
val onNextLatest = rememberUpdatedState(onNext)
@@ -434,6 +437,14 @@ internal fun AdbTextField(
}
},
update = { editText ->
if (focusOnShow && !focusAsked[0]) {
focusAsked[0] = true
editText.post {
editText.requestFocus()
(editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
?.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
}
}
editText.setTextColor(colors.onBackground.toArgb())
editText.setHintTextColor(colors.onSurfaceVariant.toArgb())
editText.hint = placeholder
+5
View File
@@ -1979,9 +1979,14 @@
<string name="stores_tab_count">%1$s (%2$d)</string>
<string name="stores_signin">Sign in</string>
<string name="stores_signout_named">%1$s · sign out</string>
<string name="stores_signout_title">Sign out of %1$s?</string>
<string name="stores_signout_note">Installed games stay. The library is fetched again when you sign back in.</string>
<string name="stores_signout_stay">Stay signed in</string>
<string name="stores_signout_go">Sign out</string>
<string name="stores_search_catalog">Search the %1$s catalog…</string>
<string name="stores_search_installed">Search installed games…</string>
<string name="stores_search_library">Search your library…</string>
<string name="stores_search_open">Search</string>
<string name="stores_installed_empty">Nothing installed</string>
<string name="stores_library_loading">Loading</string>
<string name="stores_nothing_matches">No games</string>
+1 -1
View File
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<paths>
<cache-path name="shared_logs" path="shared-logs/" />
<cache-path name="shared_logs" path="share/" />
</paths>
@@ -87,4 +87,65 @@ class LogRedactorTest {
assertEquals(once, LogRedactor.redact(once))
}
}
// The Steam UI's own login line (webhelper_js.txt), as the privacy scan found it.
@Test fun loginStateLineLosesAnEmailAccount() {
val line = "[2026-10-07 21:14:03] SteamUI: INFO: Login: OnLoginStateChange someone.masked@example.com 2 1 0 0"
val out = LogRedactor.redact(line)
assertFalse(out.contains("someone.masked"))
assertFalse(out.contains("example.com"))
assertEquals("[2026-10-07 21:14:03] SteamUI: INFO: Login: OnLoginStateChange <redacted:account> 2 1 0 0", out)
assertEquals(out, LogRedactor.redactForShare(line))
}
@Test fun loginStateLineLosesAPlainAccountName() {
val line = "[2026-10-07 21:14:03] SteamUI: INFO: Login: OnLoginStateChange maskeduser42 2 1 0 0"
val out = LogRedactor.redact(line)
assertFalse(out.contains("maskeduser42"))
assertEquals("[2026-10-07 21:14:03] SteamUI: INFO: Login: OnLoginStateChange <redacted:account> 2 1 0 0", out)
assertEquals(out, LogRedactor.redactForShare(line))
}
@Test fun loginStateWithoutAnAccountIsKept() {
val line = "SteamUI: INFO: Login: OnLoginStateChange 0 1 0 0"
assertEquals(line, LogRedactor.redact(line))
}
@Test fun accountNameFieldsAreRedacted() {
val lines = listOf(
"\t\"AccountName\"\t\t\"maskeduser42\"",
"account_name=maskeduser42 remember=1",
"{\"login\":\"maskeduser42\",\"persist\":1}",
"auth: login=maskeduser42&remember=1",
"accountName: maskeduser42",
"{\"username\": \"masked user 42\"}",
)
for (line in lines) {
val out = LogRedactor.redactForShare(line)
assertFalse(out, out.contains("maskeduser42") || out.contains("masked user"))
assertTrue(out, out.contains("<redacted:account>"))
assertEquals(out, LogRedactor.redactForShare(out))
}
}
@Test fun loginAsAWordIsNotAField() {
for (line in listOf("SteamUI: INFO: Login: OnLoginStateChange 0 1 0 0", "login refresh pending", "Login: state 5")) {
assertEquals(line, LogRedactor.redact(line))
}
}
@Test fun privateAddressesLeaveTheZipPublicOnesStay() {
assertEquals("I/LinuxNetworkLink: resolver: <lan-address> <lan-address> 8.8.8.8",
LogRedactor.redactForShare("I/LinuxNetworkLink: resolver: 192.168.1.1 10.0.0.138 8.8.8.8"))
assertEquals("gateway <lan-address>:53 link <lan-address> lan <lan-address>",
LogRedactor.redactForShare("gateway 172.16.4.20:53 link 169.254.10.2 lan 172.31.255.254"))
for (line in listOf(
"connecting to CM 162.254.193.47:27017",
"public 172.32.0.1 and 11.0.0.1 and 193.168.1.1",
"Windows 10.0.19041.1 build 10.0.19045",
"Proton 10.0-3, driver 25.1.0.4",
)) assertEquals(line, LogRedactor.redactForShare(line))
val once = LogRedactor.redactForShare("resolver: 192.168.0.1")
assertEquals(once, LogRedactor.redactForShare(once))
}
}
@@ -0,0 +1,39 @@
package com.droiddeck.launcher.core
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Test
class SecretScrubTest {
private fun share(line: String) = SecretScrub.scrub(line, SecretScrub.Urls.KEEP_PATH, "<redacted:token>")
@Test fun windowsExceptionCodesAreKept() {
for (line in listOf(
"0024:trace:seh:dispatch_exception code=406d1388 flags=0 addr=00006FFFFFC0A6E8",
"0024:warn:seh:dispatch_exception code=c0000005 flags=0 addr=0000000140012345",
"0030:trace:seh:handle_syscall_fault code=80000003 flags=0",
"exception code=0xC0000005 at 0x140012345",
// An exception code stays one even on a line that also carries OAuth keys.
"client_id=abc code=c0000005",
)) assertEquals(line, share(line))
}
@Test fun anOAuthCodeIsBlanked() {
assertEquals("redirect client_id=34a02cf8 redirect_uri=x state=1 code=<redacted:token>",
share("redirect client_id=34a02cf8 redirect_uri=x state=1 code=AUTHCODE123"))
assertEquals("GET /on_login_success?code=<redacted:token>&scope=",
share("GET /on_login_success?code=AUTHCODE123&scope="))
assertEquals("exchange_code=<redacted:token>", share("exchange_code=0123456789abcdef"))
assertEquals("authorizationCode=<redacted:token>", share("authorizationCode=ABCD1234XYZ"))
}
@Test fun aCodeWithoutOAuthAroundItIsKept() {
for (line in listOf("exit code=1337", "status code=ERR_TIMEOUT", "code 403")) assertEquals(line, share(line))
}
@Test fun scrubbingTwiceChangesNothing() {
val once = share("client_id=1 code=AUTHCODE123 ?code=XYZW1234567")
assertFalse(once.contains("AUTHCODE123"))
assertEquals(once, share(once))
}
}
@@ -33,12 +33,13 @@ class SessionLogShareTest {
"rules $rules\n" + files.joinToString("") { val f = File(folder, it); "${f.length()}\t${f.lastModified()}\t$it\n" })
}
@Test fun aRecordedUnchangedFileGoesInAsItIs() {
@Test fun aRecordedUnchangedFileIsScrubbedAgainOnTheWayIntoTheZip() {
val folder = tmp.newFolder("2026-10-06-01-steam")
// Stands in for a file the ending scrubbed; the share must not pass it through again.
// A file the ending recorded as scrubbed still gets the share's final pass: the record
// may predate a rule, and a zip is the one way a log leaves the device.
File(folder, "session.log").writeText("$secret\n")
record(folder, "session.log")
assertTrue(zip(folder).getValue("session.log").contains(leaked))
assertFalse(zip(folder).getValue("session.log").contains(leaked))
}
@Test fun anythingTheRecordDoesNotVouchForIsScrubbed() {
@@ -0,0 +1,107 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.util.zip.ZipFile
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** A shared zip is scrubbed on the way in, whatever the files on disk still hold. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class SessionLogShareZipTest {
private val app get() = RuntimeEnvironment.getApplication()
@Test fun everyTextFileInTheZipIsScrubbedAndTheStoresAndToolsLogsComeAlong() {
val logs = LinuxRuntime.logDir(app)
val session = File(logs, "2026-10-08-01-steam").apply { mkdirs() }
// Written raw, as a file from before a rule existed would be.
File(session, "session.log").writeText(
"fetch https://gog-cdn-fastly.gog.com/token=nva=1791500000~dirs=/x~token=0a1b2c3d4e5f/content-system/v2/store/1/ab/cd/f\n" +
"fetch https://epicgames-download1.akamaized.net/Builds/Org/a/ChunksV4/12/ABCD.chunk?__token__=exp=1~hmac=deadbeefcafe\n" +
"login refresh_token=abcdef123456 user someone@example.com code=AUTHCODE123\n" +
"Authorization: Bearer abc.def.ghi\n" +
"kept: EResult 5, app 1086940, steamapps/common/Game\n"
)
File(logs, "stores").apply { mkdirs() }.resolve("stores-2026-10-08.log").writeText("epic: f_token=zzzzzzzz12 window 32\n")
File(logs, SessionPaths.TOOLS_DIR).apply { mkdirs() }.resolve("flatpak-install.log").writeText("== install\nCookie: steamLoginSecure=76561198000000000%7C%7Ceyabc\n")
val zip = SessionLogShare.zipFolder(app, session)!!
assertTrue(zip.path.startsWith(File(app.cacheDir, "share").path))
val text = ZipFile(zip).use { z -> z.entries().toList().associate { e -> e.name to z.getInputStream(e).bufferedReader().readText() } }
assertTrue(text.keys.containsAll(listOf("2026-10-08-01-steam/session.log", "stores/stores-2026-10-08.log", "tools/flatpak-install.log")))
val all = text.values.joinToString("\n")
for (secret in listOf("0a1b2c3d4e5f", "deadbeefcafe", "abcdef123456", "someone@example.com", "AUTHCODE123", "abc.def.ghi", "zzzzzzzz12", "eyabc")) {
assertFalse("$secret survived", all.contains(secret))
}
// What makes a log worth reading stays.
assertTrue(all.contains("kept: EResult 5, app 1086940, steamapps/common/Game"))
assertTrue(all.contains("https://gog-cdn-fastly.gog.com/"))
SessionLogShare.clear(app)
assertFalse(zip.exists())
}
@Test fun theSharePassChangesNothingInACleanLine() {
val line = "dxvk: Device 0x5 (Adreno 750) https://github.com/doitsujin/dxvk/releases code 403"
assertEquals(line, com.droiddeck.launcher.core.LogRedactor.redactForShare(line))
}
// Folders an earlier build scrubbed and marked under older rules, their copied Steam UI log
// still naming the account: one app start (the move out of Download/, then the pass over
// older folders) leaves every one scrubbed on disk under the current rules.
private fun olderFolder(parent: File, name: String, marker: String = ".scrubbed-2"): File {
val dir = File(parent, name).apply { mkdirs() }
File(dir, marker).writeText("scrubbed earlier\n")
File(dir, SessionArtifacts.SCRUBBED_TREE_MARKER).writeText("rules 2\n")
File(dir, "steam").apply { mkdirs() }.resolve("webhelper_js.txt").writeText(
"[2026-10-01 20:00:00] SteamUI: INFO: Login: OnLoginStateChange someone.masked@example.com 2 1 0 0\n" +
"[2026-10-01 20:00:01] SteamUI: INFO: Login: OnLoginStateChange maskeduser42 2 1 0 0\n" +
"[2026-10-01 20:00:02] SteamUI: INFO: Login: OnLoginStateChange 0 1 0 0\n" +
"0024:trace:seh:dispatch_exception code=c0000005 flags=0\n"
)
return dir
}
private fun assertScrubbed(dir: File) {
val text = File(dir, "steam/webhelper_js.txt").readText()
for (secret in listOf("someone.masked", "example.com", "maskeduser42")) assertFalse("$secret survived in $dir", text.contains(secret))
assertTrue(text.contains("Login: OnLoginStateChange <redacted:account> 2 1 0 0"))
assertTrue(text.contains("Login: OnLoginStateChange 0 1 0 0"))
assertTrue(text.contains("code=c0000005"))
val markers = dir.list()!!.filter { it.startsWith(".scrubbed-") && it != SessionArtifacts.SCRUBBED_TREE_MARKER }
assertEquals("$dir", listOf(".scrubbed-r${com.droiddeck.launcher.core.LogRedactor.RULES_VERSION}"), markers)
assertTrue(File(dir, SessionArtifacts.SCRUBBED_TREE_MARKER).readText()
.startsWith("rules ${com.droiddeck.launcher.core.LogRedactor.RULES_VERSION}\n"))
}
@Test fun aFolderMarkedUnderOlderRulesIsScrubbedAgainAtStart() {
val dir = olderFolder(LinuxRuntime.logDir(app), "2026-10-01-01-steam")
SessionArtifacts.scrubOlder(app)
assertScrubbed(dir)
}
@Test fun everyMigratedFolderIsScrubbedUnderTheCurrentRulesInOneStart() {
val legacy = LinuxRuntime.legacyLogDir().apply { mkdirs() }
val names = (1..9).map { "2026-10-0${it}-01-steam" }
names.forEachIndexed { i, name ->
// Old markers of every kind an earlier build left, one even claiming the current rules.
olderFolder(legacy, name, marker = listOf(".scrubbed-2", ".scrubbed-1", ".scrubbed-r${com.droiddeck.launcher.core.LogRedactor.RULES_VERSION}")[i % 3])
}
File(legacy, "Saves").apply { mkdirs() }.resolve("keep.txt").writeText("save\n")
// What MainActivity runs at start.
LogMigration.run(app)
SessionArtifacts.scrubOlder(app)
val logs = LinuxRuntime.logDir(app)
for (name in names) assertScrubbed(File(logs, name))
assertEquals(listOf("Saves"), legacy.list()!!.toList())
}
}
@@ -0,0 +1,173 @@
package com.droiddeck.launcher.stores
import org.json.JSONObject
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
import java.security.SecureRandom
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
/** The stores' sign-in files sealed at rest; a plain key stands in for the AndroidKeyStore. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class StoreAccountsCipherTest {
private val app get() = RuntimeEnvironment.getApplication()
private fun newKey(): SecretKey = SecretKeySpec(ByteArray(32).also { SecureRandom().nextBytes(it) }, "AES")
private val key = newKey()
private val fake = CredentialCipher.KeyProvider { key }
private val broken = CredentialCipher.KeyProvider { throw java.security.KeyStoreException("no keystore") }
private val creds = JSONObject().put("access_token", "AT-secret-123456").put("refresh_token", "RT-secret-654321")
.put("account_id", "acct-1").put("display_name", "Someone").put("expires_at", 1_900_000_000_000L)
private fun file(store: Store) = StoreAccounts.credentialsFile(app, store)
@Before fun setUp() { StoreAccounts.keys = fake; StoreAccounts.keystoreFailed = false }
@After fun tearDown() {
StoreAccounts.keys = CredentialCipher.Keystore; StoreAccounts.keystoreFailed = false
for (store in Store.entries) StoreAccounts.clear(app, store)
}
@Test fun envelopeRoundTrips() {
val envelope = CredentialCipher.seal(creds.toString(), fake)
assertEquals(1, envelope.getInt("v"))
assertEquals("AES/GCM", envelope.getString("alg"))
assertFalse(envelope.toString().contains("secret"))
assertEquals(creds.toString(), CredentialCipher.open(envelope, fake))
// A fresh IV every time.
assertFalse(envelope.getString("iv") == CredentialCipher.seal(creds.toString(), fake).getString("iv"))
}
@Test fun writtenCredentialsAreSealedOnDisk() {
StoreAccounts.write(app, Store.EPIC, creds)
val text = file(Store.EPIC).readText()
assertFalse(text.contains("AT-secret") || text.contains("RT-secret") || text.contains("Someone"))
assertTrue(CredentialCipher.isEnvelope(JSONObject(text)))
assertEquals(creds.toString(), StoreAccounts.read(app, Store.EPIC).toString())
assertEquals("Someone", StoreAccounts.signedInAs(app, Store.EPIC))
assertFalse(File(file(Store.EPIC).path + ".tmp").exists())
}
@Test fun aPlainFileFromAnEarlierBuildIsSealedAndStaysSignedIn() {
for (store in Store.entries) file(store).writeText(creds.toString())
File(file(Store.GOG).path + ".tmp").writeText(creds.toString())
StoreAccounts.encryptAll(app)
for (store in Store.entries) {
val text = file(store).readText()
assertTrue(store.id, CredentialCipher.isEnvelope(JSONObject(text)))
assertFalse(store.id, text.contains("secret"))
assertEquals(store.id, creds.toString(), StoreAccounts.read(app, store).toString())
}
assertFalse(File(file(Store.GOG).path + ".tmp").exists())
}
@Test fun aTamperedFileReadsAsSignedOutAndIsDeleted() {
StoreAccounts.write(app, Store.GOG, creds)
val envelope = JSONObject(file(Store.GOG).readText())
val ct = android.util.Base64.decode(envelope.getString("ct"), android.util.Base64.NO_WRAP)
ct[0] = (ct[0].toInt() xor 1).toByte()
file(Store.GOG).writeText(envelope.put("ct", android.util.Base64.encodeToString(ct, android.util.Base64.NO_WRAP)).toString())
assertNull(StoreAccounts.read(app, Store.GOG))
assertNull(StoreAccounts.signedInAs(app, Store.GOG))
assertFalse(file(Store.GOG).exists())
}
@Test fun aFileSealedUnderALostKeyReadsAsSignedOutAndIsDeleted() {
StoreAccounts.write(app, Store.AMAZON, creds)
// Data cleared, or a backup restored on another device: the Keystore key is a new one.
val other = newKey()
StoreAccounts.keys = CredentialCipher.KeyProvider { other }
assertNull(StoreAccounts.read(app, Store.AMAZON))
assertFalse(file(Store.AMAZON).exists())
}
@Test fun garbageReadsAsSignedOut() {
file(Store.EPIC).writeText("{\"v\":1,\"alg\":\"AES/GCM\",\"iv\":\"!!\",\"ct\":\"??\"}")
assertNull(StoreAccounts.read(app, Store.EPIC))
file(Store.EPIC).writeText("not json")
assertNull(StoreAccounts.read(app, Store.EPIC))
}
@Test fun withoutAKeystoreCredentialsStayPlainAndTheNextStartSealsThem() {
StoreAccounts.keys = broken
StoreAccounts.write(app, Store.EPIC, creds)
assertEquals(creds.toString(), file(Store.EPIC).readText())
assertEquals(creds.toString(), StoreAccounts.read(app, Store.EPIC).toString())
assertTrue(StoreAccounts.keystoreFailed)
// The next start, on a Keystore that works.
StoreAccounts.keys = fake
StoreAccounts.keystoreFailed = false
StoreAccounts.encryptAll(app)
assertTrue(CredentialCipher.isEnvelope(JSONObject(file(Store.EPIC).readText())))
assertEquals(creds.toString(), StoreAccounts.read(app, Store.EPIC).toString())
}
@Test fun signOutRemovesTheFile() {
StoreAccounts.write(app, Store.GOG, creds)
StoreAccounts.clear(app, Store.GOG)
assertFalse(file(Store.GOG).exists())
assertNull(StoreAccounts.read(app, Store.GOG))
}
/** A Keystore whose key is there but which fails to hand it over [failures] times first. */
private class Flaky(private val key: SecretKey, var failures: Int, private val error: () -> Exception) : CredentialCipher.KeyProvider {
override fun key(): SecretKey = key
override fun existing(): SecretKey { if (failures > 0) { failures--; throw error() }; return key }
}
@Test fun aTransientKeystoreFailureKeepsTheFileAndALaterReadSucceeds() {
StoreAccounts.write(app, Store.EPIC, creds)
val sealed = file(Store.EPIC).readText()
for (error in listOf<() -> Exception>(
{ java.security.ProviderException("busy") },
{ java.security.KeyStoreException("keystore down") },
{ java.security.InvalidKeyException("not now") },
{ java.io.IOException("read") },
)) {
StoreAccounts.keys = Flaky(key, 1, error)
assertNull(StoreAccounts.read(app, Store.EPIC))
assertTrue(StoreAccounts.isUnavailable(Store.EPIC))
assertEquals(sealed, file(Store.EPIC).readText())
// Still signed in for the page: no sign-in card, and an action says why it failed.
assertEquals("Epic sign-in could not be read: try again.", StoresState.notSignedInLine(Store.EPIC))
// The next access, once the Keystore answers.
assertEquals(creds.toString(), StoreAccounts.read(app, Store.EPIC).toString())
assertFalse(StoreAccounts.isUnavailable(Store.EPIC))
assertEquals("Someone", StoreAccounts.signedInAs(app, Store.EPIC))
assertEquals("Epic session expired: sign in again.", StoresState.notSignedInLine(Store.EPIC))
}
}
@Test fun signedInAsKeepsTheStoreWhileItsSignInIsUnavailable() {
StoreAccounts.write(app, Store.GOG, creds)
StoreAccounts.keys = Flaky(key, 5) { java.security.ProviderException("busy") }
assertEquals("GOG", StoreAccounts.signedInAs(app, Store.GOG))
assertTrue(file(Store.GOG).exists())
}
@Test fun aKeyGoneFromTheKeystoreReadsAsSignedOutAndIsDeleted() {
StoreAccounts.write(app, Store.AMAZON, creds)
StoreAccounts.keys = object : CredentialCipher.KeyProvider {
override fun key(): SecretKey = newKey()
override fun existing(): SecretKey = throw CredentialCipher.KeyMissing()
}
assertNull(StoreAccounts.read(app, Store.AMAZON))
assertFalse(StoreAccounts.isUnavailable(Store.AMAZON))
assertFalse(file(Store.AMAZON).exists())
}
}
@@ -0,0 +1,54 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Path
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class StepOutTest {
private val pill = Rect(400f, 100f, 500f, 140f)
@Test fun leftOutlineRunsFromTheBoxLeftToThePillRight() {
val path = Path()
stepPath(path, pill, left = 240f, bottom = 300f, pullTop = 146f, box = 16f, fillet = 10f)
val b = path.getBounds()
assertEquals(240f, b.left, 0.5f)
assertEquals(500f, b.right, 0.5f)
assertEquals(100f, b.top, 0.5f)
assertEquals(300f, b.bottom, 0.5f)
}
@Test fun rightOutlineMirrorsItAboutThePill() {
val path = Path()
stepPathRight(path, pill, right = 660f, bottom = 300f, pullTop = 146f, box = 16f, fillet = 10f)
val b = path.getBounds()
assertEquals(400f, b.left, 0.5f)
assertEquals(660f, b.right, 0.5f)
assertEquals(100f, b.top, 0.5f)
assertEquals(300f, b.bottom, 0.5f)
}
@Test fun aClosedOutlineIsJustThePill() {
val path = Path()
stepPathRight(path, pill, right = pill.right, bottom = pill.bottom, pullTop = pill.bottom + 6f, box = 16f, fillet = 10f, pillCorner = 12f)
val b = path.getBounds()
assertEquals(pill.left, b.left, 0.5f)
assertEquals(pill.right, b.right, 0.5f)
assertEquals(pill.bottom, b.bottom, 0.5f)
}
@Test fun aCardMarkIsTakenOnceAndOnlyForItsGame() {
StoresMotion.markCard(CardMark("gog:1", pill, 10f, null))
assertNull(StoresMotion.takeCard("gog:2"))
StoresMotion.markCard(CardMark("gog:1", pill, 10f, null))
assertNotNull(StoresMotion.takeCard("gog:1"))
assertNull(StoresMotion.takeCard("gog:1"))
}
}
@@ -4,15 +4,15 @@ import com.droiddeck.launcher.stores.Store
import org.junit.Assert.assertEquals
import org.junit.Test
/** Amazon has no catalog of its own: Installed and Library only, and Store falls back to Library. */
/** A store's modes are Store, Library and Installed; Amazon has no catalog of its own, so no Store. */
class StoreTabsTest {
@Test fun storeAndLibraryAmazonLibraryOnly() {
assertEquals(listOf("store", "library"), tabsFor(Store.GOG))
assertEquals(listOf("library"), tabsFor(Store.AMAZON))
@Test fun storeLibraryInstalledAmazonWithoutStore() {
assertEquals(listOf("store", "library", "installed"), tabsFor(Store.GOG))
assertEquals(listOf("library", "installed"), tabsFor(Store.AMAZON))
assertEquals("library", tabFor(Store.AMAZON, "store"))
// An old saved Installed or All tab opens Library.
// An old saved All tab opens Library; Installed is a mode again.
assertEquals("library", tabFor(Store.GOG, "all"))
assertEquals("library", tabFor(Store.EPIC, "installed"))
assertEquals("installed", tabFor(Store.EPIC, "installed"))
assertEquals("store", tabFor(Store.GOG, "store"))
}
}
+1 -1
View File
@@ -22,7 +22,7 @@ The script then unpacks them without hooks and checks what the binaries link. Li
the Desktop package normally brings (PyGObject, json-glib, fuse3 and others) are fetched too,
but only when their files are missing. Flathub is added as a per-user remote from a copy of
its `.flatpakrepo` carried in the script, so that step needs no network. Every store command
writes its output to `Download/DroidDeck/flatpak-<verb>.log`, next to the session logs. The
writes its output to `files/logs/tools/flatpak-<verb>.log`, next to the session logs. The
setup script also puts Flatpak's own error text in the failure message the app shows.
## bubblewrap without namespaces
+34 -2
View File
@@ -189,5 +189,37 @@ Store log lines (the engines' included) go through `StoresState.logLine`, which
(`StoreLogFiles`: one file a day, seven days kept, ~2 MB each before it rolls to `.1`). Nothing
shows them in the app; the session's Share logs zip carries them under `stores/`.
Credentials live in `filesDir/stores/<store>/credentials.json` only (`StoreAccounts`); store URLs
are logged through `StoreLog.redactUrl`, which drops the query string where the signed tokens live.
Store URLs are logged through `StoreLog.redactUrl`, which drops the query string where the signed
tokens live.
## Security
- **Sign-ins:** `filesDir/stores/<store>/credentials.json` only, read and written through
`StoreAccounts` alone (`GogAuth`, `EpicCredentialStore`, `AmazonCredentialStore`, cloud saves
all call it). The file is an envelope `{"v":1,"alg":"AES/GCM","iv":...,"ct":...}` (base64):
AES-256-GCM (`CredentialCipher`) under a key generated in the AndroidKeyStore (alias
`droiddeck-store-credentials`; encrypt/decrypt, GCM, no padding, not exportable, no user
authentication so background downloads and launch-time exchange codes work with the screen off;
StrongBox where present, else the TEE). Written through a temp file and a rename, mode 600.
- **Earlier plain files:** sealed at app start (`StoreAccounts.encryptAll`, and on any read),
verified by opening the result, the plain file replaced; the log says
`stores: credentials encrypted <store>`. A plain `.tmp` left by an older build is deleted.
- **No Keystore** (some ROMs): the file stays plain, the log says
`stores: keystore unavailable, credentials stay plain (<exception class>)` once, and the next
start tries again.
- **A file that can never open** - it does not authenticate (`AEADBadTagException`: tampered, or
another key after data was cleared or a backup restored on another device), the key is
permanently invalidated or gone from the Keystore, or it is not an envelope: deleted, and the
store reads as signed out, so its sign-in card shows.
- **A failure that may pass** (`KeyStoreException`, `ProviderException`, any other
`InvalidKeyException`, an I/O error, StrongBox busy): the file is kept, the store stays signed in
(no sign-in card) and is marked unavailable (`StoreAccounts.isUnavailable`), a store action shows
`<Store> sign-in could not be read: try again.`, the log says
`stores: credentials unreadable this start (<exception class>)` once, and the next access tries
again.
- **The Linux session:** the app's files directory is bound into every session, so the guest can
see `credentials.json` - as the envelope only; the key never leaves the Keystore. Nothing in the
guest reads the files: `droiddeck-store-launch` asks the app over `<session>/stores/req|resp`
for an Epic exchange code, which the app writes beside the game's launcher; the launcher reads
it into a variable and deletes it before the game starts (single use, expires in minutes).
Steam's own client files are outside this.
+74
View File
@@ -7,6 +7,80 @@ the timeline, then lessons and backlog. Companion to the README (what the app *d
---
## 2026-10-09 - `feat/store-credentials-keystore`: store sign-ins sealed with the Android Keystore
- **What:** `filesDir/stores/<store>/credentials.json` (GOG, Epic, Amazon: tokens, ids, names,
expiry) is now an AES-256-GCM envelope (`{"v":1,"alg":"AES/GCM","iv","ct"}`) under a
non-exportable AndroidKeyStore key (StrongBox if present, else TEE; no user authentication).
`StoreAccounts` is the one layer; `CredentialCipher` holds the envelope and the key.
- **Upgrade:** a plain file is sealed at the first start (verified, then replaced); users stay
signed in. Log: `stores: credentials encrypted <store>`.
- **Fallbacks:** no Keystore - stays plain, logged once, retried next start. A file that can never
open (bad tag, key invalidated or missing, not an envelope) - deleted, signed out (sign-in card).
Any other Keystore or I/O failure - file kept, store stays signed in but unavailable (actions show
`<Store> sign-in could not be read: try again.`), logged once, retried on the next access. Never
a crash.
- **Session:** the guest sees the envelope only; it never read the files (the Epic code comes over
the request channel, written beside the launcher and deleted by it).
- **Tests:** `StoreAccountsCipherTest` (round trip, sealed on disk, migration of all three stores,
tampered file, lost key, key missing, garbage, no-Keystore fallback then sealed next start,
transient Keystore / I/O failures keep the file and a later read succeeds, sign-out). Not yet
on a device.
## 2026-10-08 - `feat/private-logs`: every log in app-private storage, shared as one scrubbed zip
- **Where logs live:** `files/logs/` (`LinuxRuntime.logDir`), nothing under `Download/DroidDeck`
any more. Session folders (`<day>-NN-<what>/`), `tools/` (GuestCommand, Flatpak, Windows
component installers) and `stores/` (the stores' engine log, one file a day) all sit there. The
files directory is bound into every session at the same path, so the session script, gamescope
and the guest tools write there as before. Thirty sessions kept; the Logs switch off still means
a cache folder deleted at session end. Game save backups stay public in `Download/DroidDeck/Saves`.
- **Moving the old ones:** on the first start of this build, session folders, `tools/` and loose
`*.log` files move from `Download/DroidDeck/` into `files/logs/` (rename, else copy and delete;
an item that fails stays). A marker records the pass; `Saves/` and anything else there is never
touched, and the app does not read `Download/DroidDeck/` again.
- **Share logs:** one zip in `cache/share/`, made on demand: the newest session folder (or the one
the session screen shares), the last seven days of `stores/` and `tools/`. Every text file goes
through `LogRedactor.redactForShare` on the way in - the existing rules (Steam tokens, JWTs,
SteamIDs, account names, emails, own addresses, MACs, serials) plus URLs without query, fragment
or userinfo and with token-bearing path segments blanked (GOG secure links), `__token__`,
`f_token`, `hdnts`, OAuth `code=`, and Authorization / Cookie headers - so a file written before a
rule existed is clean in the zip. The zip is deleted at the next share or app start.
`SessionLogShareTest` covers it. Nothing was relaxed: the per-session scrub, `scrubOlder` and
every existing rule stay as they were.
- **File manager:** the Session logs shortcut opens `files/logs` (the app reads its own storage).
- **On main after Stores (#476) and the KDE Plasma desktop (#473):** the stores' log is already
`files/logs/stores/stores-<date>.log` and the zip carries its last seven days under `stores/`. One
set of rules scrubs both the stores' log and the zip (`SecretScrub`): `StoreLog.redactLine` keeps
URLs to their host and first plain segment, the zip pass keeps paths with token segments blanked,
both blank token values and Authorization / Cookie headers; the two test suites pass on it. The
Plasma desktop writes nothing outside the session folder (its output is the session's
`desktop.log`), so there was nothing new to move.
- **Privacy scan fixes:** the Steam login account (an email, 374 times) was still in older
folders' copied `steam/webhelper_js.txt` (`SteamUI: INFO: Login: OnLoginStateChange <account>`):
those folders carried a scrub marker from before the account rules, and the marker never
expired. The marker is now named after the redactor's rules version (`.scrubbed-r3`), so every
folder scrubbed under older rules goes through again at app start, steam/ and every subfolder
included; folders moved out of `Download/DroidDeck` lose every old marker
(`SessionArtifacts.unmarkMoved`), so the same pass takes them whatever those markers said. New rules: `OnLoginStateChange <anything>`, and
`AccountName` / `account_name` / `username` / `login` fields (`login` only as `login=`, a quoted
key or a VDF pair, so the "Login:" label stays). The `code=` rule no longer touches Proton's
exception codes (`code=c0000005`, `406d1388`, `80000003`): a bare `code=` is blanked only right
after `?`/`&` or on a line with OAuth keys (`client_id`, `redirect_uri`, `state`, tokens), and
never when it is 8 hex digits; exchange / authorization codes are always blanked. Tests:
`LogRedactorTest` (the login line with an email and with a plain name), `SecretScrubTest`,
`SessionLogShareZipTest` (older and moved folders scrubbed on disk).
- **Device check (31 migrated folders):** only 4 carried `.scrubbed-r3` a minute in. Nothing was
skipped - the pass was still running: one folder holds ~30 MB of Steam logs, ~30 s through the
redactor, one folder after another (about 15 minutes for 31). The start pass now scrubs a few
folders at a time (half the cores, at most 4, background priority), old markers go whether or
not a folder's pass succeeds, a folder the process does not finish is taken up at the next start,
and it logs one line: `logs: scrubbed N folders under r3`. Test: nine migrated folders carrying
`.scrubbed-2`, `.scrubbed-1` or a stale `.scrubbed-r3` all end up scrubbed under r3 after one
migration + start pass.
- **LAN addresses in the zip:** private IPv4 addresses (10/8, 172.16/12, 192.168/16, 169.254/16;
e.g. the router in `LinuxNetworkLink: resolver: ...`) become `<lan-address>` in the zip pass;
public server addresses and dotted version numbers stay (`LogRedactorTest`).
## 2026-10-08 - `feat/stores`: GOG, Epic Games and Amazon Games in the launcher (in progress)
A new **Stores** section - the three storefronts' libraries and public catalogs, one download