diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 6336fb1325..8fd115b62e 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -180,6 +180,17 @@
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
android:theme="@style/AppTheme" />
+
+
+
+
+
diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gfn/GfnActivity.kt b/app/src/main/java/com/droiddeck/launcher/stores/gfn/GfnActivity.kt
new file mode 100644
index 0000000000..fd1c09f95f
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/stores/gfn/GfnActivity.kt
@@ -0,0 +1,251 @@
+package com.droiddeck.launcher.stores.gfn
+
+import android.content.Intent
+import android.net.Uri
+import android.os.Bundle
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.setContent
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.grid.GridCells
+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
+import androidx.compose.foundation.lazy.grid.items
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Button
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.OutlinedTextField
+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.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import coil.compose.AsyncImage
+import com.droiddeck.launcher.ui.DroidDeckTheme
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import org.json.JSONObject
+
+/** GeForce NOW: sign in with an NVIDIA account, browse the games GeForce NOW offers, and play one. */
+class GfnActivity : ComponentActivity() {
+ data class Game(val id: String, val variantId: String, val title: String, val store: String,
+ val imageUrl: String, val inLibrary: Boolean, val search: String)
+
+ private sealed interface Screen {
+ data object Loading : Screen
+ data class SignedOut(val error: String? = null) : Screen
+ data class Code(val userCode: String, val url: String, val attemptId: String, val intervalMs: Long) : Screen
+ data class Games(val user: String, val games: List) : Screen
+ data class Failed(val message: String) : Screen
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContent { DroidDeckTheme { Content() } }
+ }
+
+ @Composable
+ private fun Content() {
+ var screen by remember { mutableStateOf(Screen.Loading) }
+ val scope = rememberCoroutineScope()
+ val load: () -> Unit = {
+ screen = Screen.Loading
+ scope.launch { screen = withContext(Dispatchers.IO) { loadSignedIn() } }
+ }
+ LaunchedEffect(Unit) { load() }
+ Column(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)) {
+ Row(Modifier.fillMaxWidth().padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
+ OutlinedButton(onClick = { finish() }) { Text("Back") }
+ Text("GeForce NOW", style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold,
+ color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.padding(horizontal = 16.dp).weight(1f))
+ val current = screen
+ if (current is Screen.Games) {
+ Text(current.user, color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.padding(end = 12.dp))
+ OutlinedButton(onClick = {
+ scope.launch {
+ withContext(Dispatchers.IO) { runCatching { GfnCore.request(this@GfnActivity, "auth.logout") } }
+ screen = Screen.SignedOut()
+ }
+ }) { Text("Sign out") }
+ }
+ }
+ Text("Unofficial client built on OpenNOW. NVIDIA does not support third-party GeForce NOW apps.",
+ color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.6f), fontSize = 12.sp,
+ modifier = Modifier.padding(horizontal = 16.dp))
+ when (val current = screen) {
+ Screen.Loading -> Message("Loading…")
+ is Screen.Failed -> Column(Modifier.padding(24.dp)) {
+ Text(current.message, color = MaterialTheme.colorScheme.onBackground)
+ Spacer(Modifier.height(12.dp))
+ Button(onClick = load) { Text("Try again") }
+ }
+ is Screen.SignedOut -> Column(Modifier.padding(24.dp)) {
+ Text("Sign in with your NVIDIA account to play your GeForce NOW games.",
+ color = MaterialTheme.colorScheme.onBackground)
+ current.error?.let { Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(top = 8.dp)) }
+ Spacer(Modifier.height(16.dp))
+ Button(onClick = {
+ scope.launch {
+ screen = withContext(Dispatchers.IO) {
+ runCatching { startSignIn() }.getOrElse { Screen.SignedOut(it.message) }
+ }
+ }
+ }) { Text("Sign in") }
+ }
+ is Screen.Code -> {
+ SignInCode(current) {
+ startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(current.url)))
+ }
+ LaunchedEffect(current.attemptId) {
+ screen = withContext(Dispatchers.IO) { waitForSignIn(current) }
+ }
+ }
+ is Screen.Games -> GameGrid(current.games) { game -> play(game) }
+ }
+ }
+ }
+
+ @Composable
+ private fun Message(text: String) {
+ Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ Text(text, color = MaterialTheme.colorScheme.onBackground)
+ }
+ }
+
+ @Composable
+ private fun SignInCode(code: Screen.Code, openBrowser: () -> Unit) {
+ Column(Modifier.padding(24.dp)) {
+ Text("On this phone or another device, open", color = MaterialTheme.colorScheme.onBackground)
+ Text(code.url, color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.Bold, modifier = Modifier.padding(vertical = 6.dp))
+ Text("and enter this code:", color = MaterialTheme.colorScheme.onBackground)
+ Text(code.userCode, fontSize = 34.sp, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground,
+ modifier = Modifier.padding(vertical = 12.dp))
+ Button(onClick = openBrowser) { Text("Open the sign-in page") }
+ Text("Waiting for you to sign in…", color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f),
+ modifier = Modifier.padding(top = 12.dp))
+ }
+ }
+
+ @Composable
+ private fun GameGrid(games: List, onPlay: (Game) -> Unit) {
+ var query by remember { mutableStateOf("") }
+ val shown = remember(games, query) {
+ val words = query.trim().lowercase().split(' ').filter { it.isNotEmpty() }
+ games.filter { game -> words.all { game.search.contains(it) } }
+ }
+ Column {
+ OutlinedTextField(value = query, onValueChange = { query = it }, singleLine = true,
+ label = { Text("Search ${games.size} games") },
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp))
+ LazyVerticalGrid(columns = GridCells.Adaptive(220.dp), modifier = Modifier.fillMaxSize(),
+ horizontalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(12.dp),
+ contentPadding = androidx.compose.foundation.layout.PaddingValues(16.dp)) {
+ items(shown, key = { it.id }) { game ->
+ Column(Modifier.clip(RoundedCornerShape(10.dp)).background(MaterialTheme.colorScheme.surfaceVariant)
+ .clickable { onPlay(game) }) {
+ AsyncImage(model = game.imageUrl, contentDescription = game.title, contentScale = ContentScale.Crop,
+ modifier = Modifier.fillMaxWidth().aspectRatio(460f / 215f))
+ Text(game.title, maxLines = 1, overflow = TextOverflow.Ellipsis, fontWeight = FontWeight.SemiBold,
+ color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = 10.dp, top = 8.dp, end = 10.dp))
+ Text(game.store + if (game.inLibrary) " · in your library" else "", fontSize = 12.sp,
+ color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f),
+ modifier = Modifier.padding(start = 10.dp, bottom = 8.dp, end = 10.dp).width(200.dp))
+ }
+ }
+ }
+ }
+ }
+
+ private fun play(game: Game) {
+ startActivity(Intent(this, GfnPlayerActivity::class.java)
+ .putExtra(GfnPlayerActivity.EXTRA_APP_ID, game.id)
+ .putExtra(GfnPlayerActivity.EXTRA_VARIANT_ID, game.variantId)
+ .putExtra(GfnPlayerActivity.EXTRA_TITLE, game.title))
+ }
+
+ private fun loadSignedIn(): Screen = runCatching {
+ val auth = GfnCore.request(this, "auth.session.get")
+ val user = auth.optJSONObject("session")?.optJSONObject("user") ?: auth.optJSONObject("user")
+ if (user == null || user.optString("userId").isEmpty()) return Screen.SignedOut()
+ Screen.Games(user.optString("displayName").ifEmpty { "Signed in" }, loadGames())
+ }.getOrElse { Screen.Failed(it.message ?: "GeForce NOW could not start.") }
+
+ /** NVIDIA's full list (public catalog), marking the games in the account's library. */
+ private fun loadGames(): List {
+ val owned = runCatching { gamesOf(GfnCore.request(this, "catalog.library.list", JSONObject().put("limit", 100))) }
+ .getOrDefault(emptyList()).map { it.id }.toSet()
+ return gamesOf(GfnCore.request(this, "catalog.public.list", timeoutMs = 60_000))
+ .map { if (it.id in owned) it.copy(inLibrary = true) else it }
+ .sortedBy { it.title.lowercase() }
+ }
+
+ private fun gamesOf(result: JSONObject): List {
+ val list = result.optJSONArray("games") ?: return emptyList()
+ return (0 until list.length()).mapNotNull { index ->
+ val game = list.optJSONObject(index) ?: return@mapNotNull null
+ val variants = game.optJSONArray("variants")
+ val variant = variants?.optJSONObject(game.optInt("selectedVariantIndex", 0).coerceIn(0, (variants.length() - 1).coerceAtLeast(0)))
+ Game(id = game.optString("id"),
+ variantId = variant?.optString("id").orEmpty().ifEmpty { game.optString("launchAppId") },
+ title = game.optString("title"),
+ store = variant?.optString("store").orEmpty(),
+ imageUrl = game.optString("imageUrl"),
+ inLibrary = game.optBoolean("isInLibrary"),
+ search = game.optString("searchText").ifEmpty { game.optString("title").lowercase() })
+ }.filter { it.id.isNotEmpty() && it.variantId.isNotEmpty() }
+ }
+
+ private fun startSignIn(): Screen {
+ val challenge = GfnCore.request(this, "auth.device.start")
+ return Screen.Code(
+ userCode = challenge.optString("userCode"),
+ url = challenge.optString("verificationUriComplete").ifEmpty { challenge.optString("verificationUri") },
+ attemptId = challenge.optString("attemptId"),
+ intervalMs = (challenge.optDouble("intervalSeconds", 5.0) * 1000).toLong().coerceAtLeast(1000))
+ }
+
+ private suspend fun waitForSignIn(code: Screen.Code): Screen {
+ var interval = code.intervalMs
+ while (true) {
+ delay(interval)
+ val poll = runCatching { GfnCore.request(this, "auth.device.poll", JSONObject().put("attemptId", code.attemptId)) }
+ .getOrElse { return Screen.SignedOut(it.message) }
+ when (poll.optString("status")) {
+ "authorized" -> {
+ runCatching {
+ GfnCore.request(this, "auth.device.complete",
+ JSONObject().put("attemptId", code.attemptId).put("staySignedIn", true))
+ }.onFailure { return Screen.SignedOut(it.message) }
+ return loadSignedIn()
+ }
+ "pending", "slow_down" -> interval = poll.optLong("retryAfterMs",
+ (poll.optDouble("intervalSeconds", interval / 1000.0) * 1000).toLong()).coerceAtLeast(1000)
+ else -> return Screen.SignedOut(poll.optString("message").ifEmpty { "Sign-in did not finish. Try again." })
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gfn/GfnCore.kt b/app/src/main/java/com/droiddeck/launcher/stores/gfn/GfnCore.kt
new file mode 100644
index 0000000000..185e6eaafd
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/stores/gfn/GfnCore.kt
@@ -0,0 +1,128 @@
+package com.droiddeck.launcher.stores.gfn
+
+import android.content.Context
+import android.util.Log
+import org.json.JSONObject
+import java.io.BufferedWriter
+import java.io.File
+import java.util.concurrent.CompletableFuture
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.TimeUnit
+import java.util.concurrent.TimeoutException
+import java.util.concurrent.atomic.AtomicLong
+
+class GfnError(val code: String, message: String) : Exception(message)
+
+/**
+ * OpenNOW's core service (external/opennow, MIT, by Zortos) as a child process: sign-in, the
+ * GeForce NOW catalog and CloudMatch sessions, spoken as newline-delimited JSON on its stdin and
+ * stdout (external/opennow/docs/core-protocol.md). It ships as libopennowcore.so in the native
+ * library directory, the one place the app may run programs from.
+ */
+object GfnCore {
+ private const val TAG = "GfnCore"
+ private const val PROTOCOL_VERSION = 5
+ private const val BINARY = "libopennowcore.so"
+
+ private var process: Process? = null
+ private var writer: BufferedWriter? = null
+ private val pending = ConcurrentHashMap>()
+ private val nextId = AtomicLong(1)
+ private val listeners = java.util.concurrent.CopyOnWriteArrayList<(String, JSONObject) -> Unit>()
+
+ fun addListener(listener: (String, JSONObject) -> Unit) { listeners += listener }
+ fun removeListener(listener: (String, JSONObject) -> Unit) { listeners -= listener }
+
+ /** Starts the core if it is not running, then checks the protocol and turns its reporting off. */
+ @Synchronized
+ fun ensureStarted(context: Context) {
+ if (process?.isAlive == true) return
+ val app = context.applicationContext
+ val binary = File(app.applicationInfo.nativeLibraryDir, BINARY)
+ check(binary.isFile) { "This build has no GeForce NOW core ($BINARY)" }
+ val dataDir = File(app.filesDir, "gfn/core").apply { mkdirs() }
+ val logFile = File(app.filesDir, "gfn/core.log")
+ val started = ProcessBuilder(binary.path, "--data-dir", dataDir.path)
+ .directory(dataDir)
+ .redirectError(ProcessBuilder.Redirect.appendTo(logFile))
+ .start()
+ process = started
+ writer = started.outputStream.bufferedWriter()
+ Thread({ readLoop(started) }, "gfn-core-out").apply { isDaemon = true; start() }
+ Log.i(TAG, "core started")
+ request(app, "core.hello", JSONObject()
+ .put("protocolVersion", PROTOCOL_VERSION)
+ .put("shell", "qt")
+ .put("shellVersion", "droiddeck"), timeoutMs = 10_000)
+ // DroidDeck never sends OpenNOW's analytics or crash reports anywhere.
+ for ((key, value) in listOf("automaticBugReports" to "disabled", "errorReportingConsent" to "denied")) {
+ runCatching { request(app, "settings.set", JSONObject().put("key", key).put("value", value)) }
+ .onFailure { Log.w(TAG, "could not set $key: ${it.message}") }
+ }
+ }
+
+ /** One request, answered with its `result` or thrown as [GfnError]. Blocking: call off the main thread. */
+ fun request(context: Context, method: String, params: JSONObject = JSONObject(), timeoutMs: Long = 30_000): JSONObject {
+ if (method != "core.hello") ensureStarted(context)
+ val id = "dd-" + nextId.getAndIncrement()
+ val answer = CompletableFuture()
+ pending[id] = answer
+ try {
+ val line = JSONObject().put("type", "request").put("id", id).put("method", method).put("params", params).toString()
+ synchronized(this) {
+ val out = writer ?: throw GfnError("core_stopped", "The GeForce NOW core is not running")
+ out.write(line)
+ out.newLine()
+ out.flush()
+ }
+ val response = try {
+ answer.get(timeoutMs, TimeUnit.MILLISECONDS)
+ } catch (e: TimeoutException) {
+ throw GfnError("timeout", "GeForce NOW did not answer in time ($method)")
+ }
+ if (response.optBoolean("ok")) return response.optJSONObject("result") ?: JSONObject()
+ val error = response.optJSONObject("error")
+ throw GfnError(error?.optString("code").orEmpty().ifEmpty { "error" },
+ error?.optString("message").orEmpty().ifEmpty { "GeForce NOW request failed ($method)" })
+ } finally {
+ pending.remove(id)
+ }
+ }
+
+ @Synchronized
+ fun stop() {
+ runCatching { writer?.close() }
+ process?.destroy()
+ process = null
+ writer = null
+ pending.values.forEach { it.completeExceptionally(GfnError("core_stopped", "The GeForce NOW core stopped")) }
+ pending.clear()
+ }
+
+ private fun readLoop(running: Process) {
+ try {
+ running.inputStream.bufferedReader().useLines { lines ->
+ lines.forEach { line ->
+ val message = runCatching { JSONObject(line) }.getOrNull() ?: return@forEach
+ when (message.optString("type")) {
+ "event" -> {
+ val name = message.optString("name")
+ val payload = message.optJSONObject("payload") ?: JSONObject()
+ listeners.forEach { runCatching { it(name, payload) } }
+ }
+ else -> pending[message.optString("id")]?.complete(message)
+ }
+ }
+ }
+ } catch (_: Exception) {
+ }
+ Log.w(TAG, "core output ended")
+ synchronized(this) {
+ if (process === running) {
+ process = null
+ writer = null
+ }
+ }
+ pending.values.forEach { it.completeExceptionally(GfnError("core_stopped", "The GeForce NOW core stopped")) }
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gfn/GfnPlayerActivity.kt b/app/src/main/java/com/droiddeck/launcher/stores/gfn/GfnPlayerActivity.kt
new file mode 100644
index 0000000000..555763681a
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/stores/gfn/GfnPlayerActivity.kt
@@ -0,0 +1,282 @@
+package com.droiddeck.launcher.stores.gfn
+
+import android.app.AlertDialog
+import android.graphics.Color
+import android.os.Bundle
+import android.util.Log
+import android.view.Gravity
+import android.view.InputDevice
+import android.view.KeyEvent
+import android.view.MotionEvent
+import android.view.SurfaceHolder
+import android.view.SurfaceView
+import android.view.WindowManager
+import android.widget.FrameLayout
+import android.widget.TextView
+import androidx.activity.ComponentActivity
+import androidx.activity.OnBackPressedCallback
+import androidx.core.view.WindowCompat
+import androidx.core.view.WindowInsetsCompat
+import androidx.core.view.WindowInsetsControllerCompat
+import org.json.JSONObject
+import java.util.concurrent.Executors
+import kotlin.math.hypot
+import kotlin.math.roundToInt
+
+/** Plays one GeForce NOW game: books a seat, waits in the queue, then streams onto a SurfaceView. */
+class GfnPlayerActivity : ComponentActivity() {
+ companion object {
+ const val EXTRA_APP_ID = "appId"
+ const val EXTRA_VARIANT_ID = "variantId"
+ const val EXTRA_TITLE = "title"
+ private const val TAG = "GfnPlayer"
+ private const val DEADZONE = 0.15f
+ }
+
+ private lateinit var status: TextView
+ private val worker = Executors.newSingleThreadExecutor()
+ private var streamer: GfnStreamer? = null
+ @Volatile private var session: JSONObject? = null
+ @Volatile private var closed = false
+ @Volatile private var capabilities: JSONObject? = null
+ private val helloWait = java.util.concurrent.CompletableFuture()
+ private val pads = Pads()
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ WindowCompat.setDecorFitsSystemWindows(window, false)
+ WindowInsetsControllerCompat(window, window.decorView).apply {
+ hide(WindowInsetsCompat.Type.systemBars())
+ systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
+ }
+ val root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) }
+ val surface = SurfaceView(this)
+ surface.holder.addCallback(object : SurfaceHolder.Callback {
+ override fun surfaceCreated(holder: SurfaceHolder) = GfnStreamer.setSurface(holder.surface)
+ override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}
+ override fun surfaceDestroyed(holder: SurfaceHolder) = GfnStreamer.setSurface(null)
+ })
+ root.addView(surface, FrameLayout.LayoutParams(-1, -1))
+ status = TextView(this).apply {
+ setTextColor(Color.WHITE)
+ textSize = 18f
+ gravity = Gravity.CENTER
+ setPadding(48, 48, 48, 48)
+ }
+ root.addView(status, FrameLayout.LayoutParams(-1, -1))
+ setContentView(root)
+ onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
+ override fun handleOnBackPressed() = confirmLeave()
+ })
+ val appId = intent.getStringExtra(EXTRA_APP_ID).orEmpty()
+ val variantId = intent.getStringExtra(EXTRA_VARIANT_ID).orEmpty()
+ val title = intent.getStringExtra(EXTRA_TITLE).orEmpty()
+ show("Starting $title…")
+ worker.execute {
+ runCatching { play(appId, variantId, title) }.onFailure {
+ Log.w(TAG, "could not start: ${it.message}")
+ show(it.message ?: "GeForce NOW could not start this game.")
+ }
+ }
+ }
+
+ private fun play(appId: String, variantId: String, title: String) {
+ val engine = GfnStreamer(::onStreamerMessage)
+ streamer = engine
+ engine.send("hello", JSONObject().put("protocolVersion", 7))
+ val caps = helloWait.get(10, java.util.concurrent.TimeUnit.SECONDS)
+ capabilities = caps
+
+ val inspect = GfnCore.request(this, "catalog.launch.inspect", JSONObject().put("appId", appId).put("variantId", variantId))
+ val decision = inspect.optJSONObject("decision")
+ if (decision?.optString("status") != "ready") {
+ show(decision?.optString("message").orEmpty().ifEmpty { "This game can't be started with this account." })
+ return
+ }
+ show("Requesting a GeForce NOW seat…")
+ var current = GfnCore.request(this, "session.create", JSONObject()
+ .put("appId", variantId)
+ .put("variantId", variantId)
+ .put("catalogAppId", appId)
+ .put("scope", inspect.opt("scope"))
+ .put("title", title)
+ .put("runtimeCapabilities", caps), timeoutMs = 60_000)
+ current = current.optJSONObject("session") ?: current
+ session = current
+ while (!closed && !ready(current)) {
+ val position = current.optInt("queuePosition", 0)
+ show(if (position > 0) "In the queue: position $position" else "Preparing your seat…")
+ Thread.sleep(2_000)
+ val polled = GfnCore.request(this, "session.poll", JSONObject()
+ .put("sessionId", current.opt("sessionId"))
+ .put("streamingBaseUrl", current.opt("streamingBaseUrl")), timeoutMs = 35_000)
+ current = polled.optJSONObject("session") ?: polled
+ session = current
+ if (current.optString("phase") == "failed") {
+ show("GeForce NOW could not prepare this session.")
+ return
+ }
+ }
+ if (closed) return
+ show("Connecting…")
+ val prepared = GfnCore.request(this, "streamer.prepare",
+ JSONObject().put("session", current).put("runtimeCapabilities", caps))
+ prepared.optJSONObject("session")?.let { session = it }
+ val context = prepared.optJSONObject("context") ?: error("GeForce NOW returned no stream context")
+ engine.send("start", JSONObject().put("context", context).put("microphoneEnabled", false))
+ }
+
+ private fun ready(session: JSONObject): Boolean {
+ val phase = session.optString("phase")
+ return phase == "ready" || phase == "streaming" || session.optInt("status", 0) >= 2
+ }
+
+ private fun onStreamerMessage(message: JSONObject) {
+ when (message.optString("type")) {
+ "ready" -> message.optJSONObject("capabilities")?.let { helloWait.complete(it) }
+ "error" -> {
+ Log.w(TAG, "streamer error ${message.optString("code")}: ${message.optString("message")}")
+ show(message.optString("message").ifEmpty { "The stream stopped." })
+ }
+ "status" -> when (message.optString("event")) {
+ "first-frame" -> runOnUiThread { status.visibility = android.view.View.GONE }
+ }
+ "stopped" -> show("The stream ended.")
+ }
+ }
+
+ private fun show(text: String) = runOnUiThread {
+ status.text = text
+ status.visibility = android.view.View.VISIBLE
+ }
+
+ private fun confirmLeave() {
+ AlertDialog.Builder(this)
+ .setTitle("Leave the game?")
+ .setMessage("This ends your GeForce NOW session.")
+ .setPositiveButton("Leave") { _, _ -> finish() }
+ .setNegativeButton("Keep playing", null)
+ .show()
+ }
+
+ override fun onDestroy() {
+ closed = true
+ val engine = streamer
+ val active = session
+ streamer = null
+ Thread({
+ runCatching { engine?.send("stop") }
+ if (active != null) {
+ runCatching {
+ GfnCore.request(applicationContext, "session.stop", JSONObject()
+ .put("sessionId", active.opt("sessionId"))
+ .put("streamingBaseUrl", active.opt("streamingBaseUrl")))
+ }.onFailure { Log.w(TAG, "session stop: ${it.message}") }
+ }
+ engine?.close()
+ }, "gfn-leave").start()
+ worker.shutdownNow()
+ super.onDestroy()
+ }
+
+ // --- controllers: Android gamepads in XInput layout, the same mapping OpenNOW uses ---
+
+ override fun dispatchKeyEvent(event: KeyEvent): Boolean {
+ if (event.isFromSource(InputDevice.SOURCE_GAMEPAD) || event.isFromSource(InputDevice.SOURCE_JOYSTICK)) {
+ val bit = buttonBit(event.keyCode)
+ if (bit != 0) {
+ if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) pads.press(event.deviceId, bit, true)
+ else if (event.action == KeyEvent.ACTION_UP) pads.press(event.deviceId, bit, false)
+ return true
+ }
+ }
+ return super.dispatchKeyEvent(event)
+ }
+
+ override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
+ if (event.isFromSource(InputDevice.SOURCE_JOYSTICK) && event.action == MotionEvent.ACTION_MOVE) {
+ pads.move(event)
+ return true
+ }
+ return super.dispatchGenericMotionEvent(event)
+ }
+
+ private fun buttonBit(keyCode: Int): Int = when (keyCode) {
+ KeyEvent.KEYCODE_BUTTON_A -> 0x1000
+ KeyEvent.KEYCODE_BUTTON_B -> 0x2000
+ KeyEvent.KEYCODE_BUTTON_X -> 0x4000
+ KeyEvent.KEYCODE_BUTTON_Y -> 0x8000
+ KeyEvent.KEYCODE_BUTTON_SELECT -> 0x0020
+ KeyEvent.KEYCODE_BUTTON_START -> 0x0010
+ KeyEvent.KEYCODE_BUTTON_THUMBL -> 0x0040
+ KeyEvent.KEYCODE_BUTTON_THUMBR -> 0x0080
+ KeyEvent.KEYCODE_BUTTON_L1 -> 0x0100
+ KeyEvent.KEYCODE_BUTTON_R1 -> 0x0200
+ KeyEvent.KEYCODE_DPAD_UP -> 0x0001
+ KeyEvent.KEYCODE_DPAD_DOWN -> 0x0002
+ KeyEvent.KEYCODE_DPAD_LEFT -> 0x0004
+ KeyEvent.KEYCODE_DPAD_RIGHT -> 0x0008
+ else -> 0
+ }
+
+ private inner class Pads {
+ private inner class Pad(val slot: Int) {
+ var buttons = 0
+ var hatButtons = 0
+ var lt = 0
+ var rt = 0
+ var lx = 0
+ var ly = 0
+ var rx = 0
+ var ry = 0
+ }
+
+ private val bySlot = arrayOfNulls(4)
+ private val byDevice = HashMap()
+
+ @Synchronized
+ private fun pad(deviceId: Int): Pad? = byDevice[deviceId] ?: run {
+ val free = (0 until 4).firstOrNull { bySlot[it] == null } ?: return null
+ Pad(free).also { bySlot[free] = it; byDevice[deviceId] = it }
+ }
+
+ private fun connected(): Int = (0 until 4).filter { bySlot[it] != null }.fold(0) { bits, slot -> bits or (1 shl slot) or (1 shl (slot + 8)) }
+
+ fun press(deviceId: Int, bit: Int, down: Boolean) {
+ val pad = pad(deviceId) ?: return
+ pad.buttons = if (down) pad.buttons or bit else pad.buttons and bit.inv()
+ send(pad)
+ }
+
+ fun move(event: MotionEvent) {
+ val pad = pad(event.deviceId) ?: return
+ val (lx, ly) = stick(event.getAxisValue(MotionEvent.AXIS_X), event.getAxisValue(MotionEvent.AXIS_Y))
+ val rightX = event.getAxisValue(MotionEvent.AXIS_Z).takeIf { it != 0f } ?: event.getAxisValue(MotionEvent.AXIS_RX)
+ val rightY = event.getAxisValue(MotionEvent.AXIS_RZ).takeIf { it != 0f } ?: event.getAxisValue(MotionEvent.AXIS_RY)
+ val (rx, ry) = stick(rightX, rightY)
+ pad.lx = lx; pad.ly = ly; pad.rx = rx; pad.ry = ry
+ pad.lt = trigger(maxOf(event.getAxisValue(MotionEvent.AXIS_LTRIGGER), event.getAxisValue(MotionEvent.AXIS_BRAKE)))
+ pad.rt = trigger(maxOf(event.getAxisValue(MotionEvent.AXIS_RTRIGGER), event.getAxisValue(MotionEvent.AXIS_GAS)))
+ val hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X)
+ val hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y)
+ pad.hatButtons = (if (hatY < -0.5f) 0x0001 else 0) or (if (hatY > 0.5f) 0x0002 else 0) or
+ (if (hatX < -0.5f) 0x0004 else 0) or (if (hatX > 0.5f) 0x0008 else 0)
+ send(pad)
+ }
+
+ /** Radial deadzone, Y flipped so up is positive (XInput). */
+ private fun stick(x: Float, y: Float): Pair {
+ val magnitude = hypot(x, y)
+ if (magnitude < DEADZONE) return 0 to 0
+ val scaled = ((magnitude - DEADZONE) / (1f - DEADZONE)).coerceIn(0f, 1f) / magnitude
+ return (x * scaled * 32767f).roundToInt() to (-y * scaled * 32767f).roundToInt()
+ }
+
+ private fun trigger(value: Float): Int = (value.coerceIn(0f, 1f) * 255f).roundToInt()
+
+ private fun send(pad: Pad) {
+ streamer?.gamepad(pad.slot, connected(), pad.buttons or pad.hatButtons, pad.lt, pad.rt, pad.lx, pad.ly, pad.rx, pad.ry)
+ }
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gfn/GfnStreamer.kt b/app/src/main/java/com/droiddeck/launcher/stores/gfn/GfnStreamer.kt
new file mode 100644
index 0000000000..d3ca54f54e
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/stores/gfn/GfnStreamer.kt
@@ -0,0 +1,64 @@
+package com.droiddeck.launcher.stores.gfn
+
+import android.view.Surface
+import org.json.JSONObject
+import java.util.concurrent.atomic.AtomicLong
+
+/**
+ * OpenNOW's native streamer engine (external/opennow, MIT, by Zortos) inside libdroiddeckgfn.so,
+ * with DroidDeck's Android media backend: MediaCodec onto [setSurface]'s Surface, AAudio sound.
+ * Commands are the engine's JSON protocol (`hello`, `start`, `stop`, ...); answers and events
+ * arrive on [onMessage] from a polling thread.
+ */
+class GfnStreamer(private val onMessage: (JSONObject) -> Unit) {
+ private var handle = nativeOpen()
+ private val ids = AtomicLong(1)
+ @Volatile private var open = true
+ private val poller = Thread({
+ while (open) {
+ val line = nativePoll(handle, 250) ?: continue
+ runCatching { JSONObject(line) }.getOrNull()?.let { message -> runCatching { onMessage(message) } }
+ }
+ }, "gfn-streamer-poll").apply { isDaemon = true; start() }
+
+ /** Sends one command; returns its id (responses carry it), or "" if the engine is closed. */
+ fun send(type: String, fields: JSONObject = JSONObject()): String {
+ if (!open) return ""
+ val id = "dd-" + ids.getAndIncrement()
+ fields.put("id", id).put("type", type)
+ return if (nativeCommand(handle, fields.toString())) id else ""
+ }
+
+ fun gamepad(slot: Int, connected: Int, buttons: Int, leftTrigger: Int, rightTrigger: Int,
+ leftX: Int, leftY: Int, rightX: Int, rightY: Int) {
+ if (open) nativeGamepad(handle, slot, connected, buttons, leftTrigger, rightTrigger, leftX, leftY, rightX, rightY)
+ }
+
+ fun key(virtualKey: Int, modifiers: Int, pressed: Boolean) {
+ if (open) nativeKey(handle, virtualKey, modifiers, pressed)
+ }
+
+ fun close() {
+ if (!open) return
+ open = false
+ poller.join(1_000)
+ nativeClose(handle)
+ handle = 0
+ }
+
+ companion object {
+ init { System.loadLibrary("droiddeckgfn") }
+
+ @JvmStatic fun setSurface(surface: Surface?) = nativeSetSurface(surface)
+
+ @JvmStatic private external fun nativeOpen(): Long
+ @JvmStatic private external fun nativeCommand(handle: Long, json: String): Boolean
+ @JvmStatic private external fun nativePoll(handle: Long, timeoutMs: Int): String?
+ @JvmStatic private external fun nativeClose(handle: Long)
+ @JvmStatic private external fun nativeSetSurface(surface: Surface?)
+ @JvmStatic private external fun nativeGamepad(handle: Long, slot: Int, connected: Int, buttons: Int,
+ leftTrigger: Int, rightTrigger: Int,
+ leftX: Int, leftY: Int, rightX: Int, rightY: Int)
+ @JvmStatic private external fun nativeKey(handle: Long, virtualKey: Int, modifiers: Int, pressed: Boolean)
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt
index 916e44e43f..116387bcd2 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt
@@ -93,6 +93,7 @@ import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.automirrored.filled.Login
import androidx.compose.foundation.basicMarquee
import androidx.compose.material.icons.filled.Settings
+import androidx.compose.material.icons.outlined.Cloud
import androidx.compose.material.icons.outlined.Download
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
@@ -650,6 +651,12 @@ private fun StoreChips(
) { onDownloads() }
ChipGlide(keys.indexOf(DOWNLOADS), bounds[DOWNLOADS], tint, visible = fillShown && highlighted == DOWNLOADS)
}
+ val gfnContext = LocalContext.current
+ StoreChip(
+ label = "GeForce NOW", on = false, under = false, key = "geforce-now", mark = pal.signal, modifier = Modifier,
+ lead = { Icon(Icons.Outlined.Cloud, null, modifier = Modifier.size(18.dp)) },
+ description = "GeForce NOW", onFocused = onFocusChip,
+ ) { gfnContext.startActivity(android.content.Intent(gfnContext, com.droiddeck.launcher.stores.gfn.GfnActivity::class.java)) }
var cogAt by remember { mutableStateOf(null) }
Box(Modifier.onGloballyPositioned { cogAt = it.boundsInRoot() }) {
IconChip(Icons.Filled.Settings, stringResource(R.string.stores_settings)) { onSettings(cogAt) }