Compare commits

..
Author SHA1 Message Date
The412Banner 332c4ea751 GFN: GeForce NOW as a Stores tab
GeForce NOW was its own screen behind a chip. It is now a tab in the Stores tab row after
the store tabs, reached by tapping, the shoulder buttons or focus like the others, with its
pane in the same animated pane slot:

- Signed out: a sign-in card like the stores' (title, Sign in, device code inline).
- Signed in: a profile strip (name, library count, Refresh, Sign out), Store / My library /
  Connected stores pills next to the usual search header, and games as the app's own
  cards (CardFace) in the adaptive store grid, with controller focus. A card plays the game.
- NVIDIA green for the tab's chip, dot and accents (GfnTheme).

The OpenNOW core locks its data directory, so it keeps running once, in the :gfn process
with the player. GfnCoreService there answers core requests from the main process over
a binder; GfnCore routes to it outside :gfn. The state and requests the old screen held
moved to GfnState so they survive tab switches. GfnActivity is removed.
2026-10-26 18:25:14 +00:00
The412Banner 41b065e89c GFN: keep the NVIDIA sign-in across restarts; tidy store rows and labels
- On Android keyring falls back to an in-memory mock, so the core 'saved' the session
  in memory and lost it on every restart (the user had to sign in again). The vault now
  uses OpenNOW's JSON fallback in the app's private data directory there.
- Connected stores hides NVIDIA's non-store rows (NVIDIA, UNKNOWN, NONE) and stores with
  no link or sync support unless connected.
- Store names on cards read Steam, Battle.net, Xbox ...; My library cards drop the
  redundant 'in library'.
2026-10-26 18:25:14 +00:00
The412Banner bc35bb5d43 GFN: My library and Connected stores tabs
- My library: the account's GeForce NOW library (catalog.library.list, every page),
  searchable, launchable.
- Connected stores: the store accounts linked to GeForce NOW (Ubisoft, Battle.net,
  Epic, Gaijin, GOG, Steam, Xbox) with Connect/Reconnect, Sync library and Disconnect,
  chosen by OpenNOW's own rule. Connect opens the store's sign-in page and waits for the
  link; Sync follows the operation until the library refresh.
- Game cards are one shared composable for Store and My library.
2026-10-26 18:25:14 +00:00
The412Banner c378489f45 GFN store: games from NVIDIA's signed-in catalog so launching works
The first launch tests failed with "The exact catalog game was not returned": the
public list carries Steam ids, while catalog.launch.inspect looks games up by GFN's own
app and variant ids. The grid now pages through catalog.store.local (40 at a time,
more while scrolling) and searches with catalog.store.list; in-library marks come from
the store items themselves.
2026-10-26 18:25:14 +00:00
The412Banner ef4e43032c GFN games: five smaller cards per row 2026-10-26 18:25:14 +00:00
The412Banner 62f49756bf GFN games: up to 1000 shown, search covers the whole catalog, full library marks
The first test showed 240 games: catalog.public.list stops at its default limit.
Load 1000, show NVIDIA's total, search through the core's searchQuery so every game
can be found, and page through the account's library for the in-library marks.
2026-10-26 18:25:14 +00:00
The412Banner 510c7e35e6 GFN build: vendored mtu with a versioned Android target for bindgen
cargo-ndk sets bindgen's per-target clang arguments itself, so the environment
workaround never reached the mtu build script. mtu 0.3.0 is vendored with one
build.rs change and patched in for the GFN crate and the OpenNOW workspace.
2026-10-26 18:25:14 +00:00
The412Banner 57578501e5 GFN build: versioned Android target for bindgen 2026-10-26 18:25:14 +00:00
The412Banner 53b5fde2ff GeForce NOW store: sign-in, game list and native player
- GfnCore: OpenNOW's core service as a child process (newline-delimited JSON); turns
  OpenNOW's analytics and crash reports off.
- GfnStreamer: the JNI streamer engine with a polling thread for answers and events.
- GfnActivity: NVIDIA device sign-in (code + link), NVIDIA's full game list with search,
  games in the account's library marked.
- GfnPlayerActivity: catalog.launch.inspect -> session.create -> queue polling ->
  streamer.prepare -> start, onto a SurfaceView; controllers mapped to XInput like
  OpenNOW; leaving asks first and ends the session.
- Stores page: a GeForce NOW chip opens it. Both screens run in their own :gfn process.
Not compiled locally (no Android SDK here); CI is the first compile.
2026-10-26 18:25:14 +00:00
The412Banner 6f5db08efb Build the GeForce NOW streamer host and OpenNOW core with cargo-ndk
buildGfnHost builds libdroiddeckgfn.so; buildOpenNowCore builds OpenNOW's core
service and stages it as libopennowcore.so so the app can run it from its native
library directory.
2026-10-26 18:25:14 +00:00
The412Banner d9efc1efee GeForce NOW: streamer host library (libdroiddeckgfn.so)
Runs OpenNOW's native streamer engine on its own thread with the Android media
backend. JNI for com.droiddeck.launcher.stores.gfn.GfnStreamer: open/close, JSON
commands in, one poll queue for responses and events out, the player Surface, and
gamepad (XInput layout) and key input into the engine's input queue.
Builds for aarch64-linux-android and links only Android system libraries.
2026-10-26 18:25:14 +00:00
The412Banner f44e3c46e1 OpenNOW streamer: Android media backend (MediaCodec video, AAudio sound)
The platform crate gets an android module with the same public types the streamer core
uses (MediaRuntime, MediaSession, MediaSink, MediaControl, ...). Video frames go through
OpenNOW's own VideoQueue into a hardware MediaCodec decoder that renders onto the Surface
the app sets; frames are acknowledged to the server as they are queued (flow control).
Opus audio is decoded into a short buffer played by a low-latency AAudio stream.
Desktop backends stay upstream's code (desktop_lib.rs); shared types moved to
media_types.rs. opennow-streamer-core now compiles for aarch64-linux-android.
2026-10-26 18:25:13 +00:00
The412Banner 51e911f9a8 OpenNOW core: build for Android (Linux helpers cover target_os android) 2026-10-26 18:25:13 +00:00
The412Banner f0f17b9b63 Vendor OpenNOW's core and native streamer (MIT, by Zortos)
From OpenCloudGaming/OpenNOW a49b124c (2026-10-18): native/opennow-core and the
native/opennow-streamer crates DroidDeck's GeForce NOW store builds on, unmodified,
with OpenNOW's MIT license and a NOTICE crediting Zortos and the OpenNOW contributors.
2026-10-26 18:25:13 +00:00
862 changed files with 340500 additions and 1663 deletions

No files matched your search

+51
View File
@@ -325,6 +325,57 @@ def buildRustStores = tasks.register('buildRustStores', Exec) {
if (!skipRust) android.sourceSets.main.jniLibs.srcDir(rustJniLibsDir)
tasks.named('preBuild').configure { dependsOn(buildRustStores) }
// GeForce NOW: DroidDeck's streamer host (libdroiddeckgfn.so, src/main/rust/gfn) and OpenNOW's
// core service (external/opennow, MIT, by Zortos). The core is a program the app runs as a child
// process, so it ships as libopennowcore.so in the native library directory (the one place the
// app may exec from), like the Mali bridge server.
def gfnCrateDir = layout.projectDirectory.dir('src/main/rust/gfn')
def openNowCoreDir = rootProject.layout.projectDirectory.dir('external/opennow/native/opennow-core')
def gfnJniLibsDir = layout.buildDirectory.dir('gfnJniLibs')
def gfnCargoEnvironment = { Exec task ->
def cargoBin = "${System.getProperty('user.home')}/.cargo/bin"
task.environment 'PATH', "${cargoBin}${File.pathSeparator}${System.getenv('PATH')}"
task.environment 'ANDROID_NDK_HOME', android.ndkDirectory.absolutePath
task.environment 'CARGO_TERM_COLOR', 'never'
// bindgen (the mtu crate) otherwise passes an unversioned Android triple, which the NDK headers reject.
task.environment 'BINDGEN_EXTRA_CLANG_ARGS_aarch64_linux_android', '--target=aarch64-linux-android29'
}
def buildGfnHost = tasks.register('buildGfnHost', Exec) {
description = 'Cross-compiles the GeForce NOW streamer host (libdroiddeckgfn.so) with cargo-ndk.'
onlyIf { !skipRust }
inputs.dir(gfnCrateDir.dir('src'))
inputs.files(gfnCrateDir.file('Cargo.toml'), gfnCrateDir.file('Cargo.lock'))
inputs.dir(rootProject.file('external/opennow/native/opennow-streamer/crates'))
inputs.property('ndkVersion', android.ndkVersion)
outputs.dir(gfnJniLibsDir)
workingDir gfnCrateDir
gfnCargoEnvironment(it)
commandLine 'rustup', 'run', 'stable', 'cargo', 'ndk', '--target', 'arm64-v8a', '--platform', '29',
'--output-dir', gfnJniLibsDir.get().asFile.absolutePath,
'build', '--release', '--locked'
}
def buildOpenNowCore = tasks.register('buildOpenNowCore', Exec) {
description = "Cross-compiles OpenNOW's core service and stages it as libopennowcore.so."
onlyIf { !skipRust }
inputs.dir(openNowCoreDir.dir('src'))
inputs.files(openNowCoreDir.file('Cargo.toml'), openNowCoreDir.file('Cargo.lock'))
inputs.property('ndkVersion', android.ndkVersion)
outputs.file(gfnJniLibsDir.map { it.file('arm64-v8a/libopennowcore.so') })
workingDir openNowCoreDir
gfnCargoEnvironment(it)
commandLine 'rustup', 'run', 'stable', 'cargo', 'ndk', '--target', 'arm64-v8a', '--platform', '29',
'build', '--release', '--locked', '--bin', 'opennow-core'
doLast {
def built = openNowCoreDir.file('target/aarch64-linux-android/release/opennow-core').asFile
def staged = gfnJniLibsDir.get().file('arm64-v8a/libopennowcore.so').asFile
staged.parentFile.mkdirs()
java.nio.file.Files.copy(built.toPath(), staged.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING)
}
}
buildOpenNowCore.configure { mustRunAfter(buildGfnHost) }
if (!skipRust) android.sourceSets.main.jniLibs.srcDir(gfnJniLibsDir)
tasks.named('preBuild').configure { dependsOn(buildGfnHost, buildOpenNowCore) }
dependencies {
implementation "org.opencv:opencv:${trackingPack.OPENCV_VERSION}"
implementation 'org.khronos.openxr:openxr_loader_for_android:1.1.49'
+9
View File
@@ -180,6 +180,15 @@
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
android:theme="@style/AppTheme" />
<!-- GeForce NOW (OpenNOW's core and streamer): the core child and the player share the :gfn process;
the Stores page reaches the core through GfnCoreService. -->
<service android:name=".stores.gfn.GfnCoreService" android:exported="false" android:process=":gfn" />
<activity android:name=".stores.gfn.GfnPlayerActivity" android:exported="false"
android:process=":gfn" android:screenOrientation="sensorLandscape" android:hardwareAccelerated="true"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
android:theme="@style/AppTheme" />
<activity android:name=".stores.xbox.XboxCloudSettingsActivity" android:exported="false"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
android:theme="@style/AppTheme" />
@@ -268,7 +268,7 @@ static struct wl_event_source *g_fallback_timer;
static int g_fallback_armed;
volatile int g_fps_limit;
/* fps limit -1 (phone output, not mirrored): replaced buffers go back to the client at once instead of once per refresh. */
/* fps limit -1 (Performance mode without a limit): replaced buffers go back to the client at once instead of once per refresh. */
volatile int g_release_unpaced;
volatile int g_hide_shell;
@@ -91,16 +91,12 @@ class FrontEndActivity : ComponentActivity() {
private val components = ComponentsMenu(this, ui)
private val decky = DeckyMenu(this, ui)
private val updates = UpdatesMenu(this, ui)
private val protons = ProtonMenu(this, ui) { !busy && flood == null && compatLaunch == null && pkgStage == null && components.compBusy == null }
private val protons = ProtonMenu(this, ui) { !busy && flood == null && pkgStage == null && components.compBusy == null }
private var installed by mutableStateOf<String?>(null)
private var flood by mutableStateOf<PendingFlood?>(null)
private var floodProgress by androidx.compose.runtime.mutableFloatStateOf(0f)
private class PendingFlood(val from: androidx.compose.ui.geometry.Rect, val intent: Intent)
private class CompatLaunch(val intent: Intent, val loading: com.droiddeck.launcher.session.LoadingState, var menuInstall: Boolean)
private var compatLaunch by mutableStateOf<CompatLaunch?>(null)
private var compatLaunchPoll: Runnable? = null
private var compatLaunchVisible = false
private var returning by mutableStateOf<ReturningFlood?>(null)
private class ReturningFlood(val color: Int, val to: androidx.compose.ui.geometry.Rect?)
private var ready by mutableStateOf(false)
@@ -138,14 +134,9 @@ class FrontEndActivity : ComponentActivity() {
private var catalog by mutableStateOf<List<DesktopCatalog.Entry>?>(null)
private var catalogLoading by mutableStateOf(false)
private var packageRows by mutableStateOf<List<PackageRow>?>(null)
private object PackageOperation {
val id = mutableStateOf<String?>(null)
val stage = mutableStateOf<String?>(null)
val percent = mutableIntStateOf(-1)
}
private var pkgId by PackageOperation.id
private var pkgStage by PackageOperation.stage
private var pkgPercent by PackageOperation.percent
private var pkgId by mutableStateOf<String?>(null)
private var pkgStage by mutableStateOf<String?>(null)
private var pkgPercent by mutableIntStateOf(-1)
private var desktopInstalled by mutableStateOf(false)
private var desktopPresent by mutableStateOf(false)
private var battleNetInstalled by mutableStateOf(false)
@@ -401,6 +392,7 @@ class FrontEndActivity : ComponentActivity() {
private var theme by mutableStateOf("graphite")
private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE)
private var hdrOn by mutableStateOf(false)
private var performanceMode by mutableStateOf(false)
private var upscaler by mutableStateOf(0)
private var upscaleSharpness by mutableStateOf(75)
private var hdrReason by mutableStateOf<String?>(null)
@@ -448,14 +440,13 @@ class FrontEndActivity : ComponentActivity() {
override fun startActivity(intent: Intent?) {
if (intent?.component?.className == SessionActivity::class.java.name) {
if (compatLaunch != null) return
when {
busy || LinuxRuntimeInstaller.isBusy() -> {
android.widget.Toast.makeText(this, R.string.main_wait_runtime, android.widget.Toast.LENGTH_SHORT).show()
return
}
protons.protonBusyId != null || ProtonExtras.installInProgress -> {
waitForCompat(intent)
android.widget.Toast.makeText(this, R.string.main_wait_proton_install, android.widget.Toast.LENGTH_SHORT).show()
return
}
pkgStage != null -> {
@@ -483,8 +474,6 @@ class FrontEndActivity : ComponentActivity() {
flood = null
floodProgress = 0f
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
if (!busy && !LinuxRuntimeInstaller.isBusy() && pkgStage == null &&
(protons.protonBusyId != null || ProtonExtras.installInProgress)) waitForCompat(f.intent)
return
}
val signal = com.droiddeck.launcher.ui.Themes.byId(theme).signal
@@ -492,71 +481,6 @@ class FrontEndActivity : ComponentActivity() {
overridePendingTransition(0, 0)
}
private fun waitForCompat(next: Intent, menuInstall: Boolean = protons.protonBusyId != null) {
if (compatLaunch != null) return
com.droiddeck.launcher.ui.LaunchOrigin.take()
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
val waiting = CompatLaunch(Intent(next), com.droiddeck.launcher.session.LoadingState(this), menuInstall)
compatLaunch = waiting
val poll = object : Runnable {
override fun run() {
if (isDestroyed || isFinishing || compatLaunch !== waiting) return
if (protons.protonBusyId != null || ProtonExtras.installInProgress) {
waiting.menuInstall = waiting.menuInstall || protons.protonBusyId != null
val percent = if (protons.protonBusyId != null) protons.protonPercent else -1
val stage = protons.protonStage ?: getString(R.string.load_compat_wait)
waiting.loading.say(if (percent >= 0) getString(R.string.load_compat_progress, stage, percent) else stage,
com.droiddeck.launcher.session.LoadingState.Topic.RUNTIME, readable = true)
waiting.loading.percent = percent
waiting.loading.tick()
ui.postDelayed(this, 250)
return
}
if (!compatLaunchVisible) { ui.postDelayed(this, 250); return }
val problem = protons.protonProblem.takeIf { waiting.menuInstall }
if (problem == null && (busy || LinuxRuntimeInstaller.isBusy() || pkgStage != null)) {
waiting.loading.say(pkgStage ?: stage.takeIf { it.isNotBlank() } ?: getString(R.string.main_wait_runtime),
com.droiddeck.launcher.session.LoadingState.Topic.RUNTIME, readable = true)
waiting.loading.percent = if (pkgStage != null) pkgPercent else percent
waiting.loading.tick()
ui.postDelayed(this, 250)
return
}
compatLaunchPoll = null
if (problem != null) waiting.loading.showEnded(problem)
else {
compatLaunch = null
startActivity(waiting.intent)
}
}
}
compatLaunchPoll = poll
poll.run()
}
private fun cancelCompatLaunch() {
compatLaunchPoll?.let(ui::removeCallbacks)
compatLaunchPoll = null
compatLaunch = null
}
private fun restoreCompatLaunch(state: Bundle) {
savedIntent(state, KEY_COMPAT_LAUNCH)?.let { next ->
val problem = state.getString(KEY_COMPAT_PROBLEM)
if (problem == null) waitForCompat(next, state.getBoolean(KEY_COMPAT_MENU_INSTALL))
else compatLaunch = CompatLaunch(next,
com.droiddeck.launcher.session.LoadingState(this).apply { showEnded(problem) }, false)
}
}
private fun saveCompatLaunch(state: Bundle) {
compatLaunch?.let {
state.putParcelable(KEY_COMPAT_LAUNCH, it.intent)
state.putBoolean(KEY_COMPAT_MENU_INSTALL, it.menuInstall)
if (it.loading.ended) state.putString(KEY_COMPAT_PROBLEM, it.loading.step)
}
}
private var shortcutPicker by mutableStateOf(false)
private var shortcutLibraryScanning by mutableStateOf(false)
@Volatile private var libraryScanGeneration = 0
@@ -618,7 +542,7 @@ class FrontEndActivity : ComponentActivity() {
}
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false): Boolean {
if (pkgStage != null) {
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return false
}
@@ -730,7 +654,7 @@ class FrontEndActivity : ComponentActivity() {
android.widget.Toast.makeText(this, R.string.epic_client_uninstalling, android.widget.Toast.LENGTH_SHORT).show()
return false
}
if (pkgStage != null) {
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return false
}
@@ -1292,21 +1216,12 @@ class FrontEndActivity : ComponentActivity() {
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
}
}
androidx.activity.compose.BackHandler(compatLaunch != null) { cancelCompatLaunch() }
compatLaunch?.loading?.let { loading ->
com.droiddeck.launcher.ui.LoadingOverlay(
loading.step, loading.percent, loading.elapsed, getString(R.string.load_compat_hint), loading.ended,
loading.topic, loading.readable, title = getString(R.string.load_compat_title),
onCancel = ::cancelCompatLaunch, onClose = ::cancelCompatLaunch,
)
}
}
}
}
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled() }
else {
restoreCompatLaunch(savedInstanceState)
pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH)
savedIntent(savedInstanceState, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, savedInstanceState.getLong(KEY_SWITCH_DEADLINE)) }
}
@@ -1393,14 +1308,6 @@ class FrontEndActivity : ComponentActivity() {
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (compatLaunch != null) {
if (event.keyCode == KeyEvent.KEYCODE_BACK || event.keyCode == KeyEvent.KEYCODE_BUTTON_B) {
if (event.action == KeyEvent.ACTION_UP) cancelCompatLaunch()
return true
}
if (!compatLaunch!!.loading.ended && event.keyCode !in listOf(
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) return true
}
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) {
@@ -1417,20 +1324,8 @@ class FrontEndActivity : ComponentActivity() {
}
}
override fun dispatchGenericMotionEvent(event: android.view.MotionEvent): Boolean {
if (compatLaunch != null && !compatLaunch!!.loading.ended &&
com.droiddeck.launcher.input.PadBridge.isControllerMotionEvent(event)) return true
return super.dispatchGenericMotionEvent(event)
}
override fun onPause() {
compatLaunchVisible = false
super.onPause()
}
override fun onResume() {
super.onResume()
compatLaunchVisible = true
orientation = SessionPrefs.orientation(this)
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
requestedOrientation = launcherOrientation
@@ -1483,7 +1378,6 @@ class FrontEndActivity : ComponentActivity() {
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
saveCompatLaunch(outState)
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
switchingTo?.let {
outState.putParcelable(KEY_SWITCHING_TO, it)
@@ -1496,7 +1390,6 @@ class FrontEndActivity : ComponentActivity() {
else @Suppress("DEPRECATION") state.getParcelable(key)
override fun onDestroy() {
cancelCompatLaunch()
updates.unregister()
super.onDestroy()
}
@@ -1701,7 +1594,7 @@ class FrontEndActivity : ComponentActivity() {
}
private fun openBattleNet(args: List<String> = emptyList()) {
if (pkgStage != null) {
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return
}
@@ -1809,7 +1702,7 @@ class FrontEndActivity : ComponentActivity() {
ModeSettings(
mode = mode, resolution = resolution,
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
hdr = hdrOn, hdrReason = hdrReason,
hdr = hdrOn, hdrReason = hdrReason, performanceMode = performanceMode,
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
gpuDrivers = drivers.summary(),
touchMode = touchMode,
@@ -1874,6 +1767,7 @@ class FrontEndActivity : ComponentActivity() {
onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); resolution = value },
onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on },
onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) },
onPerformanceMode = { on -> SessionPrefs.setPerformanceMode(this, mode, on); performanceMode = on },
onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m },
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
@@ -2124,6 +2018,7 @@ class FrontEndActivity : ComponentActivity() {
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
loadBootMovie()
hdrOn = SessionPrefs.hdr(this, mode)
performanceMode = SessionPrefs.performanceMode(this, mode)
upscaler = SessionPrefs.upscaler(this)
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
@@ -2421,9 +2316,6 @@ class FrontEndActivity : ComponentActivity() {
private const val SESSION_SWITCH_WAIT_MS = 30_000L
private const val SESSION_SWITCH_POLL_MS = 250L
private const val KEY_PENDING_SWITCH = "pending_switch"
private const val KEY_COMPAT_LAUNCH = "compat_launch"
private const val KEY_COMPAT_MENU_INSTALL = "compat_menu_install"
private const val KEY_COMPAT_PROBLEM = "compat_problem"
private const val KEY_SWITCHING_TO = "switching_to"
private const val KEY_SWITCH_DEADLINE = "switch_deadline"
private val SESSION_ENDED = setOf(SessionPhase.IDLE, SessionPhase.FAILED)
@@ -20,19 +20,10 @@ internal class ProtonMenu(
private val ui: Handler,
private val idle: () -> Boolean = { true },
) {
// Install workers and their results outlive the activity that starts them.
private object Operation {
val rows = mutableStateOf<List<ProtonRow>>(emptyList())
val busyId = mutableStateOf<String?>(null)
val stage = mutableStateOf<String?>(null)
val percent = mutableIntStateOf(-1)
val problem = mutableStateOf<String?>(null)
}
var protonRows by Operation.rows
var protonBusyId by Operation.busyId
var protonStage by Operation.stage
var protonPercent by Operation.percent
var protonProblem by Operation.problem
var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
var protonBusyId by mutableStateOf<String?>(null)
var protonStage by mutableStateOf<String?>(null)
var protonPercent by mutableIntStateOf(-1)
private val checking = java.util.concurrent.atomic.AtomicBoolean(false)
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
{ tool, progress -> ProtonExtras.install(activity, tool, progress) }
@@ -42,7 +33,6 @@ internal class ProtonMenu(
if (protonBusyId != null || ProtonExtras.installInProgress || SessionState.running) return
ProtonExtras.unqueue(activity, tool)
protonBusyId = id
protonProblem = null
protonStage = activity.getString(R.string.store_starting)
protonPercent = -1
Thread({
@@ -53,7 +43,6 @@ internal class ProtonMenu(
}.getOrElse { it.message ?: it.javaClass.simpleName }
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
ui.post {
protonProblem = problem
protonBusyId = null
protonStage = null
protonPercent = -1
@@ -71,7 +60,6 @@ internal class ProtonMenu(
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
if (protonBusyId != null || SessionState.running) return
protonBusyId = id
protonProblem = null
protonStage = activity.getString(R.string.main_removing_named, dir ?: tool.name)
protonPercent = -1
Thread({
@@ -110,7 +98,6 @@ internal class ProtonMenu(
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
protonBusyId = ProtonExtras.OWN
protonProblem = null
Thread({
ProtonExtras.tidy(activity)
val tidied = ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size <= 1
@@ -260,8 +260,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val backQamInput = com.droiddeck.launcher.input.BackQamInput(
setPressed = { padBridge?.setBackQamPressed(it) },
onTap = { performBackAction(double = it) },
doubleTapMs = { backDoubleTapMs.toLong() },
onCancel = { padBridge?.cancelBackQam() },
)
private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN
private var drawerDirectionDownTime = 0L
@@ -324,7 +322,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER)
private var drawerControllerActive by mutableStateOf(false)
private var backActionsInverted by mutableStateOf(false)
private var backDoubleTapMs by mutableStateOf(500)
private var lowLatency by mutableStateOf(true)
private var padType by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
private var pcKeyboardOpen by mutableStateOf(false)
@@ -498,6 +495,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
com.droiddeck.launcher.gpu.SteamVrHealth.begin(this, SessionState.sessionId)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
if (!SessionState.running) {
val prefMode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
SessionState.performanceMode = SessionPrefs.performanceMode(this, prefMode)
}
applyOutputPacing()
if (!SessionState.running) SessionState.followScreen = followChoice()
applyFollowOrientation(resources.configuration)
@@ -528,7 +529,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
bridge.setSelectSteam(ControllerPrefs.read(this).selectSteam)
bridge.setBuiltinPad(SessionState.mode != SessionService.MODE_STEAM || SessionPrefs.builtinPad(this))
padBridge = bridge
bridge.setOnChordInput(backQamInput::onChordInput)
SessionState.padBridge = bridge
if (Build.VERSION.SDK_INT >= 31) {
val vr = com.droiddeck.launcher.input.JoyConVr(this, File(filesDir, ".wayland-rt/${com.droiddeck.launcher.input.JoyConVr.FILE}")) { taken, released ->
@@ -553,18 +553,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
uiHandler.removeCallbacks(cursorHide)
cursorVisible = false
}
onScreenControls = OnScreenControls(this, bridge, onKeyboard = ::togglePcKeyboard).also { controls ->
controls.onTouchMiss = miss@{ event ->
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss
event.offsetLocation(controls.left - surfaceView.left.toFloat(), controls.top - surfaceView.top.toFloat())
onTouchEvent(event)
}
root.addView(controls)
}
onScreenControls = OnScreenControls(this, bridge, onKeyboard = ::togglePcKeyboard).also { root.addView(it) }
screenKeysShown = com.droiddeck.launcher.input.ControllerPrefs.screenKeysShown(this)
screenKeys = ScreenKeys(this) { code, down -> if (CompositorHost.isStarted) sendGuestKey(code, down) }.also { keys ->
keys.onTouchMiss = miss@{ event ->
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, event)) return@miss
if (routedTouchMode == SessionPrefs.TOUCH_GESTURES &&
!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, event)) return@miss
event.offsetLocation(keys.left - surfaceView.left.toFloat(), keys.top - surfaceView.top.toFloat())
onTouchEvent(event)
}
@@ -589,7 +583,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// game surface and on-screen buttons, in either finger-down order.
root.isMotionEventSplittingEnabled = true
surfaceView.setOnTouchListener { _, event ->
if (!event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) {
if (routedTouchMode != SessionPrefs.TOUCH_GESTURES) {
gestureTouchStreamGate.reset()
false
} else if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SURFACE, event)) {
false
@@ -1024,11 +1019,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
padType = id
},
backActionsInverted = backActionsInverted,
backDoubleTapMs = backDoubleTapMs,
onBackDoubleTapMs = { ms ->
SessionPrefs.setBackDoubleTapMs(this@SessionActivity, ms)
backDoubleTapMs = ms
},
onBackActionsInverted = { inverted ->
SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted)
backActionsInverted = inverted
@@ -1307,7 +1297,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
performBackAction(double = false)
}
pendingBackAction = pending
uiHandler.postDelayed(pending, backDoubleTapMs.toLong())
uiHandler.postDelayed(pending, 500L)
}
private fun performBackAction(double: Boolean) {
@@ -1641,7 +1631,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
oscMode = SessionPrefs.oscMode(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
backDoubleTapMs = SessionPrefs.backDoubleTapMs(this)
lowLatency = SessionPrefs.lowLatency(this)
padType = SessionPrefs.steamController(this)
}
@@ -1994,7 +1983,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun mirrorRefreshLimit(): Int =
GlassesRendering.mirrorRefreshLimit(glassesSettings, glasses, glassesScreen != null)
private fun outputFpsLimit(): Int = SessionPrefs.compositorFpsLimit(mirrorRefreshLimit())
private fun outputFpsLimit(): Int = SessionPrefs.compositorFpsLimit(
mirrorRefreshLimit(), SessionState.performanceMode,
)
private fun applyOutputPacing() {
Log.i(TAG, "perf: " + PerfMode.apply(this, outputFpsLimit(), mirrorRefreshLimit()))
@@ -2336,7 +2327,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (pipUi) return true
if (event.actionMasked == MotionEvent.ACTION_DOWN && event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) {
drawerControllerActive = false
gestureTouchStreamGate.reset()
}
return super.dispatchTouchEvent(event)
}
@@ -2987,11 +2977,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
uiHandler.postDelayed({ updateOnScreenControls() }, 700)
}
view.onStyle = { screenKeys?.refreshAppearance() }
view.onTouchMiss = miss@{ event ->
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss
event.offsetLocation(view.left - surfaceView.left.toFloat(), view.top - surfaceView.top.toFloat())
onTouchEvent(event)
}
root.addView(view, root.indexOfChild(onScreenControls) + 1)
steamTouchControls = view
steamTouchAvailable = true
@@ -4,8 +4,7 @@ import android.view.KeyEvent
import android.os.Handler
import android.os.Looper
class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap: (Boolean) -> Unit,
private val doubleTapMs: () -> Long = { 500 }, private val onCancel: () -> Unit = {}) {
class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap: (Boolean) -> Unit) {
private class Press(val hold: Runnable, var held: Boolean = false, var used: Boolean = false)
private val handler = Handler(Looper.getMainLooper())
private val presses = mutableMapOf<Int, Press>()
@@ -18,18 +17,6 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
tapPending = false
}
fun onChordInput() {
if (presses.isEmpty()) return
val alreadyHeld = presses.values.any { it.held }
presses.values.forEach {
handler.removeCallbacks(it.hold)
it.held = true
it.used = true
}
cancelTap()
if (!alreadyHeld) setPressed(true)
}
fun onKeyEvent(event: KeyEvent, enabled: Boolean): Boolean {
if (!enabled) cancel()
if (event.keyCode != KeyEvent.KEYCODE_BACK) return false
@@ -61,7 +48,7 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
if (press.held && presses.values.none { it.held }) setPressed(false)
if (!press.used && !event.isCanceled) {
if (tapPending) { cancelTap(); onTap(true) }
else { tapPending = true; handler.postDelayed(singleTap, doubleTapMs()) }
else { tapPending = true; handler.postDelayed(singleTap, 500) }
} else if (event.isCanceled) cancelTap()
}
press != null || wasCancelled || enabled
@@ -76,7 +63,6 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
presses.values.forEach { handler.removeCallbacks(it.hold) }
cancelled.addAll(presses.keys)
presses.clear()
onCancel()
if (wasHeld) setPressed(false)
}
@@ -85,9 +71,6 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
val press = presses.remove(device) ?: return
handler.removeCallbacks(press.hold)
cancelTap()
if (press.held && presses.values.none { it.held }) {
onCancel()
setPressed(false)
}
if (press.held && presses.values.none { it.held }) setPressed(false)
}
}
@@ -4,7 +4,7 @@ import android.view.MotionEvent
/** Keeps split Android touch targets from restarting one shared gesture recognizer. */
internal class GestureTouchStreamGate {
enum class Source { SURFACE, SCREEN_KEYS, ON_SCREEN_CONTROLS }
enum class Source { SURFACE, SCREEN_KEYS }
private var owner: Source? = null
@@ -96,8 +96,6 @@ class OnScreenControls(
private var quickHidden = false
private var quickPressedBy = -1
private var keyboardPressedBy = -1
private var forwardedPointerBits = 0
var onTouchMiss: ((MotionEvent) -> Unit)? = null
private var settings = ControllerPrefs.read(context)
private var snap = settings.snap
private var safe = Rect()
@@ -517,9 +515,6 @@ class OnScreenControls(
val index = event.actionIndex
val x = event.getX(index)
val y = event.getY(index)
if (event.actionMasked == MotionEvent.ACTION_DOWN) forwardedPointerBits = 0
if (event.actionMasked == MotionEvent.ACTION_POINTER_DOWN && forwardMiss(event, x, y)) return true
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
if (event.actionMasked == MotionEvent.ACTION_DOWN && keyboardContains(x, y)) {
keyboardPressedBy = event.getPointerId(index)
invalidate()
@@ -547,13 +542,11 @@ class OnScreenControls(
return true
}
MotionEvent.ACTION_MOVE -> {
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
if (keyboardPressedBy != -1) return true
if (quickPressedBy != -1) return true
var changed = false
for (index in 0 until event.pointerCount) {
val pointer = event.getPointerId(index)
if (forwardedPointerBits and (1 shl pointer) != 0) continue
val x = event.getX(index)
val y = event.getY(index)
val stick = controls.firstOrNull { it.stick >= 0 && it.pressedBy == pointer }
@@ -575,16 +568,10 @@ class OnScreenControls(
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> {
val pointer = event.getPointerId(event.actionIndex)
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
if (event.actionMasked == MotionEvent.ACTION_CANCEL) {
forwardedPointerBits = 0
releaseAll()
return true
}
if (forwardedPointerBits and (1 shl pointer) != 0) {
forwardedPointerBits = forwardedPointerBits and (1 shl pointer).inv()
return true
}
if (keyboardPressedBy == pointer) {
val tapped = event.actionMasked == MotionEvent.ACTION_UP && keyboardContains(event.x, event.y)
keyboardPressedBy = -1
@@ -617,23 +604,6 @@ class OnScreenControls(
return false
}
private fun forwardMiss(event: MotionEvent, x: Float, y: Float): Boolean {
if (onTouchMiss == null || keyboardPressedBy != -1 || quickPressedBy != -1) return false
if (!quickHidden && (controlAt(x, y) ?: adaptiveStickAt(x, y)) != null) return false
forwardedPointerBits = forwardedPointerBits or (1 shl event.getPointerId(event.actionIndex))
forwardPointers(event, forwardedPointerBits)
return true
}
private fun forwardPointers(event: MotionEvent, pointerIdBits: Int) {
val split = event.pointerSubset(pointerIdBits) ?: return
try {
onTouchMiss?.invoke(split)
} finally {
split.recycle()
}
}
private fun onEditTouch(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
@@ -62,18 +62,12 @@ public final class PadBridge {
private boolean systemGuidePressed;
private boolean systemQamPressed;
private boolean backQamPressed;
private final PadState lastBackQamReport = new PadState();
private final PadState lastWrittenReport = new PadState();
private boolean backQamAxesBlocked;
private final java.util.Set<Runnable> backQamWrites = new java.util.HashSet<>();
private long backQamDelayMs, backQamWriteAt;
private boolean qamChordActive;
private int chordButton = -1;
private boolean chordButtonPressed;
private boolean qamTapPressed;
private int qamChordGeneration;
private volatile Runnable onPlayerInput;
private Runnable onChordInput;
private final java.util.concurrent.atomic.AtomicBoolean playerInputPosted = new java.util.concurrent.atomic.AtomicBoolean();
private static final long STATS_WINDOW_MS = 10_000;
@@ -136,7 +130,6 @@ public final class PadBridge {
}
private void resetBuiltin() {
clearBackQamWrites();
routedTouch.clear();
systemGuidePressed = false;
systemQamPressed = false;
@@ -159,7 +152,6 @@ public final class PadBridge {
}
public synchronized void stop() {
clearBackQamWrites();
releaseBackPaddles();
activeControllerId = NO_CONTROLLER;
for (int slot = 0; slot < SLOTS; slot++) {
@@ -284,14 +276,6 @@ public final class PadBridge {
onPlayerInput = listener;
}
public synchronized void setOnChordInput(Runnable listener) {
onChordInput = listener;
}
private void noteChordInput(int slot) {
if (slot == 0 && onChordInput != null) onChordInput.run();
}
private void notePlayerInput() {
Runnable listener = onPlayerInput;
if (listener == null || !playerInputPosted.compareAndSet(false, true)) return;
@@ -342,7 +326,6 @@ public final class PadBridge {
default: return false;
}
noteDevice(event.getDevice(), slot);
if (pressed && event.getRepeatCount() == 0 && !event.isCanceled()) noteChordInput(slot);
if (pressed) notePlayerInput();
statButtons++;
scheduleStats();
@@ -372,7 +355,6 @@ public final class PadBridge {
pad.rightX = x;
pad.rightY = y;
}
if (x != 0f || y != 0f) noteChordInput(slot);
if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) notePlayerInput();
publish(slot);
return true;
@@ -403,8 +385,6 @@ public final class PadBridge {
pad.up = hatY < -0.5f;
pad.down = hatY > 0.5f;
}
if (pad.leftX != 0f || pad.leftY != 0f || pad.rightX != 0f || pad.rightY != 0f
|| lt > 0f || rt > 0f || pad.up || pad.right || pad.down || pad.left) noteChordInput(slot);
if (Math.max(Math.max(Math.abs(pad.leftX), Math.abs(pad.leftY)), Math.max(Math.abs(pad.rightX), Math.abs(pad.rightY))) > 0.5f
|| lt > 0.5f || rt > 0.5f || pad.up || pad.right || pad.down || pad.left) {
notePlayerInput();
@@ -481,7 +461,6 @@ public final class PadBridge {
}
public synchronized void releaseAll() {
clearBackQamWrites();
routedTouch.clear();
backQamPressed = false;
releaseBackPaddles();
@@ -512,108 +491,9 @@ public final class PadBridge {
if (pressed && !canHoldQam()) return;
if (backQamPressed == pressed) return;
backQamPressed = pressed;
if (pressed && (open || start())) {
backQamAxesBlocked = false;
long now = android.os.SystemClock.uptimeMillis();
long modifierAt = Math.max(now, backQamWriteAt);
backQamDelayMs = modifierAt - now + QAM_GUIDE_LEAD_MIN_MS;
PadState modifier = new PadState();
modifier.copyFrom(lastBackQamReport);
modifier.press(PadState.QAM, true);
writeBackQamReport(modifier, modifierAt);
}
if (!pressed) {
backQamAxesBlocked = hasAxes(state);
if (!backQamWrites.isEmpty()) {
PadState neutral = new PadState();
neutral.copyFrom(lastWrittenReport);
clearAxes(neutral);
writer.writePad(neutral);
lastWrittenReport.copyFrom(neutral);
}
}
publish();
}
public synchronized void cancelBackQam() {
if (!backQamPressed && backQamWrites.isEmpty()) return;
clearBackQamWrites();
backQamPressed = false;
state.clear();
publish();
}
private void clearBackQamWrites() {
for (Runnable pending : backQamWrites) mainHandler.removeCallbacks(pending);
backQamWrites.clear();
backQamDelayMs = backQamWriteAt = 0;
lastBackQamReport.clear();
lastWrittenReport.clear();
backQamAxesBlocked = false;
}
private void writeBackQamReport(PadState report, long at) {
lastBackQamReport.copyFrom(report);
if (backQamWrites.isEmpty() && at <= android.os.SystemClock.uptimeMillis()) {
writeReport(report, false);
return;
}
PadState queued = new PadState();
queued.copyFrom(report);
Runnable pending = new Runnable() {
@Override public void run() {
synchronized (PadBridge.this) {
if (!backQamWrites.remove(this)) return;
writeReport(queued, true);
if (backQamWrites.isEmpty() && !hasButtons(lastBackQamReport)) backQamDelayMs = 0;
}
}
};
backQamWrites.add(pending);
backQamWriteAt = at;
mainHandler.postAtTime(pending, at);
}
private void writePad(PadState report) {
if (backQamAxesBlocked && !hasAxes(state)) backQamAxesBlocked = false;
long at = android.os.SystemClock.uptimeMillis();
// Steam must see the modifier before a partner; preserve quick press/release pairs in order.
if (backQamPressed || !backQamWrites.isEmpty()) at += backQamDelayMs;
writeBackQamReport(report, at);
}
private static boolean hasAxes(PadState pad) {
return pad.leftX != 0f || pad.leftY != 0f || pad.rightX != 0f || pad.rightY != 0f
|| pad.leftTrigger != 0f || pad.rightTrigger != 0f;
}
private static void clearAxes(PadState pad) {
pad.leftX = pad.leftY = pad.rightX = pad.rightY = pad.leftTrigger = pad.rightTrigger = 0f;
}
private static boolean hasButtons(PadState pad) {
for (int i = 0; i < 10; i++) if (pad.isDown(i)) return true;
return pad.isDown(PadState.GUIDE) || pad.up || pad.right || pad.down || pad.left;
}
private void writeReport(PadState report, boolean queued) {
if (!queued && !backQamAxesBlocked) {
lastWrittenReport.copyFrom(report);
writer.writePad(report);
return;
}
PadState live = new PadState();
live.copyFrom(report);
if (queued) {
live.leftX = state.leftX; live.leftY = state.leftY;
live.rightX = state.rightX; live.rightY = state.rightY;
live.leftTrigger = state.leftTrigger; live.rightTrigger = state.rightTrigger;
}
if ((queued && (!backQamPressed || !report.isDown(PadState.QAM))) || backQamAxesBlocked) clearAxes(live);
lastWrittenReport.copyFrom(live);
writer.writePad(live);
}
public synchronized void triggerQam() {
if (!builtinPad) return;
if (!nativeQam()) {
@@ -692,9 +572,7 @@ public final class PadBridge {
slotJoyCons.set(slot * 2 + side, id);
slotJoyCons.set(slot * 2 + 1 - side, owner.getId());
if (slot == firstPlayerSlot()) releaseBackPaddles();
if (slot == 0) clearBackQamWrites();
stateFor(slot).clear();
if (slot == 0) publish();
Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") joins \"" + owner.getName() + "\" as player " + (slot + 1));
return slot;
}
@@ -729,7 +607,6 @@ public final class PadBridge {
}
private void leave(int slot, int id) {
if (slot == 0) clearBackQamWrites();
if (partners[slot] == NO_CONTROLLER) {
free(slot);
return;
@@ -824,14 +701,14 @@ public final class PadBridge {
boolean guide = systemGuidePressed || qamChordActive;
boolean qam = nativeQam() && (systemQamPressed || qamTapPressed || backQamPressed);
if (!guide && !qam) {
writePad(state);
writer.writePad(state);
return;
}
effectiveState.copyFrom(state);
if (guide) effectiveState.press(PadState.GUIDE, true);
if (qam) effectiveState.press(PadState.QAM, true);
if (chordButtonPressed) effectiveState.press(chordButton, true);
writePad(effectiveState);
writer.writePad(effectiveState);
}
public static boolean wiredXboxLayout(MotionEvent event) {
@@ -1,35 +0,0 @@
package com.droiddeck.launcher.input
import android.view.MotionEvent
internal fun MotionEvent.pointerSubset(pointerIdBits: Int): MotionEvent? {
val indices = (0 until pointerCount).filter { index ->
pointerIdBits and (1 shl getPointerId(index)) != 0
}
if (indices.isEmpty()) return null
val splitIndex = indices.indexOf(actionIndex)
val splitAction = when (actionMasked) {
MotionEvent.ACTION_DOWN -> if (splitIndex >= 0) MotionEvent.ACTION_DOWN else MotionEvent.ACTION_MOVE
MotionEvent.ACTION_POINTER_DOWN -> if (splitIndex >= 0) {
if (indices.size == 1) MotionEvent.ACTION_DOWN
else MotionEvent.ACTION_POINTER_DOWN or (splitIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
} else MotionEvent.ACTION_MOVE
MotionEvent.ACTION_UP -> if (splitIndex >= 0) MotionEvent.ACTION_UP else MotionEvent.ACTION_MOVE
MotionEvent.ACTION_POINTER_UP -> if (splitIndex >= 0) {
if (indices.size == 1) MotionEvent.ACTION_UP
else MotionEvent.ACTION_POINTER_UP or (splitIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
} else MotionEvent.ACTION_MOVE
else -> action
}
val properties = Array(indices.size) { MotionEvent.PointerProperties() }
val coordinates = Array(indices.size) { MotionEvent.PointerCoords() }
indices.forEachIndexed { target, index ->
getPointerProperties(index, properties[target])
getPointerCoords(index, coordinates[target])
}
return MotionEvent.obtain(
downTime, eventTime, splitAction, indices.size, properties, coordinates,
metaState, buttonState, xPrecision, yPrecision,
deviceId, edgeFlags, source, flags,
)
}
@@ -926,7 +926,35 @@ class ScreenKeys(context: Context, private val sendKey: (Int, Boolean) -> Unit)
}
private fun forwardPointers(event: MotionEvent, pointerIdBits: Int) {
val split = event.pointerSubset(pointerIdBits) ?: return
val indices = (0 until event.pointerCount).filter { index ->
pointerIdBits and (1 shl event.getPointerId(index)) != 0
}
if (indices.isEmpty()) return
val actionIndex = indices.indexOf(event.actionIndex)
val action = when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> if (actionIndex >= 0) MotionEvent.ACTION_DOWN else MotionEvent.ACTION_MOVE
MotionEvent.ACTION_POINTER_DOWN -> if (actionIndex >= 0) {
if (indices.size == 1) MotionEvent.ACTION_DOWN
else MotionEvent.ACTION_POINTER_DOWN or (actionIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
} else MotionEvent.ACTION_MOVE
MotionEvent.ACTION_UP -> if (actionIndex >= 0) MotionEvent.ACTION_UP else MotionEvent.ACTION_MOVE
MotionEvent.ACTION_POINTER_UP -> if (actionIndex >= 0) {
if (indices.size == 1) MotionEvent.ACTION_UP
else MotionEvent.ACTION_POINTER_UP or (actionIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
} else MotionEvent.ACTION_MOVE
else -> event.action
}
val properties = Array(indices.size) { MotionEvent.PointerProperties() }
val coordinates = Array(indices.size) { MotionEvent.PointerCoords() }
indices.forEachIndexed { target, source ->
event.getPointerProperties(source, properties[target])
event.getPointerCoords(source, coordinates[target])
}
val split = MotionEvent.obtain(
event.downTime, event.eventTime, action, indices.size, properties, coordinates,
event.metaState, event.buttonState, event.xPrecision, event.yPrecision,
event.deviceId, event.edgeFlags, event.source, event.flags,
)
try {
onTouchMiss?.invoke(split)
} finally {
@@ -103,8 +103,6 @@ class SteamTouchControls(
private class Finger(val element: Element?, var x: Float, var y: Float, val toolbar: Int = -1)
private val fingers = HashMap<Int, Finger>()
private var forwardedPointerBits = 0
var onTouchMiss: ((MotionEvent) -> Unit)? = null
private var editing = false
private var editElements: MutableList<Element> = mutableListOf()
@@ -631,17 +629,7 @@ class SteamTouchControls(
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
val x = event.getX(index)
val y = event.getY(index)
if (event.actionMasked == MotionEvent.ACTION_DOWN) forwardedPointerBits = 0
val e = hit(live(), x, y)
if (e == null) {
if (event.actionMasked == MotionEvent.ACTION_DOWN) return false
if (onTouchMiss != null) {
forwardedPointerBits = forwardedPointerBits or (1 shl event.getPointerId(index))
forwardPointers(event, forwardedPointerBits)
}
return true
}
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
val e = hit(live(), x, y) ?: return event.actionMasked == MotionEvent.ACTION_POINTER_DOWN
fingers[event.getPointerId(index)] = Finger(e, x, y)
if (feedback) performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY)
requestUnbufferedDispatch(event)
@@ -649,7 +637,6 @@ class SteamTouchControls(
return true
}
MotionEvent.ACTION_MOVE -> {
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
for (i in 0 until event.pointerCount) {
val f = fingers[event.getPointerId(i)] ?: continue
f.x = event.getX(i)
@@ -668,14 +655,12 @@ class SteamTouchControls(
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> {
val id = event.getPointerId(index)
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
forwardedPointerBits = if (event.actionMasked == MotionEvent.ACTION_CANCEL) 0 else forwardedPointerBits and (1 shl id).inv()
val f = fingers.remove(id)
if (event.actionMasked == MotionEvent.ACTION_CANCEL) fingers.clear()
val e = f?.element
if (event.actionMasked != MotionEvent.ACTION_CANCEL && e != null && reach(e, event.getX(index), event.getY(index)) <= 1.3f) {
when (e.type) {
SteamTouchConfig.THUMB -> { cancelForwarded(event); openMenu() }
SteamTouchConfig.THUMB -> openMenu()
SteamTouchConfig.KEYBOARD -> onKeyboard()
SteamTouchConfig.PASTE -> onPaste()
}
@@ -688,25 +673,6 @@ class SteamTouchControls(
}
private fun cancelForwarded(event: MotionEvent) {
val split = event.pointerSubset(forwardedPointerBits).also { forwardedPointerBits = 0 } ?: return
split.action = MotionEvent.ACTION_CANCEL
try {
onTouchMiss?.invoke(split)
} finally {
split.recycle()
}
}
private fun forwardPointers(event: MotionEvent, pointerIdBits: Int) {
val split = event.pointerSubset(pointerIdBits) ?: return
try {
onTouchMiss?.invoke(split)
} finally {
split.recycle()
}
}
val isEditing get() = editing
fun startEditing() {
@@ -255,16 +255,6 @@ object SessionPrefs {
prefs(context).edit().putBoolean("backActionsInverted", inverted).apply()
}
val BACK_DOUBLE_TAP_MS_OPTIONS = (100..800 step 100).toList()
fun backDoubleTapMs(context: Context): Int =
prefs(context).getInt("backDoubleTapMs", 500).takeIf { it in BACK_DOUBLE_TAP_MS_OPTIONS } ?: 500
fun setBackDoubleTapMs(context: Context, ms: Int) {
require(ms in BACK_DOUBLE_TAP_MS_OPTIONS)
prefs(context).edit().putInt("backDoubleTapMs", ms).apply()
}
const val TOUCH_AUTO = "auto"
const val TOUCH_PAD = "touchpad"
const val TOUCH_DIRECT = "direct"
@@ -938,15 +928,22 @@ object SessionPrefs {
prefs(context).edit().putBoolean("hdr.$mode", on).apply()
}
/**
* Performance mode: buffers go back to the game as soon as they are replaced
* instead of once per refresh, and gamescope's WSI layer and winex11 reuse their per-present window checks.
*/
fun performanceMode(context: Context, mode: String): Boolean = prefs(context).getBoolean("performanceMode.$mode", false)
fun setPerformanceMode(context: Context, mode: String, on: Boolean) {
prefs(context).edit().putBoolean("performanceMode.$mode", on).apply()
}
/** Compositor frame limit that releases buffers to the game unpaced. */
const val FPS_UNPACED = -1
/**
* Buffers go back to the game as soon as they are replaced instead of once per refresh;
* Steam's Frame Limit in the Quick Access menu caps games. Mirroring still follows the glasses' refresh rate.
*/
fun compositorFpsLimit(mirrorRefreshLimit: Int): Int =
if (mirrorRefreshLimit <= 0) FPS_UNPACED else mirrorRefreshLimit
/** Mirroring still follows the glasses' refresh rate when Performance mode is on. */
fun compositorFpsLimit(mirrorRefreshLimit: Int, performanceMode: Boolean): Int =
if (performanceMode && mirrorRefreshLimit <= 0) FPS_UNPACED else mirrorRefreshLimit
val upscalerChoices = listOf(
0 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
@@ -507,13 +507,16 @@ class SessionService : Service() {
guest.add("DXVK_HDR=1")
Log.i(TAG, "hdr: gamescope --hdr-enabled, DXVK_HDR=1")
}
// gamescope's WSI layer and winex11 reuse their per-present window checks for this long.
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=100")
guest.add("WINE_OFFSCREEN_CHECK_MS=100")
// gamescope turns buffers around slower than an uncapped game draws; more images keep it drawing.
// The WSI layer goes back to its default count while Steam's Frame Limit holds the game.
guest.add("GAMESCOPE_WSI_MIN_IMAGE_COUNT=8")
guest.add("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=1")
// gamescope's WSI layer and winex11 reuse their per-present window checks for this long; 0 checks on every present.
val windowCheckMs = if (SessionState.performanceMode) 100 else 0
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=$windowCheckMs")
guest.add("WINE_OFFSCREEN_CHECK_MS=$windowCheckMs")
if (SessionState.performanceMode) {
// gamescope turns buffers around slower than an unpaced game draws; more images keep it drawing.
guest.add("GAMESCOPE_WSI_MIN_IMAGE_COUNT=8")
guest.add("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=1")
}
Log.i(TAG, "performance mode " + (if (SessionState.performanceMode) "on" else "off"))
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
guest.add("BL_LOG=" + sessionLog.path)
guest.add("BL_DEBUG_DIR=" + sessionDir.path)
@@ -103,6 +103,9 @@ object SessionState {
@Volatile
var upscaleRatio: Float = 0f
@Volatile
var performanceMode = false
@Volatile
var firstFrameSeen = false
@@ -14,7 +14,7 @@ object SettingsReset {
"orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "addedGamesArt",
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "backActionsInverted", "touch", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "picturePosition",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
@@ -0,0 +1,136 @@
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<String, CompletableFuture<JSONObject>>()
private val nextId = AtomicLong(1)
private val listeners = java.util.concurrent.CopyOnWriteArrayList<(String, JSONObject) -> Unit>()
/** The core runs in the :gfn process; other processes reach it through [GfnCoreService]. */
private val inCoreProcess: Boolean by lazy {
val name = if (android.os.Build.VERSION.SDK_INT >= 28) android.app.Application.getProcessName()
else runCatching { File("/proc/self/cmdline").readText().trimEnd('\u0000') }.getOrDefault("")
name.endsWith(":gfn")
}
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 (!inCoreProcess) return GfnRemote.request(context, method, params, timeoutMs)
if (method != "core.hello") ensureStarted(context)
val id = "dd-" + nextId.getAndIncrement()
val answer = CompletableFuture<JSONObject>()
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")) }
}
}
@@ -0,0 +1,100 @@
package com.droiddeck.launcher.stores.gfn
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Binder
import android.os.IBinder
import android.os.Parcel
import android.os.Process
import android.os.RemoteException
import org.json.JSONObject
/**
* Hosts the one OpenNOW core in the :gfn process (the core locks its data directory, so a second
* copy cannot run) and answers core requests from the Stores page in the main process.
*/
class GfnCoreService : Service() {
private val binder = object : Binder() {
override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean {
if (code != REQUEST) return super.onTransact(code, data, reply, flags)
if (getCallingUid() != Process.myUid() || reply == null) return false
val method = data.readString().orEmpty()
val params = runCatching { JSONObject(data.readString() ?: "{}") }.getOrDefault(JSONObject())
val timeoutMs = data.readLong()
try {
val result = GfnCore.request(applicationContext, method, params, timeoutMs)
reply.writeInt(1)
reply.writeString(result.toString())
} catch (e: Exception) {
reply.writeInt(0)
reply.writeString(JSONObject().put("code", (e as? GfnError)?.code ?: "error")
.put("message", e.message ?: "GeForce NOW request failed ($method)").toString())
}
return true
}
}
override fun onBind(intent: Intent?): IBinder = binder
companion object {
const val REQUEST = IBinder.FIRST_CALL_TRANSACTION
}
}
/** The main process's side of [GfnCoreService]. Blocking: call off the main thread. */
internal object GfnRemote {
private val lock = Object()
@Volatile private var binder: IBinder? = null
private var bound = false
private val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
synchronized(lock) { binder = service; lock.notifyAll() }
}
override fun onServiceDisconnected(name: ComponentName?) { binder = null }
override fun onBindingDied(name: ComponentName?) { synchronized(lock) { binder = null; bound = false } }
}
fun request(context: Context, method: String, params: JSONObject, timeoutMs: Long): JSONObject {
val service = connect(context)
val data = Parcel.obtain()
val reply = Parcel.obtain()
try {
data.writeString(method)
data.writeString(params.toString())
data.writeLong(timeoutMs)
if (!service.transact(GfnCoreService.REQUEST, data, reply, 0))
throw GfnError("core_stopped", "The GeForce NOW service refused the request")
val ok = reply.readInt() == 1
val body = reply.readString() ?: "{}"
if (ok) return JSONObject(body)
val error = JSONObject(body)
throw GfnError(error.optString("code").ifEmpty { "error" }, error.optString("message"))
} catch (e: RemoteException) {
binder = null
throw GfnError("core_stopped", "The GeForce NOW service stopped")
} finally {
data.recycle()
reply.recycle()
}
}
private fun connect(context: Context): IBinder {
synchronized(lock) {
binder?.takeIf { it.isBinderAlive }?.let { return it }
val app = context.applicationContext
if (!bound) bound = app.bindService(Intent(app, GfnCoreService::class.java), connection, Context.BIND_AUTO_CREATE)
if (!bound) throw GfnError("core_stopped", "The GeForce NOW service could not start")
val deadline = System.currentTimeMillis() + 15_000
while (binder?.isBinderAlive != true) {
val left = deadline - System.currentTimeMillis()
if (left <= 0) throw GfnError("timeout", "The GeForce NOW service did not start")
lock.wait(left)
}
return binder!!
}
}
}
@@ -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<JSONObject>()
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<Pad>(4)
private val byDevice = HashMap<Int, Pad>()
@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<Int, Int> {
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)
}
}
}
@@ -0,0 +1,367 @@
package com.droiddeck.launcher.stores.gfn
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
data class GfnGame(val id: String, val variantId: String, val title: String, val store: String,
val imageUrl: String, val inLibrary: Boolean, val search: String)
data class GfnStoreAccount(val provider: String, val label: String, val displayName: String, val connected: Boolean,
val status: String, val syncState: String, val canLink: Boolean, val canSync: Boolean)
/**
* The GeForce NOW tab on the Stores page: NVIDIA sign-in, the store catalog, the account's library
* and its connected stores, all through OpenNOW's core. Kept here so it survives switching tabs.
*/
object GfnState {
sealed interface Phase {
data object Loading : Phase
data class SignedOut(val error: String? = null) : Phase
data class Code(val userCode: String, val url: String, val attemptId: String, val intervalMs: Long) : Phase
data class SignedIn(val user: String) : Phase
data class Failed(val message: String) : Phase
}
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
var phase by mutableStateOf<Phase>(Phase.Loading)
private set
private var started = false
private var signInJob: Job? = null
var storeGames by mutableStateOf(emptyList<GfnGame>())
private set
var storeTotal by mutableStateOf(0)
private set
var storeLoading by mutableStateOf(false)
private set
var storeError by mutableStateOf<String?>(null)
private set
private var storeQuery = ""
private var storeNext = ""
private var storeMore = true
private var storeGeneration = 0
private var storeJob: Job? = null
var library by mutableStateOf<List<GfnGame>?>(null)
private set
var libraryError by mutableStateOf<String?>(null)
private set
private var libraryJob: Job? = null
var accounts by mutableStateOf<List<GfnStoreAccount>?>(null)
private set
var accountsMessage by mutableStateOf<String?>(null)
private set
var accountsBusy by mutableStateOf(false)
private set
/** Loads the sign-in state once; [force] checks again (Try again). */
fun start(context: Context, force: Boolean = false) {
if (started && !force) return
started = true
val app = context.applicationContext
phase = Phase.Loading
scope.launch { phase = withContext(Dispatchers.IO) { loadSignedIn(app) } }
}
fun signIn(context: Context) {
val app = context.applicationContext
signInJob?.cancel()
signInJob = scope.launch {
val code = withContext(Dispatchers.IO) { runCatching { startSignIn(app) } }
.getOrElse { phase = Phase.SignedOut(it.message); return@launch }
phase = code
phase = waitForSignIn(app, code)
}
}
fun cancelSignIn() {
signInJob?.cancel()
phase = Phase.SignedOut()
}
fun signOut(context: Context) {
val app = context.applicationContext
signInJob?.cancel()
scope.launch {
withContext(Dispatchers.IO) { runCatching { GfnCore.request(app, "auth.logout") } }
clearAccountData()
phase = Phase.SignedOut()
}
}
private fun clearAccountData() {
storeJob?.cancel(); libraryJob?.cancel()
storeGames = emptyList(); storeTotal = 0; storeNext = ""; storeMore = true; storeError = null; storeLoading = false
library = null; libraryError = null
accounts = null; accountsMessage = null
}
/** Shows the store for [query]: loads it when the query changed or nothing is loaded yet. */
fun showStore(context: Context, query: String) {
if (query.trim() != storeQuery || (storeGames.isEmpty() && !storeLoading && storeError == null)) loadStore(context, query, reset = true)
}
/** NVIDIA's signed-in store catalog, a page at a time; a new [query] starts over. */
fun loadStore(context: Context, query: String, reset: Boolean) {
val text = query.trim()
if (!reset && (storeLoading || !storeMore || text != storeQuery)) return
val app = context.applicationContext
storeGeneration += 1
val asked = storeGeneration
storeQuery = text
if (reset) { storeNext = ""; storeMore = true }
val cursor = storeNext
storeLoading = true
storeJob?.cancel()
storeJob = scope.launch {
if (reset && text.isNotEmpty()) delay(350)
val page = withContext(Dispatchers.IO) { runCatching { storePage(app, cursor, text) } }
if (asked != storeGeneration) return@launch
storeLoading = false
page.onSuccess {
storeError = null
val seen = if (reset) HashSet() else storeGames.map { game -> game.id }.toHashSet()
storeGames = (if (reset) emptyList() else storeGames) + it.games.filter { game -> seen.add(game.id) }
storeNext = it.next
storeMore = it.more
storeTotal = maxOf(it.total, storeGames.size)
}.onFailure { storeError = it.message ?: "The GeForce NOW store did not answer." }
}
}
fun loadLibrary(context: Context, force: Boolean = false) {
if (!force && (library != null || libraryJob?.isActive == true)) return
val app = context.applicationContext
if (force) library = null
libraryError = null
libraryJob?.cancel()
libraryJob = scope.launch {
withContext(Dispatchers.IO) { runCatching { libraryGames(app) } }
.onSuccess { library = it.sortedBy { game -> game.title.lowercase() } }
.onFailure { libraryError = it.message ?: "Your GeForce NOW library could not be loaded." }
}
}
fun loadAccounts(context: Context) {
val app = context.applicationContext
scope.launch {
withContext(Dispatchers.IO) { runCatching { storeAccounts(app) } }
.onSuccess { accounts = it }
.onFailure { accountsMessage = it.message ?: "Connected stores could not be loaded." }
}
}
fun link(context: Context, account: GfnStoreAccount) = perform(context) { app -> linkStore(app, account) }
fun sync(context: Context, account: GfnStoreAccount) = perform(context) { app -> syncStore(app, account) }
fun unlink(context: Context, account: GfnStoreAccount) = perform(context) { app ->
withContext(Dispatchers.IO) {
GfnCore.request(app, "account.connections.unlink", JSONObject().put("provider", account.provider))
.optString("message").ifEmpty { "${account.label} disconnected." }
}
}
private fun perform(context: Context, action: suspend (Context) -> String) {
if (accountsBusy) return
val app = context.applicationContext
accountsBusy = true
scope.launch {
accountsMessage = runCatching { action(app) }.getOrElse { it.message ?: "That did not work. Try again." }
accountsBusy = false
loadAccounts(app)
loadLibrary(app, force = true)
}
}
fun play(context: Context, game: GfnGame) {
context.startActivity(Intent(context, GfnPlayerActivity::class.java)
.apply { if (context !is android.app.Activity) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }
.putExtra(GfnPlayerActivity.EXTRA_APP_ID, game.id)
.putExtra(GfnPlayerActivity.EXTRA_VARIANT_ID, game.variantId)
.putExtra(GfnPlayerActivity.EXTRA_TITLE, game.title))
}
/** OpenNOW's own rule for which action a connected-store row offers. */
fun actionFor(account: GfnStoreAccount): String = when {
account.canLink && (!account.connected || account.status == "expired" ||
(account.syncState == "SYNC_DENIED" && account.provider != "STEAM")) -> "link"
account.canSync -> "sync"
account.connected && account.canLink -> "unlink"
else -> "none"
}
private fun loadSignedIn(context: Context): Phase = runCatching {
val auth = GfnCore.request(context, "auth.session.get")
val user = auth.optJSONObject("session")?.optJSONObject("user") ?: auth.optJSONObject("user")
if (user == null || user.optString("userId").isEmpty()) return Phase.SignedOut()
Phase.SignedIn(user.optString("displayName").ifEmpty { "Signed in" })
}.getOrElse { Phase.Failed(it.message ?: "GeForce NOW could not start.") }
private fun startSignIn(context: Context): Phase.Code {
val challenge = GfnCore.request(context, "auth.device.start")
return Phase.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(context: Context, code: Phase.Code): Phase {
var interval = code.intervalMs
while (true) {
delay(interval)
val poll = withContext(Dispatchers.IO) {
runCatching { GfnCore.request(context, "auth.device.poll", JSONObject().put("attemptId", code.attemptId)) }
}.getOrElse { return Phase.SignedOut(it.message) }
when (poll.optString("status")) {
"authorized" -> {
withContext(Dispatchers.IO) {
runCatching {
GfnCore.request(context, "auth.device.complete",
JSONObject().put("attemptId", code.attemptId).put("staySignedIn", true))
}
}.onFailure { return Phase.SignedOut(it.message) }
clearAccountData()
return withContext(Dispatchers.IO) { loadSignedIn(context) }
}
"pending", "slow_down" -> interval = poll.optLong("retryAfterMs",
(poll.optDouble("intervalSeconds", interval / 1000.0) * 1000).toLong()).coerceAtLeast(1000)
else -> return Phase.SignedOut(poll.optString("message").ifEmpty { "Sign-in did not finish. Try again." })
}
}
}
private class Page(val games: List<GfnGame>, val next: String, val more: Boolean, val total: Int)
/** Browsing reads the core's local copy of the catalog, which grows a page at a time; a search asks NVIDIA. */
private fun storePage(context: Context, cursor: String, query: String): Page {
val params = JSONObject().put("limit", 40).put("cursor", cursor).put("searchQuery", query)
if (query.isEmpty()) params.put("genre", "").put("store", "").put("categoryId", "").put("refresh", false)
val result = GfnCore.request(context, if (query.isEmpty()) "catalog.store.local" else "catalog.store.list", params, timeoutMs = 60_000)
val games = gamesOf(result)
return Page(games, result.optString("nextCursor"), result.optBoolean("hasNextPage") && result.optString("nextCursor").isNotEmpty(),
result.optInt("totalCount", games.size))
}
/** Pages of 50 keep each answer well under the binder transaction limit. */
private fun libraryGames(context: Context): List<GfnGame> {
val games = LinkedHashMap<String, GfnGame>()
val traversal = System.currentTimeMillis().toString()
var cursor = ""
var revision: Any? = null
var catalogContext = ""
repeat(100) {
val params = JSONObject().put("limit", 50).put("cursor", cursor).put("traversalId", traversal)
.put("catalogRevision", revision ?: JSONObject.NULL).put("catalogContext", catalogContext)
val page = GfnCore.request(context, "catalog.library.list", params, timeoutMs = 60_000)
gamesOf(page).forEach { games.putIfAbsent(it.id, it.copy(inLibrary = true)) }
revision = page.opt("catalogRevision")
catalogContext = page.optString("catalogContext")
cursor = page.optString("nextCursor")
if (!page.optBoolean("hasNextPage") || cursor.isEmpty()) return games.values.toList()
}
return games.values.toList()
}
private fun gamesOf(result: JSONObject): List<GfnGame> {
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)))
GfnGame(id = game.optString("id"),
variantId = variant?.optString("id").orEmpty().ifEmpty { game.optString("launchAppId") },
title = game.optString("title"),
store = storeLabel(variant?.optString("store").orEmpty()),
imageUrl = game.optString("imageUrl"),
inLibrary = game.optBoolean("isInLibrary") || variant?.optBoolean("inLibrary") == true,
search = game.optString("searchText").ifEmpty { game.optString("title").lowercase() })
}.filter { it.id.isNotEmpty() && it.variantId.isNotEmpty() }
}
private fun storeLabel(store: String): String = when (store.uppercase()) {
"STEAM" -> "Steam"
"EPIC" -> "Epic"
"XBOX" -> "Xbox"
"BATTLENET" -> "Battle.net"
"UPLAY", "UBISOFT" -> "Ubisoft"
"GOG" -> "GOG"
"EA_APP", "EA", "ORIGIN" -> "EA"
"GAIJIN" -> "Gaijin"
else -> store.lowercase().replaceFirstChar { it.uppercase() }
}
private fun storeAccounts(context: Context): List<GfnStoreAccount> {
val list = GfnCore.request(context, "account.connections.list").optJSONArray("accounts") ?: return emptyList()
return (0 until list.length()).mapNotNull { index ->
val account = list.optJSONObject(index) ?: return@mapNotNull null
if (account.optString("provider") in setOf("", "UNKNOWN", "NONE", "NVIDIA")) return@mapNotNull null
GfnStoreAccount(provider = account.optString("provider"), label = account.optString("label").ifEmpty { account.optString("provider") },
displayName = account.optString("displayName"),
connected = account.optBoolean("isConnected") || account.optString("status") == "connected",
status = account.optString("status"), syncState = account.optString("syncState"),
canLink = account.optBoolean("supportsLinking"), canSync = account.optBoolean("supportsSync"))
}.filter { it.canLink || it.canSync || it.connected }
}
private suspend fun linkStore(context: Context, account: GfnStoreAccount): String {
val attempt = withContext(Dispatchers.IO) {
GfnCore.request(context, "account.connections.link.start", JSONObject().put("provider", account.provider))
}
val url = attempt.optString("loginUrl")
if (url.isNotEmpty()) runCatching {
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
repeat(150) {
delay(2_000)
val poll = withContext(Dispatchers.IO) {
GfnCore.request(context, "account.connections.link.poll",
JSONObject().put("attemptId", attempt.optString("attemptId")), timeoutMs = 10_000)
}
when (poll.optString("status")) {
"pending" -> {}
"complete" -> return "${account.label} connected."
else -> return poll.optString("message").ifEmpty { "${account.label} was not connected." }
}
}
return "Stopped waiting for ${account.label}. Finish signing in, then refresh."
}
private suspend fun syncStore(context: Context, account: GfnStoreAccount): String = withContext(Dispatchers.IO) {
var state = GfnCore.request(context, "account.connections.sync", JSONObject().put("provider", account.provider))
val operation = state.optString("operationId")
if (operation.isEmpty()) return@withContext state.optString("message").ifEmpty { "${account.label} synced." }
repeat(90) {
when (state.optString("phase")) {
"waiting_remote", "starting" -> {
delay(state.optLong("retryAfterMs", 2_000).coerceAtLeast(2_000))
state = GfnCore.request(context, "account.connections.sync.status", JSONObject().put("operationId", operation))
}
"refreshing_library" -> {
runCatching { libraryGames(context) }
runCatching {
GfnCore.request(context, "account.connections.sync.status",
JSONObject().put("operationId", operation).put("libraryRefreshed", true), timeoutMs = 10_000)
}
return@withContext "${account.label} synced. Your library is up to date."
}
"timed_out" -> return@withContext "The sync could not be confirmed. ${account.label} may still finish; refresh later."
else -> return@withContext "${account.label} could not finish the sync. Try again."
}
}
"Still waiting for ${account.label}; refresh later."
}
}
@@ -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)
}
}
@@ -219,9 +219,6 @@ internal fun GameDetail(
}
}
if (StoresMotion.heroLands) hero() else Rise(1) { hero() }
if (!s.shortcutPicker) Rise(2) {
GameResourcesRow(title.takeUnless { it == id }.orEmpty(), game, Modifier.padding(top = 6.dp))
}
if (tab != null) Rise(2) {
Column(Modifier.fillMaxWidth().padding(top = 14.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
val labels = tabs.map { t ->
@@ -1,90 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.annotation.StringRes
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.OpenInNew
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import java.net.URLEncoder
internal data class GameResource(@StringRes val label: Int, val url: String, @StringRes val detail: Int? = null)
internal fun gameResources(title: String, game: Library.SteamGame?): List<GameResource> {
if (title.isBlank()) return emptyList()
val query = URLEncoder.encode(title.trim(), "UTF-8").replace("+", "%20")
val steamId = game?.takeIf { Library.fromSteamClient(it) && it.appId > 0 }?.appId
return buildList {
add(GameResource(R.string.game_resource_pcgw, "https://www.pcgamingwiki.com/w/index.php?search=$query"))
add(GameResource(R.string.game_resource_guides, "https://gamefaqs.gamespot.com/search?game=$query"))
if (steamId != null) {
add(GameResource(R.string.game_resource_protondb, "https://www.protondb.com/app/$steamId", R.string.game_resource_protondb_detail))
add(GameResource(R.string.game_resource_steam_cloud, "https://store.steampowered.com/account/remotestorageapp/?appid=$steamId", R.string.game_resource_steam_cloud_detail))
}
add(GameResource(R.string.game_resource_search, "https://www.google.com/search?q=$query"))
}
}
@Composable
@OptIn(ExperimentalLayoutApi::class)
internal fun GameResourcesRow(title: String, game: Library.SteamGame?, modifier: Modifier = Modifier) {
val links = remember(title, game) { gameResources(title, game) }
if (links.isEmpty()) return
FlowRow(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
links.forEach { ResourceLink(it) }
}
}
@Composable
private fun ResourceLink(link: GameResource) {
val ctx = LocalContext.current
val pal = LocalPalette.current
val source = remember { MutableInteractionSource() }
val hot = rememberHot(source)
val shape = RoundedCornerShape(8.dp)
val label = stringResource(link.label)
val description = listOfNotNull(label, link.detail?.let { stringResource(it) }, stringResource(R.string.game_resources_browser)).joinToString(". ")
val open = { openUrl(ctx, link.url) }
val tint = if (hot) pal.signal else pal.onSurfaceVariant
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp),
modifier = Modifier.paneItem("resource:${link.label}").heightIn(min = 44.dp).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.08f) else Color.Transparent)
.glideBorder(hot, shape, pal.signal, restColor = Color.Transparent)
.semantics { contentDescription = description }
.hoverable(source).clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = open)
.controllerConfirm(onClick = open).padding(horizontal = 8.dp),
) {
Text(label, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = tint, maxLines = 1)
Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = null, tint = tint.copy(alpha = 0.65f), modifier = Modifier.size(11.dp))
}
}
@@ -0,0 +1,375 @@
package com.droiddeck.launcher.ui
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Login
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
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.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
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.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.gfn.GfnGame
import com.droiddeck.launcher.stores.gfn.GfnState
import com.droiddeck.launcher.stores.gfn.GfnStoreAccount
/** The GeForce NOW tab's chip key; it sits after the store tabs and is not a [com.droiddeck.launcher.stores.Store]. */
internal const val GEFORCE_NOW = "geforce-now"
internal val GfnGreen = Color(0xFF76B900)
internal val GfnColours = SourceColours(Color(0xFF1C2A0A), Color(0xFFCDEB8B), GfnGreen)
internal fun gfnPalette(base: Palette): Palette = Palette(
base.id, base.label, base.detail, base.background, base.surface, base.surfaceVariant, base.line, base.line2,
base.onBackground, base.onSurfaceVariant, primary = GfnGreen, primary2 = Color(0xFF5A8F00), onPrimary = Color(0xFF0B0B0D), signal = GfnGreen,
good = base.good, error = base.error,
)
@Composable
internal fun GfnTheme(content: @Composable () -> Unit) {
val base = LocalPalette.current
val p = remember(base) { gfnPalette(base) }
val scheme = MaterialTheme.colorScheme.copy(primary = p.primary, onPrimary = p.onPrimary)
CompositionLocalProvider(LocalPalette provides p) { MaterialTheme(colorScheme = scheme, typography = MaterialTheme.typography, content = content) }
}
@Composable
internal fun GfnPane(height: Dp) {
val ctx = LocalContext.current
LaunchedEffect(Unit) { GfnState.start(ctx) }
when (val phase = GfnState.phase) {
GfnState.Phase.Loading -> Box(Modifier.fillMaxWidth().padding(top = 16.dp)) {
androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().height(3.dp))
}
is GfnState.Phase.Failed -> Column(verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth().padding(top = 8.dp)) {
Note(phase.message)
PrimaryButton(stringResource(R.string.gfn_try_again), main = true) { GfnState.start(ctx, force = true) }
}
is GfnState.Phase.SignedOut, is GfnState.Phase.Code -> Box(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(top = 4.dp, bottom = 16.dp)) {
GfnSignInCard(phase, height)
}
is GfnState.Phase.SignedIn -> GfnStorefront(phase.user)
}
}
@Composable
private fun GfnSignInCard(phase: GfnState.Phase, height: Dp) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val narrow = LocalNarrowPane.current
val shape = RoundedCornerShape(20.dp)
Box(
Modifier.fillMaxWidth().heightIn(min = height.coerceAtLeast(0.dp)).clip(shape)
.background(Brush.linearGradient(listOf(GfnColours.fill, colors.background))).border(1.dp, pal.line, shape)
.drawBehind {
drawRect(Brush.radialGradient(listOf(GfnGreen.copy(alpha = 0.28f), Color.Transparent), center = Offset(size.width * 0.16f, size.height * 0.9f), radius = size.height * 0.8f))
},
) {
Column(
verticalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.align(Alignment.BottomStart).padding(start = if (narrow) 20.dp else 40.dp, bottom = if (narrow) 20.dp else 36.dp, end = 20.dp, top = 20.dp),
) {
Rise(2) {
Text(
stringResource(R.string.gfn_name), fontSize = if (narrow) 30.sp else 42.sp, lineHeight = if (narrow) 34.sp else 46.sp,
fontWeight = FontWeight.Black, color = colors.onBackground,
)
}
Text(stringResource(R.string.gfn_pitch), fontSize = 15.sp, color = colors.onBackground)
Text(stringResource(R.string.gfn_unofficial), fontSize = 12.sp, color = colors.onSurfaceVariant)
Spacer(Modifier.height(6.dp))
when (phase) {
is GfnState.Phase.Code -> {
Text(stringResource(R.string.gfn_code_hint, phase.url), fontSize = 14.sp, color = colors.onBackground)
Text(phase.userCode, fontSize = 34.sp, fontWeight = FontWeight.Black, letterSpacing = 4.sp, color = GfnGreen)
Actions {
PrimaryButton(stringResource(R.string.gfn_open_page), main = true) { openUrl(ctx, phase.url) }
SecondaryButton(stringResource(R.string.common_cancel)) { GfnState.cancelSignIn() }
}
Text(stringResource(R.string.gfn_code_waiting), fontSize = 12.sp, color = colors.onSurfaceVariant)
}
else -> {
(phase as? GfnState.Phase.SignedOut)?.error?.let { Text(it, fontSize = 13.sp, color = colors.error) }
Rise(3) {
PrimaryButton(stringResource(R.string.stores_signin), main = true, large = true, icon = Icons.AutoMirrored.Filled.Login) { GfnState.signIn(ctx) }
}
}
}
}
}
}
private const val MODE_STORE = 0
private const val MODE_LIBRARY = 1
private const val MODE_ACCOUNTS = 2
@Composable
private fun GfnStorefront(user: String) {
val ctx = LocalContext.current
var mode by rememberSaveable { mutableIntStateOf(MODE_STORE) }
var query by rememberSaveable { mutableStateOf("") }
val grid = rememberLazyGridState()
LaunchedEffect(mode) {
when (mode) {
MODE_LIBRARY -> GfnState.loadLibrary(ctx)
MODE_ACCOUNTS -> GfnState.loadAccounts(ctx)
}
grid.scrollToItem(0)
}
LaunchedEffect(Unit) { GfnState.loadLibrary(ctx) }
LaunchedEffect(mode, query) { if (mode == MODE_STORE) GfnState.showStore(ctx, query) }
val nearEnd by remember {
derivedStateOf {
val last = grid.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0
last >= grid.layoutInfo.totalItemsCount - 10
}
}
LaunchedEffect(nearEnd, GfnState.storeGames.size, mode) {
if (mode == MODE_STORE && nearEnd && GfnState.storeGames.isNotEmpty()) GfnState.loadStore(ctx, query, reset = false)
}
val words = query.trim().lowercase().split(' ').filter { it.isNotEmpty() }
val library = GfnState.library
val libraryShown = remember(library, query) { library.orEmpty().filter { game -> words.all { game.search.contains(it) } } }
val full: androidx.compose.foundation.lazy.grid.LazyGridItemSpanScope.() -> GridItemSpan = { GridItemSpan(maxLineSpan) }
LazyVerticalGrid(
columns = GridCells.Adaptive(CardWidth), state = grid, modifier = Modifier.fillMaxSize().focusGroup(),
horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp),
) {
item(key = "profile", span = full) { Rise(1) { GfnProfile(user, library?.size, onRefresh = {
when (mode) {
MODE_STORE -> GfnState.loadStore(ctx, query, reset = true)
MODE_LIBRARY -> GfnState.loadLibrary(ctx, force = true)
else -> GfnState.loadAccounts(ctx)
}
}) } }
item(key = "modes", span = full) {
Rise(2) {
val pills: @Composable () -> Unit = {
Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
GfnModePill(stringResource(R.string.gfn_mode_store), mode == MODE_STORE, "store") { mode = MODE_STORE; query = "" }
GfnModePill(stringResource(R.string.gfn_mode_library), mode == MODE_LIBRARY, "library") { mode = MODE_LIBRARY; query = "" }
GfnModePill(stringResource(R.string.gfn_mode_accounts), mode == MODE_ACCOUNTS, "accounts") { mode = MODE_ACCOUNTS; query = "" }
}
}
if (mode == MODE_ACCOUNTS) Column(Modifier.fillMaxWidth()) {
Box(Modifier.heightIn(min = 52.dp).padding(vertical = 4.dp), contentAlignment = Alignment.CenterStart) { pills() }
Box(Modifier.fillMaxWidth().height(1.dp).background(LocalPalette.current.line))
} else ModeHeader(
stringResource(R.string.gfn_name), query, { query = it },
placeholder = if (mode == MODE_STORE) stringResource(R.string.gfn_search_store, GfnState.storeTotal)
else stringResource(R.string.gfn_search_library, library?.size ?: 0),
lead = pills,
) {}
}
}
when (mode) {
MODE_STORE -> {
GfnState.storeError?.let { line -> item(key = "error", span = full) { Note(line) } }
val games = GfnState.storeGames
items(games, key = { "gfn:${it.id}" }, contentType = { "game" }) { game -> GfnCard(game, first = game.id == games.first().id, showOwned = true) }
if (GfnState.storeLoading) item(key = "loading", span = full) {
if (games.isEmpty()) Note(stringResource(R.string.gfn_loading_store))
else androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().height(3.dp))
} else if (games.isEmpty() && GfnState.storeError == null) item(key = "empty", span = full) { GfnEmpty(stringResource(R.string.stores_nothing_matches)) }
}
MODE_LIBRARY -> {
GfnState.libraryError?.let { line -> item(key = "error", span = full) { Note(line) } }
when {
library == null && GfnState.libraryError == null -> item(key = "loading", span = full) { Note(stringResource(R.string.gfn_loading_library)) }
library?.isEmpty() == true -> item(key = "empty", span = full) { Note(stringResource(R.string.gfn_library_empty)) }
libraryShown.isEmpty() && library != null -> item(key = "nothing", span = full) { GfnEmpty(stringResource(R.string.stores_nothing_matches)) }
else -> items(libraryShown, key = { "gfn:${it.id}" }, contentType = { "game" }) { game ->
GfnCard(game, first = game.id == libraryShown.first().id, showOwned = false)
}
}
}
else -> {
item(key = "note", span = full) {
Text(stringResource(R.string.gfn_accounts_note), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 2.dp))
}
GfnState.accountsMessage?.let { line -> item(key = "message", span = full) { Note(line) } }
val accounts = GfnState.accounts
if (accounts == null) item(key = "loading", span = full) { androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().height(3.dp)) }
else items(accounts, key = { "account:${it.provider}" }, span = { full() }) { account -> GfnAccountRow(account) }
}
}
}
}
@Composable
private fun GfnEmpty(text: String) {
Box(Modifier.padding(vertical = 32.dp).fillMaxWidth(), contentAlignment = Alignment.Center) {
Text(text, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
@Composable
private fun GfnProfile(user: String, owned: Int?, onRefresh: () -> Unit) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val shape = RoundedCornerShape(16.dp)
Column(
verticalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.fillMaxWidth().padding(bottom = 4.dp).clip(shape).background(colors.surface).border(1.dp, pal.line, shape)
.padding(horizontal = 14.dp, vertical = 10.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth()) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(36.dp).clip(CircleShape).background(GfnGreen)) {
Text(user.take(1).uppercase().ifEmpty { "G" }, fontSize = 16.sp, fontWeight = FontWeight.Black, color = Color.Black)
}
Column(Modifier.weight(1f)) {
Text(user, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
if (owned != null) stringResource(R.string.gfn_profile_line, owned) else stringResource(R.string.gfn_name),
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
Actions {
SecondaryButton(stringResource(R.string.stores_refresh), compact = true) { onRefresh() }
ConfirmButton(stringResource(R.string.stores_signout_go), stringResource(R.string.gfn_signout_confirm), compact = true) { GfnState.signOut(ctx) }
}
}
Text(stringResource(R.string.gfn_unofficial), fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 2)
}
}
@Composable
private fun GfnModePill(label: String, on: Boolean, key: String, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(99.dp)
Text(
label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1,
color = if (on) colors.onPrimary else if (hot) colors.onBackground else colors.onSurfaceVariant,
modifier = Modifier.paneItem("gfnmode:$key").clip(shape)
.background(if (on) pal.signal else Color.Transparent)
.glideBorder(hot, shape, pal.signal, if (on) Color.Transparent else pal.line)
.hoverable(src).clickable(role = Role.Tab, interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 14.dp, vertical = 8.dp),
)
}
@Composable
private fun GfnCard(game: GfnGame, first: Boolean, showOwned: Boolean) {
val ctx = LocalContext.current
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val pressed by src.collectIsPressedAsState()
val scale by animateFloatAsState(if (pressed) 0.985f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "gfnCardScale")
val play = { GfnState.play(ctx, game) }
Column(
Modifier.fillMaxWidth().paneItem("card:gfn:${game.id}").then(if (first) Modifier.firstTile() else Modifier)
.graphicsLayer { scaleX = scale; scaleY = scale }
.clip(RoundedCornerShape(10.dp)).glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, pal.line)
.hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = play)
.controllerConfirm(onClick = play),
) {
CardFace(game.title, game.imageUrl.ifEmpty { null }, null, null, hot) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) {
if (showOwned && game.inLibrary) Icon(Icons.Filled.Check, null, tint = GfnGreen, modifier = Modifier.size(11.dp))
Text(game.store, fontSize = 9.sp, fontWeight = FontWeight.SemiBold, color = Color.White.copy(alpha = 0.75f), maxLines = 1)
}
}
}
}
@Composable
private fun GfnAccountRow(account: GfnStoreAccount) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val shape = RoundedCornerShape(14.dp)
val busy = GfnState.accountsBusy
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().clip(shape).background(colors.surface).border(1.dp, pal.line, shape).padding(horizontal = 14.dp, vertical = 10.dp),
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(36.dp).clip(Shape12).background(if (account.connected) GfnColours.fill else colors.surfaceVariant)) {
Text(account.label.take(1).uppercase(), fontSize = 15.sp, fontWeight = FontWeight.Black, color = if (account.connected) GfnColours.ink else colors.onSurfaceVariant)
}
Column(Modifier.weight(1f)) {
Text(account.label, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
when {
account.status == "expired" -> stringResource(R.string.gfn_status_expired)
account.status == "sync_error" -> stringResource(R.string.gfn_status_sync_error)
account.connected && account.displayName.isNotEmpty() -> stringResource(R.string.gfn_status_connected_as, account.displayName)
account.connected -> stringResource(R.string.gfn_status_connected)
else -> stringResource(R.string.gfn_status_not_connected)
},
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
Box {
when (GfnState.actionFor(account)) {
"link" -> PrimaryButton(stringResource(if (account.connected) R.string.gfn_reconnect else R.string.gfn_connect), enabled = !busy, compact = true) { GfnState.link(ctx, account) }
"sync" -> SecondaryButton(stringResource(R.string.gfn_sync), enabled = !busy, compact = true) { GfnState.sync(ctx, account) }
"unlink" -> ConfirmButton(stringResource(R.string.gfn_disconnect), stringResource(R.string.gfn_disconnect_confirm), compact = true) { GfnState.unlink(ctx, account) }
else -> if (account.provider == "STEAM" && !account.connected)
Text(stringResource(R.string.gfn_steam_link), fontSize = 12.sp, color = colors.onSurfaceVariant)
}
}
}
}
@@ -60,6 +60,7 @@ class ModeSettings(
val hdr: Boolean,
val hdrReason: String?,
val gpuDrivers: String? = null,
val performanceMode: Boolean = false,
val upscaler: Int = 0,
val upscaleSharpness: Int = 75,
val touchMode: String,
@@ -115,6 +116,7 @@ class ModeSettingsActions(
val onResolution: (String) -> Unit,
val onHdr: (Boolean) -> Unit,
val onGpuDrivers: () -> Unit = {},
val onPerformanceMode: (Boolean) -> Unit = {},
val onUpscaler: (Int) -> Unit = {},
val onUpscaleSharpness: (Int) -> Unit = {},
val onTouch: (String) -> Unit,
@@ -246,6 +248,10 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
format = { "$it%" }, onChange = a.onUpscaleSharpness,
)
}
SettingsGroup(stringResource(R.string.display_frame_rate)) {
ToggleRow(host, "performance", stringResource(R.string.mode_performance), stringResource(R.string.mode_performance_hint),
s.performanceMode, onChange = a.onPerformanceMode)
}
SettingsGroup(stringResource(R.string.mode_hdr)) {
ToggleRow(
host, "hdr", stringResource(R.string.mode_hdr10),
@@ -215,8 +215,6 @@ class DrawerActions(
val micEnabled: Boolean = false,
val onMicEnabled: (Boolean) -> Unit = {},
val backActionsInverted: Boolean,
val backDoubleTapMs: Int = 500,
val onBackDoubleTapMs: (Int) -> Unit = {},
val padType: String? = null,
val onPadType: (String) -> Unit = {},
val touchMode: String,
@@ -609,9 +607,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
if (a.steam) ChoiceRow(host, "back-actions", stringResource(R.string.mode_back), null,
listOf(false to stringResource(SessionPrefs.BACK_MENU_THEN_QAM), true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU)),
a.backActionsInverted, chipModifier = focus.track(page, "back-actions"), onPick = a.onBackActionsInverted)
if (a.steam) ChoiceRow(host, "back-double-tap", stringResource(R.string.back_double_tap_window), null,
SessionPrefs.BACK_DOUBLE_TAP_MS_OPTIONS.map { it to stringResource(R.string.back_tap_ms, it) },
a.backDoubleTapMs, chipModifier = focus.track(page, "back-double-tap"), onPick = a.onBackDoubleTapMs)
if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls),
stringResource(R.string.unfolded_controls_hint), a.unfoldedControls,
chipModifier = focus.track(page, "unfolded-controls"), onChange = a.onUnfoldedControls)
@@ -197,7 +197,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
LaunchedEffect(StoresState.openDownloads) { if (StoresState.openDownloads) { chip = DOWNLOADS; StoresState.openDownloads = false } }
val store = Store.byId(chip)
LaunchedEffect(tabs.toList()) {
if (chip != DOWNLOADS && Store.byId(chip) !in shownStores) chip = shownStores.firstOrNull()?.id ?: DOWNLOADS
if (chip != DOWNLOADS && chip != GEFORCE_NOW && Store.byId(chip) !in shownStores) chip = shownStores.firstOrNull()?.id ?: DOWNLOADS
}
val pane = PaneKey(
chip,
@@ -250,8 +250,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
}
val pal = LocalPalette.current
fun cycleStore(step: Int) {
val ids = tabs.filter { it.shown }.map { it.store.id }
if (ids.isEmpty()) return
val ids = tabs.filter { it.shown }.map { it.store.id } + GEFORCE_NOW
val at = ids.indexOf(chip)
pickChip(ids[if (at < 0) (if (step > 0) 0 else ids.size - 1) else (at + step + ids.size) % ids.size])
}
@@ -324,11 +323,12 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
)),
) {
Box(Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
StoreTheme(Store.byId(focusedChip ?: chip)) {
StoreTheme(Store.byId(focusedChip ?: chip), gfn = (focusedChip ?: chip) == GEFORCE_NOW) {
Rise(0) {
StoreChips(
chip, focusedChip, s.storeDownloadsActive, tabs, arranging,
onStore = { st -> openModes(st) },
onGfn = { if (chip != GEFORCE_NOW) pickChip(GEFORCE_NOW) else move("first") },
onDownloads = { if (chip != DOWNLOADS) pickChip(DOWNLOADS) else move("first") },
onFocusChip = { focusedChip = it },
onArrangeDone = { arranging = false },
@@ -364,13 +364,14 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
CompositionLocalProvider(LocalFrontFocus provides if (outgoing) null else LocalFrontFocus.current) {
val leavingNow = androidx.compose.runtime.rememberUpdatedState(outgoing)
val st = Store.byId(k.chip)
StoreTheme(st) {
StoreTheme(st, gfn = k.chip == GEFORCE_NOW) {
Column(
Modifier.fillMaxSize()
.focusProperties { enter = { if (leavingNow.value) androidx.compose.ui.focus.FocusRequester.Cancel else androidx.compose.ui.focus.FocusRequester.Default } }
.focusGroup(),
) {
when {
k.chip == GEFORCE_NOW -> GfnPane(viewportH - 20.dp)
k.chip == DOWNLOADS -> Column(Modifier.fillMaxWidth().verticalScroll(scroll).padding(top = 4.dp, bottom = 16.dp)) { StoresDownloadsPane(s, a) }
st == null -> {}
!k.accountsLoaded -> Box(Modifier.fillMaxWidth().padding(top = 16.dp)) {
@@ -588,17 +589,17 @@ private fun RowScope.ArrangeStoreChip(
@Composable
private fun StoreChips(
selected: String, focused: String?, active: Int, tabs: List<StoreTab>, arranging: Boolean,
onStore: (Store) -> Unit, onDownloads: () -> Unit, onSettings: (Rect?) -> Unit, onFocusChip: (String?) -> Unit,
onStore: (Store) -> Unit, onGfn: () -> Unit, onDownloads: () -> Unit, onSettings: (Rect?) -> Unit, onFocusChip: (String?) -> Unit,
onArrangeDone: () -> Unit, onMoveTab: (Store, Int) -> Unit, onToggleTab: (Store) -> Unit,
) {
val pal = LocalPalette.current
val keys = tabs.filter { it.shown }.map { it.store.id } + DOWNLOADS
val keys = tabs.filter { it.shown }.map { it.store.id } + GEFORCE_NOW + DOWNLOADS
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, Rect>() }
val highlighted = focused ?: selected
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current.inputMode
val fillShown = inputMode != androidx.compose.ui.input.InputMode.Keyboard && !arranging
val tint = androidx.compose.animation.animateColorAsState(
Store.byId(highlighted)?.let { sourceColours(it.id).dot } ?: pal.signal, Motion.tw(160), label = "chipTint",
Store.byId(highlighted)?.let { sourceColours(it.id).dot } ?: if (highlighted == GEFORCE_NOW) GfnGreen else pal.signal, Motion.tw(160), label = "chipTint",
)
val gap = 8.dp
val gapPx = with(androidx.compose.ui.platform.LocalDensity.current) { gap.toPx() }
@@ -630,6 +631,17 @@ private fun StoreChips(
}
}
}
if (!arranging) key(GEFORCE_NOW) {
val reveal = remember { BringIntoViewRequester() }
LaunchedEffect(selected) { if (selected == GEFORCE_NOW) reveal.bringIntoView() }
val signedIn = com.droiddeck.launcher.stores.gfn.GfnState.phase is com.droiddeck.launcher.stores.gfn.GfnState.Phase.SignedIn
StoreChip(
label = stringResource(R.string.gfn_name), on = selected == GEFORCE_NOW, under = fillShown && highlighted == GEFORCE_NOW, key = GEFORCE_NOW, mark = GfnGreen,
modifier = Modifier.bringIntoViewRequester(reveal).onGloballyPositioned { bounds[GEFORCE_NOW] = it.boundsInParent() },
lead = { Box(Modifier.size(12.dp).background(GfnGreen.copy(alpha = if (signedIn) 1f else 0.35f), CircleShape)) },
description = stringResource(R.string.gfn_name), onFocused = onFocusChip,
) { onGfn() }
}
}
ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown && highlighted != DOWNLOADS)
}
@@ -1159,7 +1171,8 @@ internal fun FlathubTheme(content: @Composable () -> Unit) {
}
@Composable
internal fun StoreTheme(store: Store?, content: @Composable () -> Unit) {
internal fun StoreTheme(store: Store?, gfn: Boolean = false, content: @Composable () -> Unit) {
if (gfn) return GfnTheme(content)
val base = LocalPalette.current
val p = remember(base, store) { storePalette(base, store) }
val scheme = MaterialTheme.colorScheme.copy(primary = p.primary, onPrimary = p.onPrimary)
+1
View File
@@ -2025,6 +2025,7 @@
<string name="display_filter_live">يُطبَّق فوريًا. مشترك بين Steam وسطح المكتب.</string>
<string name="display_filter_note">تُطبَّق FSR و GSR و NIS عند تكبير صورة الجلسة. ويعمل خيار «زيادة الحدة فقط» أيضًا دون تكبير.</string>
<string name="display_sharpness">حدّة المرشِّح</string>
<string name="display_frame_rate">معدّل الإطارات</string>
<string name="display_look_filter">%1$s يضبط أسلوب التكبير على %2$s.</string>
<string name="display_match_screen">مطابقة الشاشة (%1$d×%2$d)</string>
<string name="display_follow_screen">اتباع الشاشة (يُغيَّر الحجم عند الطي أو الفتح)</string>
@@ -1994,6 +1994,7 @@
<string name="display_filter_live">Se aplica al instante. Compartido por Steam y Escritorio.</string>
<string name="display_filter_note">FSR, GSR y NIS se aplican al ampliar la imagen de la sesión. Solo nitidez también funciona sin ampliar.</string>
<string name="display_sharpness">Nitidez del filtro</string>
<string name="display_frame_rate">Velocidad de fotogramas</string>
<string name="display_look_filter">%1$s Cambia el escalado a %2$s.</string>
<string name="display_match_screen">Igual a la pantalla (%1$d×%2$d)</string>
<string name="display_follow_screen">Seguir la pantalla (cambia de tamaño al plegar o desplegar)</string>
+1
View File
@@ -1941,6 +1941,7 @@
<string name="display_filter_live">Прилага се веднага. Общ за Steam и Desktop.</string>
<string name="display_filter_note">FSR, GSR и NIS се прилагат при уголемяване на изображението на сесията. „Само изостряне“ работи и без уголемяване.</string>
<string name="display_sharpness">Острота на филтъра</string>
<string name="display_frame_rate">Честота на кадрите</string>
<string name="display_look_filter">%1$s Задава мащабиране на %2$s.</string>
<string name="display_match_screen">Напасване на екрана (%1$d×%2$d)</string>
<string name="display_follow_screen">Следване на екрана (преоразмерява при сгъване или разгъване)</string>
+1
View File
@@ -1983,6 +1983,7 @@
<string name="display_filter_live">Použije se okamžitě. Sdíleno Steamem a Plochou.</string>
<string name="display_filter_note">FSR, GSR a NIS se použijí při zvětšování obrazu relace. Jen zaostření funguje i bez zvětšení.</string>
<string name="display_sharpness">Ostrost filtru</string>
<string name="display_frame_rate">Snímková frekvence</string>
<string name="display_look_filter">%1$s Nastaví škálování na %2$s.</string>
<string name="display_match_screen">Podle obrazovky (%1$d×%2$d)</string>
<string name="display_follow_screen">Sledovat obrazovku (změní velikost při složení nebo rozložení)</string>
+1
View File
@@ -1941,6 +1941,7 @@
<string name="display_filter_live">Træder i kraft øjeblikkeligt. Deles af Steam og Desktop.</string>
<string name="display_filter_note">FSR, GSR og NIS anvendes ved forstørrelse af sessionsbilledet. Kun skærpning virker også uden forstørrelse.</string>
<string name="display_sharpness">Filterskarphed</string>
<string name="display_frame_rate">Billedfrekvens</string>
<string name="display_look_filter">%1$s Indstiller skalering til %2$s.</string>
<string name="display_match_screen">Match skærm (%1$d×%2$d)</string>
<string name="display_follow_screen">Følg skærm (ændrer størrelse ved fold/udfold)</string>
+1
View File
@@ -1933,6 +1933,7 @@
<string name="display_filter_live">Wirkt sofort. Gemeinsam für Steam und Desktop.</string>
<string name="display_filter_note">FSR, GSR und NIS wirken beim Vergrößern des Sitzungsbilds. „Nur schärfen“ funktioniert auch ohne Vergrößerung.</string>
<string name="display_sharpness">Filterschärfe</string>
<string name="display_frame_rate">Bildrate</string>
<string name="display_look_filter">%1$s Stellt die Skalierung auf %2$s.</string>
<string name="display_match_screen">An Bildschirm anpassen (%1$d×%2$d)</string>
<string name="display_follow_screen">Bildschirm folgen (passt sich beim Auf- und Zuklappen an)</string>
+1
View File
@@ -1941,6 +1941,7 @@
<string name="display_filter_live">Εφαρμόζεται σε πραγματικό χρόνο. Κοινό για το Steam και την Επιφάνεια εργασίας.</string>
<string name="display_filter_note">Τα FSR, GSR και NIS εφαρμόζονται κατά τη μεγέθυνση της εικόνας συνεδρίας. Το Μόνο όξυνση λειτουργεί και χωρίς μεγέθυνση.</string>
<string name="display_sharpness">Οξύτητα φίλτρου</string>
<string name="display_frame_rate">Καρέ ανά δευτερόλεπτο</string>
<string name="display_look_filter">%1$s Ορίζει την κλιμάκωση σε %2$s.</string>
<string name="display_match_screen">Αντιστοίχιση οθόνης (%1$d×%2$d)</string>
<string name="display_follow_screen">Ακολούθηση οθόνης (αλλάζει μέγεθος όταν διπλώνει ή ξεδιπλώνει)</string>
+1
View File
@@ -1964,6 +1964,7 @@
<string name="display_filter_live">Se aplica al instante. Compartido por Steam y Escritorio.</string>
<string name="display_filter_note">FSR, GSR y NIS se aplican al ampliar la imagen de la sesión. Solo nitidez también funciona sin ampliar.</string>
<string name="display_sharpness">Nitidez del filtro</string>
<string name="display_frame_rate">Velocidad de fotogramas</string>
<string name="display_look_filter">%1$s Cambia el escalado a %2$s.</string>
<string name="display_match_screen">Igual a la pantalla (%1$d×%2$d)</string>
<string name="display_follow_screen">Seguir la pantalla (cambia de tamaño al plegar o desplegar)</string>
+1
View File
@@ -1941,6 +1941,7 @@
<string name="display_filter_live">Vaikuttaa välittömästi. Yhteinen Steamille ja Työpöydälle.</string>
<string name="display_filter_note">FSR, GSR ja NIS vaikuttavat, kun istunnon kuvaa suurennetaan. Vain terävöinti toimii myös suurentamatta.</string>
<string name="display_sharpness">Suodattimen terävyys</string>
<string name="display_frame_rate">Kuvanopeus</string>
<string name="display_look_filter">%1$s Asettaa skaalauksen tilaan %2$s.</string>
<string name="display_match_screen">Sovita näyttöön (%1$d×%2$d)</string>
<string name="display_follow_screen">Seuraa näyttöä (koko muuttuu taitettuna tai avattuna)</string>
+1
View File
@@ -1964,6 +1964,7 @@
<string name="display_filter_live">S\'applique en direct. Partagé entre Steam et le bureau.</string>
<string name="display_filter_note">FSR, GSR et NIS s\'appliquent lors de l\'agrandissement de l\'image de la session. « Netteté seule » fonctionne aussi sans agrandissement.</string>
<string name="display_sharpness">Netteté du filtre</string>
<string name="display_frame_rate">Fréquence d\'images</string>
<string name="display_look_filter">%1$s Règle la mise à l\'échelle sur %2$s.</string>
<string name="display_match_screen">Adapter à l\'écran (%1$d×%2$d)</string>
<string name="display_follow_screen">Suivre l\'écran (s\'adapte au pliage et au dépliage)</string>
+1
View File
@@ -1941,6 +1941,7 @@
<string name="display_filter_live">लाइव लागू होता है। Steam और डेस्कटॉप में साझा।</string>
<string name="display_filter_note">FSR, GSR और NIS सेशन इमेज को बड़ा करने पर लागू होते हैं। सिर्फ़ शार्पन बिना बड़ा किए भी काम करता है।</string>
<string name="display_sharpness">फ़िल्टर शार्पनेस</string>
<string name="display_frame_rate">फ़्रेम रेट</string>
<string name="display_look_filter">%1$s स्केलिंग को %2$s पर सेट करता है।</string>
<string name="display_match_screen">स्क्रीन से मिलाएँ (%1$d×%2$d)</string>
<string name="display_follow_screen">Follow screen (खुलने या बंद होने पर आकार बदलता है)</string>
+1
View File
@@ -1941,6 +1941,7 @@
<string name="display_filter_live">Élőben érvénybe lép. A Steam és az Asztal közösen használja.</string>
<string name="display_filter_note">Az FSR, a GSR és a NIS a munkamenet képének felnagyításakor lép érvénybe. A Csak élesítés nagyítás nélkül is működik.</string>
<string name="display_sharpness">Szűrőélesség</string>
<string name="display_frame_rate">Képkockasebesség</string>
<string name="display_look_filter">%1$s A méretezést erre állítja: %2$s.</string>
<string name="display_match_screen">Képernyőhöz illesztés (%1$d×%2$d)</string>
<string name="display_follow_screen">Képernyő követése (átméreteződik össze- vagy kinyitáskor)</string>
+1
View File
@@ -1920,6 +1920,7 @@
<string name="display_filter_live">Berlaku langsung. Digunakan bersama oleh Steam dan Desktop.</string>
<string name="display_filter_note">FSR, GSR, dan NIS berlaku saat memperbesar gambar sesi. Hanya penajaman juga berfungsi tanpa pembesaran.</string>
<string name="display_sharpness">Ketajaman filter</string>
<string name="display_frame_rate">Frame rate</string>
<string name="display_look_filter">%1$s Mengatur skala ke %2$s.</string>
<string name="display_match_screen">Sesuaikan layar (%1$d×%2$d)</string>
<string name="display_follow_screen">Ikuti layar (ukuran berubah saat dilipat atau dibuka)</string>
+1
View File
@@ -1954,6 +1954,7 @@
<string name="display_filter_live">Si applica subito. Condiviso da Steam e Desktop.</string>
<string name="display_filter_note">FSR, GSR e NIS si applicano quando l\'immagine della sessione viene ingrandita. Solo nitidezza funziona anche senza ingrandimento.</string>
<string name="display_sharpness">Nitidezza del filtro</string>
<string name="display_frame_rate">Frequenza fotogrammi</string>
<string name="display_look_filter">%1$s Imposta il ridimensionamento su %2$s.</string>
<string name="display_match_screen">Adatta allo schermo (%1$d×%2$d)</string>
<string name="display_follow_screen">Segui lo schermo (si ridimensiona quando lo pieghi o lo apri)</string>
+1
View File
@@ -1922,6 +1922,7 @@
<string name="display_filter_live">すぐに反映されます。Steamとデスクトップで共有されます。</string>
<string name="display_filter_note">FSR、GSR、NISはセッションの映像を拡大するときに機能します。「シャープのみ」は拡大しなくても機能します。</string>
<string name="display_sharpness">フィルターのシャープネス</string>
<string name="display_frame_rate">フレームレート</string>
<string name="display_look_filter">%1$s スケーリングを%2$sに設定します。</string>
<string name="display_match_screen">画面に合わせる(%1$d×%2$d)</string>
<string name="display_follow_screen">画面に追従(開閉時にサイズを変更)</string>
+1
View File
@@ -1922,6 +1922,7 @@
<string name="display_filter_live">즉시 적용됩니다. Steam과 데스크톱에서 공유됩니다.</string>
<string name="display_filter_note">FSR, GSR, NIS는 세션 이미지를 확대할 때 적용됩니다. 샤프닝 전용은 확대하지 않아도 작동합니다.</string>
<string name="display_sharpness">필터 선명도</string>
<string name="display_frame_rate">프레임 속도</string>
<string name="display_look_filter">%1$s 스케일링을 %2$s(으)로 설정합니다.</string>
<string name="display_match_screen">화면에 맞춤(%1$d×%2$d)</string>
<string name="display_follow_screen">화면 따라가기(접거나 펼치면 크기 변경)</string>
+1
View File
@@ -1920,6 +1920,7 @@
<string name="display_filter_live">Berkuat kuasa secara langsung. Dikongsi oleh Steam dan Desktop.</string>
<string name="display_filter_note">FSR, GSR dan NIS berkuat kuasa semasa membesarkan imej sesi. Ketajaman sahaja juga berfungsi tanpa pembesaran.</string>
<string name="display_sharpness">Ketajaman penapis</string>
<string name="display_frame_rate">Kadar bingkai</string>
<string name="display_look_filter">%1$s Menetapkan penskalaan ke %2$s.</string>
<string name="display_match_screen">Sepadan skrin (%1$d×%2$d)</string>
<string name="display_follow_screen">Ikut skrin (mengubah saiz apabila dilipat atau dibuka)</string>
+1
View File
@@ -1941,6 +1941,7 @@
<string name="display_filter_live">Gjelder live. Delt av Steam og Skrivebord.</string>
<string name="display_filter_note">FSR, GSR og NIS gjelder ved forstørring av sesjonsbildet. Bare skarphet fungerer også uten forstørring.</string>
<string name="display_sharpness">Filterskarphet</string>
<string name="display_frame_rate">Bildefrekvens</string>
<string name="display_look_filter">%1$s Setter skalering til %2$s.</string>
<string name="display_match_screen">Tilpass skjerm (%1$d×%2$d)</string>
<string name="display_follow_screen">Følg skjermen (endrer størrelse ved sammenslåing eller utbretting)</string>
+1
View File
@@ -1941,6 +1941,7 @@
<string name="display_filter_live">Wordt direct toegepast. Gedeeld door Steam en Desktop.</string>
<string name="display_filter_note">FSR, GSR en NIS worden toegepast bij het vergroten van het sessiebeeld. Alleen verscherpen werkt ook zonder vergroting.</string>
<string name="display_sharpness">Filterscherpte</string>
<string name="display_frame_rate">Framerate</string>
<string name="display_look_filter">%1$s Zet schaling op %2$s.</string>
<string name="display_match_screen">Schermformaat (%1$d×%2$d)</string>
<string name="display_follow_screen">Scherm volgen (past formaat aan bij vouwen of uitvouwen)</string>
+1
View File
@@ -1983,6 +1983,7 @@
<string name="display_filter_live">Działa od razu. Wspólny dla Steam i Pulpitu.</string>
<string name="display_filter_note">FSR, GSR i NIS działają przy powiększaniu obrazu sesji. „Tylko wyostrzanie” działa też bez powiększania.</string>
<string name="display_sharpness">Ostrość filtra</string>
<string name="display_frame_rate">Liczba klatek</string>
<string name="display_look_filter">%1$s Ustawia skalowanie na %2$s.</string>
<string name="display_match_screen">Dopasuj do ekranu (%1$d×%2$d)</string>
<string name="display_follow_screen">Dopasuj do ekranu (zmienia rozmiar po złożeniu lub rozłożeniu)</string>
@@ -1954,6 +1954,7 @@
<string name="display_filter_live">Aplica-se em tempo real. Partilhado pelo Steam e pelo Ambiente de trabalho.</string>
<string name="display_filter_note">FSR, GSR e NIS aplicam-se ao ampliar a imagem da sessão. «Só nitidez» também funciona sem ampliação.</string>
<string name="display_sharpness">Nitidez do filtro</string>
<string name="display_frame_rate">Taxa de fotogramas</string>
<string name="display_look_filter">%1$s Define a escala como %2$s.</string>
<string name="display_match_screen">Igual ao ecrã (%1$d×%2$d)</string>
<string name="display_follow_screen">Seguir o ecrã (redimensiona ao dobrar ou desdobrar)</string>
+1
View File
@@ -1954,6 +1954,7 @@
<string name="display_filter_live">Aplicado na hora. Compartilhado entre Steam e Área de trabalho.</string>
<string name="display_filter_note">FSR, GSR e NIS são aplicados ao ampliar a imagem da sessão. Só nitidez também funciona sem ampliação.</string>
<string name="display_sharpness">Nitidez do filtro</string>
<string name="display_frame_rate">Taxa de quadros</string>
<string name="display_look_filter">%1$s Define a escala como %2$s.</string>
<string name="display_match_screen">Igual à tela (%1$d×%2$d)</string>
<string name="display_follow_screen">Seguir a tela (redimensiona ao dobrar ou desdobrar)</string>
+1
View File
@@ -1962,6 +1962,7 @@
<string name="display_filter_live">Se aplică live. Partajat de Steam și Desktop.</string>
<string name="display_filter_note">FSR, GSR și NIS se aplică la mărirea imaginii sesiunii. Doar claritate funcționează și fără mărire.</string>
<string name="display_sharpness">Claritatea filtrului</string>
<string name="display_frame_rate">Rata de cadre</string>
<string name="display_look_filter">%1$s Setează scalarea la %2$s.</string>
<string name="display_match_screen">Potrivire ecran (%1$d×%2$d)</string>
<string name="display_follow_screen">Urmărește ecranul (se redimensionează la împăturire sau desfacere)</string>
+1
View File
@@ -1985,6 +1985,7 @@
<string name="display_filter_live">Применяется сразу. Общий для Steam и рабочего стола.</string>
<string name="display_filter_note">FSR, GSR и NIS работают при увеличении изображения сессии. «Sharpen only» работает и без увеличения.</string>
<string name="display_sharpness">Резкость фильтра</string>
<string name="display_frame_rate">Частота кадров</string>
<string name="display_look_filter">%1$s Устанавливает масштабирование: %2$s.</string>
<string name="display_match_screen">По размеру экрана (%1$d×%2$d)</string>
<string name="display_follow_screen">По экрану (меняется при складывании и раскладывании)</string>
+1
View File
@@ -1941,6 +1941,7 @@
<string name="display_filter_live">Tillämpas direkt. Delas av Steam och skrivbordet.</string>
<string name="display_filter_note">FSR, GSR och NIS tillämpas när sessionens bild förstoras. Endast skärpa fungerar även utan förstoring.</string>
<string name="display_sharpness">Filterskärpa</string>
<string name="display_frame_rate">Bildfrekvens</string>
<string name="display_look_filter">%1$s Ställer in skalning till %2$s.</string>
<string name="display_match_screen">Matcha skärmen (%1$d×%2$d)</string>
<string name="display_follow_screen">Följ skärmen (ändrar storlek vid vikning)</string>
+1
View File
@@ -1920,6 +1920,7 @@
<string name="display_filter_live">มีผลทันที ใช้ร่วมกันระหว่าง Steam และเดสก์ท็อป</string>
<string name="display_filter_note">FSR, GSR และ NIS จะมีผลเมื่อขยายภาพของเซสชัน เพิ่มความคมชัดเท่านั้นทำงานได้โดยไม่ต้องขยายภาพด้วย</string>
<string name="display_sharpness">ความคมชัดของตัวกรอง</string>
<string name="display_frame_rate">อัตราเฟรม</string>
<string name="display_look_filter">%1$s ตั้งการปรับขนาดเป็น %2$s</string>
<string name="display_match_screen">พอดีหน้าจอ (%1$d×%2$d)</string>
<string name="display_follow_screen">ตามหน้าจอ (ปรับขนาดเมื่อพับหรือกาง)</string>
+1
View File
@@ -1935,6 +1935,7 @@
<string name="display_filter_live">Anında uygulanır. Steam ve Masaüstü tarafından paylaşılır.</string>
<string name="display_filter_note">FSR, GSR ve NIS, oturum görüntüsü büyütülürken uygulanır. Yalnızca keskinleştirme büyütme olmadan da çalışır.</string>
<string name="display_sharpness">Filtre keskinliği</string>
<string name="display_frame_rate">Kare hızı</string>
<string name="display_look_filter">%1$s Ölçeklemeyi %2$s olarak ayarlar.</string>
<string name="display_match_screen">Ekrana Uydur (%1$d×%2$d)</string>
<string name="display_follow_screen">Ekranı takip et (katlanıp açıldığında yeniden boyutlanır)</string>
+1
View File
@@ -1983,6 +1983,7 @@
<string name="display_filter_live">Застосовується відразу. Спільний для Steam і Робочого столу.</string>
<string name="display_filter_note">FSR, GSR і NIS застосовуються під час збільшення зображення сеансу. «Лише різкість» працює і без збільшення.</string>
<string name="display_sharpness">Різкість фільтра</string>
<string name="display_frame_rate">Частота кадрів</string>
<string name="display_look_filter">%1$s Встановлює масштабування на %2$s.</string>
<string name="display_match_screen">Під екран (%1$d×%2$d)</string>
<string name="display_follow_screen">Слідувати за екраном (змінює розмір при згортанні чи розгортанні)</string>
+1
View File
@@ -1920,6 +1920,7 @@
<string name="display_filter_live">Áp dụng ngay. Dùng chung cho Steam và Desktop.</string>
<string name="display_filter_note">FSR, GSR và NIS áp dụng khi phóng to hình ảnh phiên. Chỉ làm nét cũng hoạt động mà không cần phóng to.</string>
<string name="display_sharpness">Độ sắc nét bộ lọc</string>
<string name="display_frame_rate">Tốc độ khung hình</string>
<string name="display_look_filter">%1$s Đặt chia tỷ lệ thành %2$s.</string>
<string name="display_match_screen">Khớp màn hình (%1$d×%2$d)</string>
<string name="display_follow_screen">Theo màn hình (đổi kích thước khi gập hoặc mở)</string>
@@ -2000,6 +2000,7 @@
<string name="display_filter_live">即时生效。由 Steam 和桌面共享。</string>
<string name="display_filter_note">FSR、GSR 和 NIS 在放大会话画面时生效。“仅锐化”在不放大时也可用。</string>
<string name="display_sharpness">滤镜锐度</string>
<string name="display_frame_rate">帧率</string>
<string name="display_look_filter">%1$s 将缩放设为 %2$s。</string>
<string name="display_match_screen">匹配屏幕(%1$d×%2$d)</string>
<string name="display_follow_screen">跟随屏幕(折叠或展开时调整大小)</string>
@@ -1923,6 +1923,7 @@
<string name="display_filter_live">即時生效。Steam 和桌面共用。</string>
<string name="display_filter_note">FSR、GSR 和 NIS 會在放大會話畫面時套用。「只銳化」不放大也能使用。</string>
<string name="display_sharpness">濾鏡銳利度</string>
<string name="display_frame_rate">幀率</string>
<string name="display_look_filter">%1$s 將縮放設為 %2$s。</string>
<string name="display_match_screen">配合螢幕(%1$d×%2$d)</string>
<string name="display_follow_screen">跟隨螢幕(摺疊或展開時調整大小)</string>
@@ -1923,6 +1923,7 @@
<string name="display_filter_live">立即生效。Steam 和桌面共用。</string>
<string name="display_filter_note">FSR、GSR 和 NIS 會在放大工作階段畫面時套用。「僅銳化」不放大也能使用。</string>
<string name="display_sharpness">濾鏡銳利度</string>
<string name="display_frame_rate">影格率</string>
<string name="display_look_filter">%1$s 將縮放設為 %2$s。</string>
<string name="display_match_screen">符合螢幕(%1$d×%2$d)</string>
<string name="display_follow_screen">跟隨螢幕(摺疊或展開時調整大小)</string>
+34 -15
View File
@@ -258,6 +258,8 @@
<string name="mode_ratio">Screen ratio</string>
<string name="mode_ratio_custom">Set by the custom resolution.</string>
<string name="mode_ratio_auto">Auto uses at least 16:9.</string>
<string name="mode_performance">Performance mode</string>
<string name="mode_performance_hint">Lets games run without waiting for the screen and reduces repeated window checks in gamescope and Wine. Can use more power and run warmer. Use Steam\'s Quick Access menu to limit Steam games. Applies next session.</string>
<string name="mode_hdr">HDR</string>
<string name="mode_hdr10">HDR10 output</string>
<string name="mode_hdr_unavailable">Not available: %1$s.</string>
@@ -304,9 +306,7 @@
<string name="mode_controller_x360">Xbox 360 controller</string>
<string name="mode_controller_note">Deck: Quick Access button and gyro. Steam Controller: the same, with grip sense on the back buttons. DualShock 4 and DualSense: gyro, and the trackpads as their touchpad. Xbox 360: open Quick Access with Guide+A.</string>
<string name="mode_back">Back</string>
<string name="back_native_qam_hint">Hold Back for 700 ms, or hold Back and press another button for Steam shortcuts.</string>
<string name="back_double_tap_window">Double-tap window</string>
<string name="back_tap_ms">%1$d ms</string>
<string name="back_native_qam_hint">Hold Back for 700 ms, then press another button for Steam shortcuts. Single and double taps keep the selected actions.</string>
<string name="brightness_permission_title">Allow brightness control</string>
<string name="brightness_permission_text">Tap to allow Steam to change Android screen brightness.</string>
<string name="back_menu_then_qam">Menu → QAM</string>
@@ -1285,10 +1285,6 @@
<string name="main_wait_runtime">Wait for the runtime operation to finish</string>
<string name="main_wait_proton_install">Wait for the compatibility tool install to finish</string>
<string name="load_compat_title">Preparing compatibility tools</string>
<string name="load_compat_wait">Waiting for compatibility setup to finish</string>
<string name="load_compat_hint">Your session will start when setup finishes.</string>
<string name="load_compat_progress">%1$s · %2$d%%</string>
<string name="main_wait_desktop_install">Wait for the desktop app install to finish</string>
<string name="main_wait_install_game">Wait for the install to finish before launching a game</string>
<string name="main_saves_close_session">Close the Steam session first, so the game can\'t save over the import</string>
@@ -2052,6 +2048,7 @@
<string name="display_filter_live">Applies live. Shared by Steam and Desktop.</string>
<string name="display_filter_note">FSR, GSR and NIS apply when enlarging the session image. Sharpen only also works without enlargement.</string>
<string name="display_sharpness">Filter sharpness</string>
<string name="display_frame_rate">Frame rate</string>
<string name="display_look_filter">%1$s Sets scaling to %2$s.</string>
<string name="display_match_screen">Match screen (%1$d×%2$d)</string>
<string name="display_follow_screen">Follow screen (resizes when folded or unfolded)</string>
@@ -3207,14 +3204,6 @@
<string name="library_no_installed_matches">No installed games match these filters.</string>
<string name="library_browse_owned">Browse owned games</string>
<string name="game_tab_about">About</string>
<string name="game_resources_browser">Opens in your browser</string>
<string name="game_resource_pcgw" translatable="false">PCGamingWiki</string>
<string name="game_resource_guides">Guides</string>
<string name="game_resource_protondb" translatable="false">ProtonDB</string>
<string name="game_resource_protondb_detail">Linux / Proton compatibility reports</string>
<string name="game_resource_steam_cloud">Steam Cloud</string>
<string name="game_resource_steam_cloud_detail">For games with saves on your Steam account</string>
<string name="game_resource_search">Web search</string>
<string name="game_tab_achievements_count" translatable="false">%1$s %2$d/%3$d</string>
<string name="game_tab_launch">Launch</string>
<string name="game_tab_saves_cloud">Saves &amp; cloud</string>
@@ -3237,4 +3226,34 @@
<string name="stores_xbox_cloud_settings">Cloud settings</string>
<string name="xbox_cloud_gaming" translatable="false">Xbox Cloud Gaming</string>
<string name="xbox_filter_game_pass" translatable="false">Game Pass</string>
<!-- GeForce NOW tab (OpenNOW) -->
<string name="gfn_name" translatable="false">GeForce NOW</string>
<string name="gfn_pitch">Stream your games from NVIDIA\'s servers.</string>
<string name="gfn_unofficial">Unofficial client built on OpenNOW. NVIDIA does not support third-party GeForce NOW apps.</string>
<string name="gfn_open_page">Open the sign-in page</string>
<string name="gfn_code_hint">On this device or another one, open %1$s and enter this code:</string>
<string name="gfn_code_waiting">Waiting for you to sign in…</string>
<string name="gfn_try_again">Try again</string>
<string name="gfn_mode_store">Store</string>
<string name="gfn_mode_library">My library</string>
<string name="gfn_mode_accounts">Connected stores</string>
<string name="gfn_search_store">Search %1$d games</string>
<string name="gfn_search_library">Search your %1$d games</string>
<string name="gfn_loading_store">Loading the GeForce NOW store…</string>
<string name="gfn_loading_library">Loading your library…</string>
<string name="gfn_library_empty">Your GeForce NOW library is empty. Connect your stores under Connected stores, then sync.</string>
<string name="gfn_profile_line">GeForce NOW · %1$d in library</string>
<string name="gfn_accounts_note">Games in the stores you connect here show up in My library and can be streamed. Amazon and itch.io games are not on GeForce NOW.</string>
<string name="gfn_connect">Connect</string>
<string name="gfn_reconnect">Reconnect</string>
<string name="gfn_sync">Sync library</string>
<string name="gfn_disconnect">Disconnect</string>
<string name="gfn_disconnect_confirm">Press again to disconnect</string>
<string name="gfn_signout_confirm">Press again to sign out</string>
<string name="gfn_steam_link">Link Steam on NVIDIA\'s site</string>
<string name="gfn_status_connected">Connected</string>
<string name="gfn_status_connected_as">Connected as %1$s</string>
<string name="gfn_status_expired">Connection expired: reconnect</string>
<string name="gfn_status_sync_error">Last sync failed</string>
<string name="gfn_status_not_connected">Not connected</string>
</resources>
+2598
View File
File diff suppressed because it is too large. Load diff
+32
View File
@@ -0,0 +1,32 @@
[package]
name = "droiddeckgfn"
version = "0.1.0"
edition = "2024"
license = "GPL-3.0-or-later"
publish = false
# DroidDeck's GeForce NOW streamer host: drives OpenNOW's native streamer
# (external/opennow, MIT, by Zortos) for the app over JNI.
[lib]
name = "droiddeckgfn"
crate-type = ["cdylib"]
[dependencies]
jni = "0.21"
ndk = { version = "0.9", default-features = false, features = ["nativewindow"] }
serde_json = "1"
opennow-streamer-core = { path = "../../../../../external/opennow/native/opennow-streamer/crates/opennow-streamer-core" }
opennow-streamer-platform = { path = "../../../../../external/opennow/native/opennow-streamer/crates/opennow-streamer-platform" }
opennow-streamer-protocol = { path = "../../../../../external/opennow/native/opennow-streamer/crates/opennow-streamer-protocol" }
[patch.crates-io]
# DroidDeck: mtu 0.3.0 with a versioned Android target for bindgen (vendor/mtu/build.rs).
mtu = { path = "../../../../../external/opennow/native/opennow-streamer/vendor/mtu" }
str0m = { path = "../../../../../external/opennow/native/opennow-streamer/vendor/str0m" }
audiopus_sys = { path = "../../../../../external/opennow/native/opennow-streamer/vendor/audiopus-sys" }
[profile.release]
codegen-units = 1
lto = "thin"
strip = "symbols"
+278
View File
@@ -0,0 +1,278 @@
//! DroidDeck's GeForce NOW streamer host.
//!
//! OpenNOW's native streamer engine (external/opennow, MIT, by Zortos) runs on its own
//! thread with DroidDeck's Android media backend. Kotlin sends the engine's JSON
//! commands (`hello`, `start`, `stop`, ...) and polls one queue for everything the
//! engine answers or reports. The player's Surface and gamepad state come in through
//! the other entry points.
use std::collections::VecDeque;
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Condvar, Mutex};
use std::thread::{self, JoinHandle};
use std::time::Duration;
use jni::JNIEnv;
use jni::objects::{JClass, JObject, JString};
use jni::sys::{jboolean, jint, jlong, jstring};
use ndk::native_window::NativeWindow;
use opennow_streamer_core::Engine;
use opennow_streamer_platform::{CapturedInput, CapturedInputQueue, create_android_runtime};
use opennow_streamer_protocol::{Command, error};
use serde_json::Value;
const MAX_QUEUED_MESSAGES: usize = 4096;
#[derive(Default)]
struct Outbox {
messages: Mutex<VecDeque<String>>,
ready: Condvar,
}
impl Outbox {
fn push(&self, message: &Value) {
let mut messages = self.messages.lock().unwrap_or_else(|error| error.into_inner());
if messages.len() >= MAX_QUEUED_MESSAGES {
messages.pop_front();
}
messages.push_back(message.to_string());
self.ready.notify_one();
}
fn pop(&self, timeout: Duration) -> Option<String> {
let messages = self.messages.lock().unwrap_or_else(|error| error.into_inner());
let (mut messages, _) = self
.ready
.wait_timeout_while(messages, timeout, |messages| messages.is_empty())
.unwrap_or_else(|error| error.into_inner());
messages.pop_front()
}
}
struct Host {
commands: Mutex<Option<Sender<String>>>,
outbox: Arc<Outbox>,
input: Arc<CapturedInputQueue>,
engine: Mutex<Option<JoinHandle<()>>>,
events: Mutex<Option<JoinHandle<()>>>,
}
impl Host {
fn open() -> Result<Self, String> {
let outbox = Arc::new(Outbox::default());
let input = Arc::new(CapturedInputQueue::default());
let runtime = create_android_runtime(Arc::clone(&input));
let (event_tx, event_rx) = mpsc::channel::<Value>();
let (command_tx, command_rx) = mpsc::channel::<String>();
let event_outbox = Arc::clone(&outbox);
let events = thread::Builder::new()
.name("gfn-events".to_owned())
.spawn(move || {
while let Ok(message) = event_rx.recv() {
event_outbox.push(&message);
}
})
.map_err(|error| error.to_string())?;
let engine_outbox = Arc::clone(&outbox);
let engine = thread::Builder::new()
.name("gfn-engine".to_owned())
.spawn(move || run_engine(Engine::with_media_runtime(event_tx, runtime), &command_rx, &engine_outbox))
.map_err(|error| error.to_string())?;
Ok(Self {
commands: Mutex::new(Some(command_tx)),
outbox,
input,
engine: Mutex::new(Some(engine)),
events: Mutex::new(Some(events)),
})
}
fn send(&self, command: String) -> bool {
self.commands
.lock()
.ok()
.and_then(|commands| commands.as_ref().map(|sender| sender.send(command).is_ok()))
.unwrap_or(false)
}
fn close(&self) {
let shutdown = serde_json::json!({"id": "droiddeck-close", "type": "shutdown"}).to_string();
let _ = self.send(shutdown);
if let Ok(mut commands) = self.commands.lock() {
commands.take();
}
if let Some(engine) = self.engine.lock().ok().and_then(|mut engine| engine.take()) {
let _ = engine.join();
}
if let Some(events) = self.events.lock().ok().and_then(|mut events| events.take()) {
let _ = events.join();
}
}
}
fn run_engine(mut engine: Engine, commands: &Receiver<String>, outbox: &Outbox) {
while let Ok(line) = commands.recv() {
let command: Command = match serde_json::from_str(&line) {
Ok(command) => command,
Err(parse_error) => {
outbox.push(&error(None, "invalid-command", parse_error.to_string()));
continue;
}
};
let (responses, keep_running) = engine.handle(command);
for response in &responses {
outbox.push(response);
}
if !keep_running {
break;
}
}
drop(engine);
}
fn host<'a>(handle: jlong) -> Option<&'a Host> {
// SAFETY: the handle is a Box<Host> from nativeOpen, alive until nativeClose.
(handle != 0).then(|| unsafe { &*(handle as *const Host) })
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_com_droiddeck_launcher_stores_gfn_GfnStreamer_nativeOpen(
mut env: JNIEnv,
_class: JClass,
) -> jlong {
match Host::open() {
Ok(host) => Box::into_raw(Box::new(host)) as jlong,
Err(message) => {
let _ = env.throw_new("java/lang/IllegalStateException", message);
0
}
}
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_com_droiddeck_launcher_stores_gfn_GfnStreamer_nativeCommand(
mut env: JNIEnv,
_class: JClass,
handle: jlong,
json: JString,
) -> jboolean {
let Some(host) = host(handle) else {
return 0;
};
let Ok(command) = env.get_string(&json).map(String::from) else {
return 0;
};
jboolean::from(host.send(command))
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_com_droiddeck_launcher_stores_gfn_GfnStreamer_nativePoll(
env: JNIEnv,
_class: JClass,
handle: jlong,
timeout_ms: jint,
) -> jstring {
let Some(host) = host(handle) else {
return std::ptr::null_mut();
};
let timeout = Duration::from_millis(u64::try_from(timeout_ms).unwrap_or(0));
match host.outbox.pop(timeout) {
Some(message) => env
.new_string(message)
.map(|string| string.into_raw())
.unwrap_or(std::ptr::null_mut()),
None => std::ptr::null_mut(),
}
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_com_droiddeck_launcher_stores_gfn_GfnStreamer_nativeClose(
_env: JNIEnv,
_class: JClass,
handle: jlong,
) {
if handle == 0 {
return;
}
// SAFETY: reclaims the Box created by nativeOpen; Kotlin calls this once.
let host = unsafe { Box::from_raw(handle as *mut Host) };
host.close();
}
#[unsafe(no_mangle)]
pub extern "system" fn Java_com_droiddeck_launcher_stores_gfn_GfnStreamer_nativeSetSurface(
env: JNIEnv,
_class: JClass,
surface: JObject,
) {
if surface.is_null() {
opennow_streamer_platform::clear_surface();
return;
}
// SAFETY: env and surface are valid for this call; from_surface acquires its own reference.
let window = unsafe { NativeWindow::from_surface(env.get_raw().cast(), surface.as_raw().cast()) };
match window {
Some(window) => opennow_streamer_platform::set_surface(window),
None => opennow_streamer_platform::clear_surface(),
}
}
/// One controller's full state, XInput layout: `buttons` uses XInput's bits, sticks are
/// -32768..32767 with up positive, triggers 0..255. `connected` is the bitmap of
/// connected slots (bit n and bit n+8 for slot n, as OpenNOW sends it).
#[unsafe(no_mangle)]
#[allow(clippy::too_many_arguments)]
pub extern "system" fn Java_com_droiddeck_launcher_stores_gfn_GfnStreamer_nativeGamepad(
_env: JNIEnv,
_class: JClass,
handle: jlong,
slot: jint,
connected: jint,
buttons: jint,
left_trigger: jint,
right_trigger: jint,
left_x: jint,
left_y: jint,
right_x: jint,
right_y: jint,
) {
let Some(host) = host(handle) else {
return;
};
let axis = |value: jint| value.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16;
let trigger = |value: jint| value.clamp(0, 255) as u8;
host.input.push(CapturedInput::Gamepad {
controller_id: slot.clamp(0, 3) as u8,
bitmap: connected as u16,
buttons: buttons as u16,
left_trigger: trigger(left_trigger),
right_trigger: trigger(right_trigger),
left_stick_x: axis(left_x),
left_stick_y: axis(left_y),
right_stick_x: axis(right_x),
right_stick_y: axis(right_y),
});
}
/// A keyboard key as a Windows virtual-key code.
#[unsafe(no_mangle)]
pub extern "system" fn Java_com_droiddeck_launcher_stores_gfn_GfnStreamer_nativeKey(
_env: JNIEnv,
_class: JClass,
handle: jlong,
virtual_key: jint,
modifiers: jint,
pressed: jboolean,
) {
let Some(host) = host(handle) else {
return;
};
host.input.push(CapturedInput::Key {
virtual_key: virtual_key as u16,
modifiers: modifiers as u16,
pressed: pressed != 0,
});
}
@@ -1,268 +0,0 @@
package com.droiddeck.launcher
import android.content.Intent
import android.os.Bundle
import android.os.Looper
import com.droiddeck.launcher.session.LoadingState
import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.ui.LaunchOrigin
import java.time.Duration
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class CompatLaunchTest {
private lateinit var activity: FrontEndActivity
private lateinit var protons: ProtonMenu
@Before fun setUp() {
installing(false)
LaunchOrigin.take()
activity = Robolectric.buildActivity(FrontEndActivity::class.java).get()
protons = ReflectionHelpers.getField(activity, "protons")
ReflectionHelpers.setField(activity, "compatLaunchVisible", true)
protons.protonBusyId = "droiddeck"
protons.protonProblem = null
protons.protonStage = "Downloading DroidDeck Proton"
protons.protonPercent = 37
setString("setPkgStage", null)
}
@After fun cleanUp() {
cancel()
protons.protonBusyId = null
protons.protonProblem = null
protons.protonStage = null
protons.protonPercent = -1
setString("setPkgStage", null)
installing(false)
LaunchOrigin.take()
}
@Test fun waitingShowsRealProgressThenStartsTheOriginalRequestOnce() {
activity.startActivity(request("steam://rungameid/42"))
assertNull(shadowOf(activity).nextStartedActivity)
assertEquals(37, loading().percent)
assertTrue(loading().step.contains("37%"))
protons.protonStage = "Verifying download"
protons.protonPercent = -1
advance()
assertEquals("Verifying download", loading().step)
assertEquals(-1, loading().percent)
protons.protonBusyId = null
advance()
assertEquals("steam://rungameid/42", shadowOf(activity).nextStartedActivity.getStringExtra(SessionService.EXTRA_STEAM_URL))
assertNull(waiting())
advance()
assertNull(shadowOf(activity).nextStartedActivity)
}
@Test fun cancellingTheLaunchLeavesTheInstallRunningAndPreventsALateStart() {
activity.startActivity(request("first"))
cancel()
assertEquals("droiddeck", protons.protonBusyId)
protons.protonBusyId = null
advance()
assertNull(waiting())
assertNull(shadowOf(activity).nextStartedActivity)
}
@Test fun installationFailureStaysOnTheLoadingErrorWithoutStarting() {
activity.startActivity(request("first"))
protons.protonProblem = "Checksum verification failed"
protons.protonBusyId = null
advance()
assertTrue(loading().ended)
assertEquals("Checksum verification failed", loading().step)
assertNull(shadowOf(activity).nextStartedActivity)
}
@Test fun repeatedLaunchesDoNotReplaceThePendingGame() {
activity.startActivity(request("first"))
activity.startActivity(request("second"))
protons.protonBusyId = null
advance()
assertEquals("first", shadowOf(activity).nextStartedActivity.getStringExtra(SessionService.EXTRA_STEAM_URL))
assertNull(shadowOf(activity).nextStartedActivity)
}
@Test fun anInstallOutsideTheLauncherUsesIndeterminateProgress() {
protons.protonBusyId = null
installing(true)
activity.startActivity(request("first"))
assertEquals(-1, loading().percent)
assertNull(shadowOf(activity).nextStartedActivity)
installing(false)
advance()
assertNotNull(shadowOf(activity).nextStartedActivity)
}
@Test fun finishingInTheBackgroundWaitsUntilTheLauncherIsVisible() {
activity.startActivity(request("first"))
ReflectionHelpers.setField(activity, "compatLaunchVisible", false)
protons.protonBusyId = null
advance()
assertNull(shadowOf(activity).nextStartedActivity)
ReflectionHelpers.setField(activity, "compatLaunchVisible", true)
advance()
assertNotNull(shadowOf(activity).nextStartedActivity)
}
@Test fun aRestoredCompletedRequestWaitsForResume() {
activity.startActivity(request("first"))
val saved = save()
cancel()
protons.protonBusyId = null
recreate(saved)
advance()
assertNull(shadowOf(activity).nextStartedActivity)
ReflectionHelpers.setField(activity, "compatLaunchVisible", true)
advance()
assertEquals("first", shadowOf(activity).nextStartedActivity.getStringExtra(SessionService.EXTRA_STEAM_URL))
}
@Test fun overlappingPackageWorkKeepsTheOriginalLaunchUntilItFinishes() {
activity.startActivity(request("first"))
setString("setPkgStage", "Installing desktop")
ReflectionHelpers.callInstanceMethod<Void>(activity, "setPkgPercent", ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 64))
protons.protonBusyId = null
advance()
assertNotNull(waiting())
assertNull(shadowOf(activity).nextStartedActivity)
assertEquals("Installing desktop", loading().step)
assertEquals(64, loading().percent)
setString("setPkgStage", null)
advance()
assertEquals("first", shadowOf(activity).nextStartedActivity.getStringExtra(SessionService.EXTRA_STEAM_URL))
advance()
assertNull(shadowOf(activity).nextStartedActivity)
}
@Test fun overlappingRuntimeWorkDoesNotDropThePendingLaunch() {
activity.startActivity(request("first"))
setString("setStage", "Updating runtime")
ReflectionHelpers.callInstanceMethod<Void>(activity, "setBusy", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true))
protons.protonBusyId = null
advance()
assertNotNull(waiting())
assertNull(shadowOf(activity).nextStartedActivity)
assertEquals("Updating runtime", loading().step)
ReflectionHelpers.callInstanceMethod<Void>(activity, "setBusy", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, false))
advance()
assertEquals("first", shadowOf(activity).nextStartedActivity.getStringExtra(SessionService.EXTRA_STEAM_URL))
}
@Test fun aPackageDownloadStillBlocksTheLaunchAfterRecreationAndReportsOldWorkerProgress() {
activity.startActivity(request("first"))
setString("setPkgStage", "Downloading AppImage")
ReflectionHelpers.callInstanceMethod<Void>(activity, "setPkgPercent", ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 23))
val workerActivity = activity
val saved = save()
cancel()
recreate(saved)
ReflectionHelpers.setField(activity, "compatLaunchVisible", true)
protons.protonBusyId = null
advance()
assertNotNull(waiting())
assertNull(shadowOf(activity).nextStartedActivity)
assertEquals("Downloading AppImage", loading().step)
assertEquals(23, loading().percent)
android.os.Handler(Looper.getMainLooper()).post {
setString("setPkgStage", "Placing AppImage", workerActivity)
ReflectionHelpers.callInstanceMethod<Void>(workerActivity, "setPkgPercent", ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 90))
}
advance()
assertEquals("Placing AppImage", loading().step)
assertEquals(90, loading().percent)
assertNull(shadowOf(activity).nextStartedActivity)
android.os.Handler(Looper.getMainLooper()).post { setString("setPkgStage", null, workerActivity) }
advance()
assertEquals("first", shadowOf(activity).nextStartedActivity.getStringExtra(SessionService.EXTRA_STEAM_URL))
advance()
assertNull(shadowOf(activity).nextStartedActivity)
}
@Test fun aFailedInstallAfterRecreationKeepsItsProgressAndError() = recreationFailure(false)
@Test fun aFailedInstallBeforeRestorationStillShowsItsError() = recreationFailure(true)
private fun recreationFailure(finishBeforeRestore: Boolean) {
val entered = CountDownLatch(1)
val finish = CountDownLatch(1)
protons.protonBusyId = null
protons.installer = { _, progress ->
progress("Verifying download", 64)
entered.countDown()
check(finish.await(5, TimeUnit.SECONDS))
"Checksum verification failed"
}
try {
protons.installProton("droiddeck")
assertTrue(entered.await(5, TimeUnit.SECONDS))
activity.startActivity(request("first"))
val saved = save()
cancel()
if (finishBeforeRestore) {
finish.countDown()
waitForInstall()
}
recreate(saved)
if (!finishBeforeRestore) {
advance()
assertEquals(64, loading().percent)
finish.countDown()
waitForInstall()
}
ReflectionHelpers.setField(activity, "compatLaunchVisible", true)
advance()
assertEquals("Checksum verification failed", loading().step)
assertTrue(loading().ended)
assertNull(shadowOf(activity).nextStartedActivity)
} finally {
finish.countDown()
waitForInstall()
}
}
private fun waitForInstall() {
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (protons.protonBusyId != null && System.nanoTime() < deadline) {
shadowOf(Looper.getMainLooper()).idle()
Thread.sleep(10)
}
assertNull(protons.protonBusyId)
}
private fun save() = Bundle().also {
ReflectionHelpers.callInstanceMethod<Void>(activity, "saveCompatLaunch", ReflectionHelpers.ClassParameter.from(Bundle::class.java, it))
}
private fun recreate(saved: Bundle) {
activity = Robolectric.buildActivity(FrontEndActivity::class.java).get()
protons = ReflectionHelpers.getField(activity, "protons")
ReflectionHelpers.callInstanceMethod<Void>(activity, "restoreCompatLaunch", ReflectionHelpers.ClassParameter.from(Bundle::class.java, saved))
}
private fun setString(method: String, value: String?, target: FrontEndActivity = activity) {
ReflectionHelpers.callInstanceMethod<Void>(target, method, ReflectionHelpers.ClassParameter.from(String::class.java, value))
}
private fun request(url: String) = Intent(activity, SessionActivity::class.java).putExtra(SessionService.EXTRA_STEAM_URL, url)
private fun installing(on: Boolean) = ReflectionHelpers.setStaticField(ProtonExtras::class.java, "installInProgress", on)
private fun waiting(): Any? = ReflectionHelpers.callInstanceMethod(activity, "getCompatLaunch")
private fun loading(): LoadingState = ReflectionHelpers.getField(requireNotNull(waiting()), "loading")
private fun cancel() { ReflectionHelpers.callInstanceMethod<Void>(activity, "cancelCompatLaunch") }
private fun advance() = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(250))
}
@@ -56,10 +56,6 @@ class ProtonMenuAutoTest {
.put("tag", "${tool.prefix}-11-12").put("at", System.currentTimeMillis()))
File(activity.filesDir, "proton-latest.json").writeText(latest.toString())
menu = ProtonMenu(activity, Handler(Looper.getMainLooper())) { idle }
menu.protonBusyId = null
menu.protonProblem = null
menu.protonStage = null
menu.protonPercent = -1
menu.installer = { tool, progress ->
progress("Installing ${tool.name}", 50)
install("${tool.prefix}-11-12")
@@ -68,10 +64,6 @@ class ProtonMenuAutoTest {
}
@After fun reset() {
menu.protonBusyId = null
menu.protonProblem = null
menu.protonStage = null
menu.protonPercent = -1
AutoComponents.online = online
AutoComponents.unfavourable = constrained
SessionState.running = false
@@ -6,6 +6,7 @@ import android.view.Display
import androidx.compose.runtime.MutableState
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
@@ -37,10 +38,12 @@ class GlassesMirrorPacingTest {
val panel = Shadow.extract<ModeDisplay>(activity.display)
panel.supported = arrayOf(mode(1, 60f), mode(2, 90f), mode(3, 120f))
panel.current = panel.supported.last()
SessionState.performanceMode = false
activity.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
}
@After fun cleanup() {
SessionState.performanceMode = false
activity.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
}
@@ -50,7 +53,7 @@ class GlassesMirrorPacingTest {
apply(connected, settings.copy(refreshHz = 90))
expect(2, 90f, 90)
apply(GlassesState(), settings)
expect(3, 120f, SessionPrefs.FPS_UNPACED)
expect(3, 120f, 0)
}
@Test fun retiredSavedLimitsDoNotCapThePhoneOrMirroredOutput() {
@@ -61,13 +64,21 @@ class GlassesMirrorPacingTest {
apply(connected.copy(hz = 120f), settings)
expect(1, 60f, 60)
apply(GlassesState(), settings)
expect(3, 120f, 0)
}
@Test fun performanceModeResumesUnpacedOutputAfterMirrorDisconnects() {
SessionState.performanceMode = true
apply(connected, settings)
expect(1, 60f, 60)
apply(GlassesState(), settings)
expect(3, 120f, SessionPrefs.FPS_UNPACED)
}
@Test fun pacingFollowsThePanelWhenTheSystemKeepsALowerRateThanRequested() {
Shadow.extract<ModeDisplay>(activity.display).current = mode(2, 90f)
apply(GlassesState(), settings)
expect(3, 90f, SessionPrefs.FPS_UNPACED)
expect(3, 90f, 0)
}
private fun apply(state: GlassesState, config: GlassesSettings) {
@@ -40,29 +40,6 @@ class BackQamInputTest {
assertTrue(changes.isEmpty())
}
@Test fun theConfiguredWindowControlsSingleAndDoubleTaps() {
for (window in listOf(100L, 800L)) {
taps.clear()
val configured = BackQamInput(changes::add, taps::add, doubleTapMs = { window })
fun press(action: Int) = configured.onKeyEvent(KeyEvent(action, KeyEvent.KEYCODE_BACK), true)
press(KeyEvent.ACTION_DOWN)
press(KeyEvent.ACTION_UP)
advance(window - 1)
assertTrue(taps.isEmpty())
press(KeyEvent.ACTION_DOWN)
press(KeyEvent.ACTION_UP)
assertEquals(listOf(true), taps)
taps.clear()
press(KeyEvent.ACTION_DOWN)
press(KeyEvent.ACTION_UP)
advance(window - 1)
assertTrue(taps.isEmpty())
advance(1)
assertEquals(listOf(false), taps)
assertTrue(changes.isEmpty())
}
}
@Test fun aHoldStartsAt700msAndNeverProducesATap() {
assertTrue(send(KeyEvent.ACTION_DOWN))
advance(699)
@@ -113,55 +90,6 @@ class BackQamInputTest {
assertEquals(listOf(true, false), changes)
}
@Test fun aChordImmediatelyStartsAHoldAndSuppressesTheTap() {
send(KeyEvent.ACTION_DOWN)
advance(25)
input.onChordInput()
assertEquals(listOf(true), changes)
input.onChordInput()
send(KeyEvent.ACTION_UP)
advance(1000)
assertEquals(listOf(true, false), changes)
assertTrue(taps.isEmpty())
}
@Test fun aChordOnTheSecondPressCancelsBothTapActions() {
send(KeyEvent.ACTION_DOWN)
send(KeyEvent.ACTION_UP)
advance(100)
send(KeyEvent.ACTION_DOWN)
input.onChordInput()
send(KeyEvent.ACTION_UP)
advance(1000)
assertEquals(listOf(true, false), changes)
assertTrue(taps.isEmpty())
}
@Test fun controllerInputAfterBackIsReleasedOrCancelledCannotStartAHold() {
send(KeyEvent.ACTION_DOWN)
send(KeyEvent.ACTION_UP)
input.onChordInput()
advance(500)
assertEquals(listOf(false), taps)
send(KeyEvent.ACTION_DOWN)
input.cancel()
input.onChordInput()
advance(1000)
assertTrue(changes.isEmpty())
}
@Test fun anImmediateChordKeepsAllBackOwnersUntilTheLastRelease() {
send(KeyEvent.ACTION_DOWN, device = 4)
send(KeyEvent.ACTION_DOWN, device = 5)
input.onChordInput()
input.onDeviceRemoved(4)
assertEquals(listOf(true), changes)
send(KeyEvent.ACTION_UP, device = 5)
advance(1000)
assertEquals(listOf(true, false), changes)
assertTrue(taps.isEmpty())
}
@Test fun disabledRoutingPreservesBackNavigation() {
assertFalse(send(KeyEvent.ACTION_DOWN, enabled = false))
assertFalse(send(KeyEvent.ACTION_UP, enabled = false))
@@ -236,53 +236,6 @@ class OnScreenControlsTest {
assertEquals(-1, field(control("ls"), "pressedBy"))
}
@Test fun trackpadFingerKeepsItsOwnStreamWhileAStickIsHeld() {
val forwarded = mutableListOf<Triple<Int, Int, Float>>()
view.onTouchMiss = { forwarded += Triple(it.actionMasked, it.getPointerId(0), it.getX(0)) }
touch(MotionEvent.ACTION_DOWN, 7 to (540f to 400f))
assertTrue(touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 7 to (540f to 400f), 9 to (600f to 200f)))
touch(MotionEvent.ACTION_MOVE, 7 to (500f to 400f), 9 to (650f to 200f))
touch(MotionEvent.ACTION_POINTER_UP or (1 shl 8), 7 to (500f to 400f), 9 to (650f to 200f))
assertEquals(listOf(
Triple(MotionEvent.ACTION_DOWN, 9, 600f),
Triple(MotionEvent.ACTION_MOVE, 9, 650f),
Triple(MotionEvent.ACTION_UP, 9, 650f),
), forwarded)
assertEquals(7, field(control("ls"), "pressedBy"))
assertTrue(value(control("ls"), "kx") < 0f)
}
@Test fun stickPressedAfterTrackpadFingerReachesTheControls() {
val received = mutableListOf<Triple<Int, Int, Int>>()
val trackpad = View(context).apply {
setOnTouchListener { _, event -> received += Triple(event.actionMasked, event.pointerCount, event.getPointerId(0)); true }
}
val root = FrameLayout(context).apply {
isMotionEventSplittingEnabled = true
addView(trackpad, FrameLayout.LayoutParams(1200, 800))
addView(view, FrameLayout.LayoutParams(1200, 800))
measure(View.MeasureSpec.makeMeasureSpec(1200, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.EXACTLY))
layout(0, 0, 1200, 800)
}
fun dispatch(action: Int, vararg pointers: Pair<Int, Pair<Float, Float>>) {
val properties = pointers.map { (id, _) -> MotionEvent.PointerProperties().apply { this.id = id; toolType = MotionEvent.TOOL_TYPE_FINGER } }.toTypedArray()
val coords = pointers.map { (_, position) -> MotionEvent.PointerCoords().apply { x = position.first; y = position.second; pressure = 1f; size = 1f } }.toTypedArray()
val event = MotionEvent.obtain(1000L, time++, action, pointers.size, properties, coords, 0, 0, 1f, 1f, 0, 0, 0, 0)
try { assertTrue(root.dispatchTouchEvent(event)) } finally { event.recycle() }
}
dispatch(MotionEvent.ACTION_DOWN, 0 to (600f to 200f))
dispatch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 0 to (600f to 200f), 1 to (540f to 400f))
dispatch(MotionEvent.ACTION_MOVE, 0 to (640f to 220f), 1 to (500f to 400f))
assertEquals(1, field(control("ls"), "pressedBy"))
assertTrue(value(control("ls"), "kx") < 0f)
dispatch(MotionEvent.ACTION_POINTER_UP or (1 shl 8), 0 to (640f to 220f), 1 to (500f to 400f))
dispatch(MotionEvent.ACTION_UP, 0 to (640f to 220f))
assertEquals(-1, field(control("ls"), "pressedBy"))
assertEquals(Triple(MotionEvent.ACTION_DOWN, 1, 0), received.first())
assertEquals(Triple(MotionEvent.ACTION_UP, 1, 0), received.last())
assertTrue(received.all { it.second == 1 && it.third == 0 })
}
@Test fun adaptiveActivationLeavesFivePixelsAroundButtonHitTargets() {
for (id in listOf("a", "rb")) {
val button = control(id)
@@ -1,11 +1,6 @@
package com.droiddeck.launcher.input
import android.os.Handler
import android.os.Looper
import android.hardware.input.InputManager
import android.view.InputDevice
import android.view.KeyEvent
import android.view.MotionEvent
import com.droiddeck.launcher.session.SessionState
import java.nio.file.Files
import java.time.Duration
@@ -15,16 +10,13 @@ import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.util.ReflectionHelpers
import org.robolectric.shadows.InputDeviceBuilder
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, instrumentedPackages = ["com.droiddeck.launcher.input.FakeInputWriter", "com.droiddeck.launcher.wayland.WaylandCompositor"],
shadows = [JoyConPadTest.RecordingWriter::class, PadBridgeRoutingTest.RegisteredKeyEvent::class,
PadBridgeRoutingTest.RegisteredMotionEvent::class, SessionGestureRoutingTest.CompositorShadow::class])
@Config(sdk = [34], manifest = Config.NONE, instrumentedPackages = ["com.droiddeck.launcher.input.FakeInputWriter"],
shadows = [JoyConPadTest.RecordingWriter::class])
class PadBridgeQamTest {
private val directory = Files.createTempDirectory("qam-pad").toFile()
private lateinit var bridge: PadBridge
@@ -53,7 +45,6 @@ class PadBridgeQamTest {
bridge.applyExternal({}, false)
assertEquals(supported, pad().isDown(PadState.QAM))
bridge.setBackQamPressed(false)
advanceTime()
}
SessionState.deckPad = false
assertFalse(bridge.canHoldQam())
@@ -63,12 +54,10 @@ class PadBridgeQamTest {
bridge.setBackQamPressed(true)
advanceTime()
bridge.applyExternal({ it.press(PadState.X, true); it.press(PadState.SELECT, true) }, true)
advanceTime()
assertTrue(pad().isDown(PadState.QAM))
assertTrue(pad().isDown(PadState.X))
assertTrue(pad().isDown(PadState.SELECT))
bridge.setBackQamPressed(false)
advanceTime()
assertFalse(pad().isDown(PadState.QAM))
assertTrue(pad().isDown(PadState.X))
assertTrue(pad().isDown(PadState.SELECT))
@@ -83,7 +72,6 @@ class PadBridgeQamTest {
bridge.setSystemButtons(false, false)
assertTrue(pad().isDown(PadState.QAM))
bridge.setBackQamPressed(false)
advanceTime()
assertFalse(pad().isDown(PadState.QAM))
}
@@ -118,234 +106,10 @@ class PadBridgeQamTest {
assertFalse(pad().isDown(PadState.QAM))
}
@Test fun aQuickPartnerPressReachesSteamWithQamAndReleasesIndependently() {
val device = controller()
val taps = mutableListOf<Boolean>()
val input = BackQamInput(bridge::setBackQamPressed, taps::add)
bridge.setOnChordInput {
assertFalse(pad().isDown(PadState.X))
input.onChordInput()
}
input.onKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK), true)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(25))
assertTrue(bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_X)))
assertTrue(pad().isDown(PadState.QAM))
assertFalse(pad().isDown(PadState.X))
advance(79)
assertFalse(pad().isDown(PadState.X))
advance(1)
assertTrue(pad().isDown(PadState.X))
input.onKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK), true)
assertFalse(pad().isDown(PadState.QAM))
assertTrue(pad().isDown(PadState.X))
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_X, KeyEvent.ACTION_UP))
advance(80)
assertFalse(pad().isDown(PadState.X))
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1))
assertTrue(taps.isEmpty())
}
@Test fun onlyFreshAcceptedPrimaryControllerPressesPromoteAChord() {
val device = controller()
val second = controller(11)
val promoted = mutableListOf<Boolean>()
bridge.setOnChordInput { promoted.add(true) }
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_X, KeyEvent.ACTION_UP))
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_X, repeat = 1))
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_A))
bridge.onKeyEvent(key(second, KeyEvent.KEYCODE_BUTTON_X))
bridge.setExcluded { it == device.id }
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_X))
assertTrue(promoted.isEmpty())
bridge.setExcluded { false }
for (code in listOf(KeyEvent.KEYCODE_BUTTON_X, KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_BUTTON_L2)) {
bridge.onKeyEvent(key(device, code))
}
assertEquals(3, promoted.size)
}
@Test fun aQuickChordKeepsItsPressAndReleaseAfterTheModifierLead() {
bridge.setBackQamPressed(true)
bridge.applyExternal({ it.press(PadState.X, true) }, true)
advance(20)
bridge.applyExternal({ it.press(PadState.X, false) }, true)
bridge.setBackQamPressed(false)
assertTrue(pad().isDown(PadState.QAM))
assertFalse(pad().isDown(PadState.X))
advance(60)
assertTrue(pad().isDown(PadState.QAM))
assertTrue(pad().isDown(PadState.X))
advance(19)
assertTrue(pad().isDown(PadState.X))
advance(1)
assertFalse(pad().isDown(PadState.X))
assertFalse(pad().isDown(PadState.QAM))
}
@Test fun cancellationDiscardsQueuedPartnersAndTheirReleases() {
val input = BackQamInput(bridge::setBackQamPressed, {}, onCancel = bridge::cancelBackQam)
input.onKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK), true)
input.onChordInput()
bridge.applyExternal({ it.press(PadState.LB, true) }, true)
input.onKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK), true)
input.cancel()
advance(1000)
assertFalse(pad().isDown(PadState.LB))
assertFalse(pad().isDown(PadState.QAM))
bridge.applyExternal({ it.press(PadState.X, true) }, true)
input.cancel()
assertTrue(pad().isDown(PadState.X))
}
@Test fun aSettledHoldDoesNotDelayLaterPartnerInput() {
bridge.setBackQamPressed(true)
advance(80)
bridge.applyExternal({ it.press(PadState.LB, true) }, true)
assertTrue(pad().isDown(PadState.LB))
bridge.setBackQamPressed(false)
assertFalse(pad().isDown(PadState.QAM))
}
@Test fun disconnectingThePartnerControllerDiscardsItsQueuedPress() {
val device = controller()
bridge.setBackQamPressed(true)
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_L1))
advance(20)
bridge.onDeviceRemoved(device.id)
assertTrue(pad().isDown(PadState.QAM))
assertFalse(pad().isDown(PadState.LB))
advance(60)
assertFalse(pad().isDown(PadState.LB))
advance(1000)
assertFalse(pad().isDown(PadState.LB))
assertTrue(pad().isDown(PadState.QAM))
}
@Test fun disconnectingThePartnerControllerImmediatelyReleasesADeliveredPress() {
val device = controller()
bridge.setBackQamPressed(true)
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_L1))
advance(80)
assertTrue(pad().isDown(PadState.LB))
bridge.onDeviceRemoved(device.id)
assertFalse(pad().isDown(PadState.LB))
assertTrue(pad().isDown(PadState.QAM))
advance(1000)
assertFalse(pad().isDown(PadState.LB))
}
@Test fun removingAnotherPlayerDoesNotDiscardThePrimaryPlayersQueuedChord() {
val device = controller()
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_L1, KeyEvent.ACTION_UP))
val other = controller(11)
bridge.onKeyEvent(key(other, KeyEvent.KEYCODE_BUTTON_X, KeyEvent.ACTION_UP))
bridge.setBackQamPressed(true)
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_L1))
bridge.onDeviceRemoved(other.id)
advance(80)
assertTrue(pad().isDown(PadState.LB))
assertTrue(pad().isDown(PadState.QAM))
}
@Test fun pairingOnAnIgnoredRailKeyImmediatelyReleasesDeliveredButtonsAndDropsQueuedOnes() {
val left = controller(product = 0x2006)
bridge.setBackQamPressed(true)
bridge.onKeyEvent(key(left, KeyEvent.KEYCODE_BUTTON_L1))
advance(80)
assertTrue(pad().isDown(PadState.LB))
bridge.onKeyEvent(key(left, KeyEvent.KEYCODE_BUTTON_X))
val right = controller(11, product = 0x2007)
assertTrue(bridge.onKeyEvent(key(right, KeyEvent.KEYCODE_BUTTON_L1, scan = 0x136)))
assertFalse(pad().isDown(PadState.LB))
assertFalse(pad().isDown(PadState.X))
assertTrue(pad().isDown(PadState.QAM))
advance(1000)
assertFalse(pad().isDown(PadState.LB))
assertFalse(pad().isDown(PadState.X))
}
@Test fun queuedReportsUseTheLiveStickAndStopItImmediatelyOnBackRelease() {
bridge.setBackQamPressed(true)
bridge.applyExternal({ it.press(PadState.X, true); it.leftY = -1f }, true)
advance(20)
bridge.applyExternal({ it.leftY = -0.25f }, true)
advance(60)
assertEquals(-0.25f, pad().leftY)
bridge.setBackQamPressed(false)
assertEquals(0f, pad().leftY)
advance(1000)
assertEquals(0f, pad().leftY)
bridge.applyExternal({ it.leftY = 0f }, true)
bridge.applyExternal({ it.leftY = 0.75f }, true)
assertEquals(0.75f, pad().leftY)
}
@Test fun releasingBackDuringTheLeadNeverReplaysAnOldStickMovement() {
bridge.setBackQamPressed(true)
bridge.applyExternal({ it.leftY = -1f }, true)
advance(20)
bridge.setBackQamPressed(false)
advance(1000)
assertEquals(0f, pad().leftY)
assertFalse(pad().isDown(PadState.QAM))
}
@Test fun theInitialPartnerKeepsItsDurationWhenReleasedAfterTheLead() {
bridge.setBackQamPressed(true)
bridge.applyExternal({ it.press(PadState.X, true) }, true)
advance(100)
bridge.applyExternal({ it.press(PadState.X, false) }, true)
assertTrue(pad().isDown(PadState.X))
advance(79)
assertTrue(pad().isDown(PadState.X))
advance(1)
assertFalse(pad().isDown(PadState.X))
}
@Test fun deliberateStickTriggerAndHatMotionPromoteChordsButNeutralAndDriftDoNot() {
val device = controller()
val promoted = mutableListOf<Boolean>()
bridge.setOnChordInput { promoted.add(true) }
for ((axis, value) in listOf(MotionEvent.AXIS_X to 0f, MotionEvent.AXIS_X to 0.1f,
MotionEvent.AXIS_LTRIGGER to 0f, MotionEvent.AXIS_HAT_Y to 0f)) motion(device, axis, value)
assertTrue(promoted.isEmpty())
for ((axis, value) in listOf(MotionEvent.AXIS_X to -0.15f, MotionEvent.AXIS_LTRIGGER to 0.75f,
MotionEvent.AXIS_HAT_Y to -1f)) motion(device, axis, value)
assertEquals(3, promoted.size)
}
private fun controller(id: Int = 10, product: Int = 0): InputDevice {
val builder = InputDeviceBuilder.newBuilder().setId(id).setName("QAM pad $id")
.setVendorId(if (product == 0) 0 else 0x057e).setProductId(product)
.setDescriptor("qam-pad-$id").setExternal(true).setKeyboardType(InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC)
.setSources(InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK)
for (axis in listOf(MotionEvent.AXIS_X, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_HAT_Y)) {
builder.addMotionRange(axis, InputDevice.SOURCE_JOYSTICK, 0f, 1f, 0f, 0f, 0f)
}
return builder.build().also {
shadowOf(RuntimeEnvironment.getApplication().getSystemService(InputManager::class.java)).addInputDevice(it)
bridge.applyExternal({}, false)
}
}
private fun key(device: InputDevice, code: Int, action: Int = KeyEvent.ACTION_DOWN, repeat: Int = 0, scan: Int = 0) =
KeyEvent(0L, 0L, action, code, repeat, 0, device.id, scan, 0, InputDevice.SOURCE_GAMEPAD)
private fun motion(device: InputDevice, axis: Int, value: Float) {
val event = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_MOVE, 1,
arrayOf(MotionEvent.PointerProperties().apply { id = 0 }),
arrayOf(MotionEvent.PointerCoords().apply { setAxisValue(axis, value) }),
0, 0, 1f, 1f, device.id, 0, InputDevice.SOURCE_JOYSTICK, 0)
try { assertTrue(bridge.onMotionEvent(event)) } finally { event.recycle() }
}
private fun pad() = requireNotNull(JoyConPadTest.RecordingWriter.pads[0])
private fun advanceTime() {
val handler = ReflectionHelpers.getStaticField<Handler>(PadBridge::class.java, "chordHandler")
shadowOf(handler.looper).idleFor(Duration.ofSeconds(2))
advance(2000)
}
private fun advance(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ms))
}
@@ -1,14 +0,0 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Test
class OutputPacingTest {
@Test fun phoneOutputIsUnpaced() {
assertEquals(SessionPrefs.FPS_UNPACED, SessionPrefs.compositorFpsLimit(0))
}
@Test fun mirroringKeepsTheGlassesRate() {
assertEquals(60, SessionPrefs.compositorFpsLimit(60))
}
}
@@ -0,0 +1,36 @@
package com.droiddeck.launcher.session
import android.content.Context
import org.junit.Assert.*
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
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class PerformanceModeTest {
private val app get() = RuntimeEnvironment.getApplication()
private val session get() = app.getSharedPreferences("session", Context.MODE_PRIVATE)
@Before fun clear() { session.edit().clear().commit() }
@Test fun offByDefaultAndPerMode() {
assertFalse(SessionPrefs.performanceMode(app, SessionService.MODE_STEAM))
SessionPrefs.setPerformanceMode(app, SessionService.MODE_STEAM, true)
assertTrue(SessionPrefs.performanceMode(app, SessionService.MODE_STEAM))
assertFalse(SessionPrefs.performanceMode(app, SessionService.MODE_DESKTOP))
}
@Test fun offKeepsDisplayAndMirrorPacing() {
assertEquals(0, SessionPrefs.compositorFpsLimit(0, false))
assertEquals(60, SessionPrefs.compositorFpsLimit(60, false))
}
@Test fun onIsUnpacedUnlessMirroring() {
assertEquals(SessionPrefs.FPS_UNPACED, SessionPrefs.compositorFpsLimit(0, true))
assertEquals(60, SessionPrefs.compositorFpsLimit(60, true))
}
}
@@ -27,7 +27,6 @@ class SettingsResetTest {
@Test fun settingsGoBackToTheirDefaults() {
SessionPrefs.setTheme(app, "ocean")
SessionPrefs.setBackDoubleTapMs(app, 100)
SessionPrefs.setUnfoldedControlsWithController(app, true)
SessionPrefs.setNoXalia(app, false)
session.edit().putInt("fpsLimit.steam", 30).commit()
@@ -47,7 +46,6 @@ class SettingsResetTest {
assertTrue(SettingsReset.resetAll(app, gameProfiles = false))
assertEquals("graphite", SessionPrefs.theme(app))
assertEquals(500, SessionPrefs.backDoubleTapMs(app))
assertFalse(SessionPrefs.unfoldedControlsWithController(app))
assertTrue(SessionPrefs.noXalia(app))
assertFalse(session.contains("fpsLimit.steam"))
@@ -1,63 +0,0 @@
package com.droiddeck.launcher.ui
import android.content.Intent
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.input.InputModeManager
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsFocused
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performKeyInput
import androidx.compose.ui.test.pressKey
import androidx.compose.ui.test.requestFocus
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
@OptIn(androidx.compose.ui.test.ExperimentalTestApi::class, androidx.compose.ui.ExperimentalComposeUiApi::class)
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], qualifiers = "w360dp-h640dp-port", application = android.app.Application::class)
class GameResourcesRowTest {
@get:Rule val compose = createRobolectricComposeRule()
private val ctx get() = RuntimeEnvironment.getApplication()
private val game = Library.SteamGame(292030, "The Witcher 3", null, "/steam")
@Test fun everyResourceIsReachableOnANarrowPageAndOpensTheExpectedBrowserUrl() {
compose.setContent { DroidDeckTheme { GameResourcesRow(game.name, game) } }
for (link in gameResources(game.name, game)) {
compose.onNodeWithText(ctx.getString(link.label)).assertIsDisplayed().performClick()
val intent = shadowOf(ctx).nextStartedActivity
assertEquals(Intent.ACTION_VIEW, intent.action)
assertEquals(link.url, intent.dataString)
}
}
@Test fun controllerCanMoveBetweenLinksAndOpenAResource() {
lateinit var inputMode: InputModeManager
compose.setContent { DroidDeckTheme {
inputMode = LocalInputModeManager.current
GameResourcesRow(game.name, game)
} }
compose.runOnIdle { inputMode.requestInputMode(InputMode.Keyboard) }
compose.onNodeWithText(ctx.getString(R.string.game_resource_pcgw)).requestFocus().assertIsFocused().performKeyInput { pressKey(Key.DirectionRight) }
compose.onNodeWithText(ctx.getString(R.string.game_resource_guides)).assertIsFocused().performKeyInput { pressKey(Key.ButtonA) }
assertEquals(gameResources(game.name, game)[1].url, shadowOf(ctx).nextStartedActivity.dataString)
}
@Test @Config(qualifiers = "w640dp-h360dp-land")
fun shortLandscapeWindowsKeepEveryResourceVisible() {
compose.setContent { DroidDeckTheme { GameResourcesRow(game.name, game) } }
for (link in gameResources(game.name, game)) {
compose.onNodeWithText(ctx.getString(link.label)).assertIsDisplayed()
}
}
}
@@ -1,43 +0,0 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import java.net.URI
import java.net.URLDecoder
class GameResourcesTest {
@Test fun searchesPreserveUnicodeAndEscapeQueryDelimiters() {
val title = "Ōkami HD & friends + 100% #1?"
val links = gameResources(" $title ", null)
assertEquals(3, links.size)
links.forEach { link ->
val uri = URI(link.url)
assertEquals("https", uri.scheme)
assertEquals(null, uri.fragment)
assertEquals(title, URLDecoder.decode(uri.rawQuery.substringAfter('='), "UTF-8"))
}
}
@Test fun onlySteamClientGamesGetAppSpecificSteamResources() {
val steam = Library.SteamGame(292030, "The Witcher 3", null, "/steam")
val links = gameResources(steam.name, steam)
assertEquals("https://www.protondb.com/app/292030", links.single { it.label == R.string.game_resource_protondb }.url)
assertEquals("https://store.steampowered.com/account/remotestorageapp/?appid=292030", links.single { it.label == R.string.game_resource_steam_cloud }.url)
val others = listOf(
Library.SteamGame(292030, steam.name, null, Library.ADDED),
Library.SteamGame(292030, steam.name, null, Library.ADDED, source = "gog", storeId = "292030"),
Library.SteamGame(292030, steam.name, null, Library.XBOX_CLOUD, source = "xbox"),
Library.SteamGame(-1, steam.name, null, "/steam"),
)
others.forEach { game ->
assertEquals(3, gameResources(game.name, game).size)
}
}
@Test fun loadingPagesHaveNoResourcesUntilTheyHaveATitle() {
assertTrue(gameResources(" ", null).isEmpty())
}
}
+33
View File
@@ -0,0 +1,33 @@
# DroidDeck changes to the vendored OpenNOW code
Upstream: OpenCloudGaming/OpenNOW a49b124c. Each change keeps upstream behaviour on
Windows, macOS and Linux.
- `opennow-core/src/update_apply/{process,security,mod,managed,recovery}.rs`: the
Linux-only process, ACL and boot-id helpers also cover Android (`target_os =
"android"`), so the core compiles for aarch64-linux-android. DroidDeck never runs
the self-updater.
- `opennow-streamer/Cargo.toml`: the workspace lists only the vendored crates; the
Linux/macOS platform crates, the Qt FFI crate, the dev host and the ffmpeg/cros-codecs
patches are not vendored (DroidDeck builds Android only).
- `opennow-streamer-platform`:
- `src/media_types.rs`: the shared media types moved out of `media.rs` unchanged;
`media.rs` re-exports them.
- `src/lib.rs` → `src/desktop_lib.rs` (upstream's crate root, unchanged apart from the
`queue`/`video_queue` declarations, now in the new `lib.rs`); `src/lib.rs` includes it
on desktop and uses the new `src/android/` module on Android.
- `src/video_queue.rs`: imports `EncodedFrame` from `media_types`.
- `src/android/` (new, DroidDeck): MediaCodec decoding onto an app-supplied Surface,
Opus → AAudio playback, the same public runtime/session/sink types as the desktop
backends; recording, replay and the microphone report "not available".
- `Cargo.toml`: SDL2, openh264, the recording muxers and the Windows crate are
desktop-only; Android adds `ndk`, `ndk-sys`, `jni`, `log`.
- `opennow-streamer/vendor/mtu` (new, DroidDeck): mozilla's `mtu` 0.3.0 (MIT/Apache-2.0)
with one change in `build.rs`: on Android, bindgen gets a versioned target
(`--target=<triple>29`), since the NDK headers reject an unversioned triple and
cargo-ndk's bindgen arguments do not carry the API level. Patched in from
`opennow-streamer/Cargo.toml` and DroidDeck's `app/src/main/rust/gfn/Cargo.toml`.
- `opennow-core/src/credential_vault.rs`: on Android the vault's "OS store" declines every
write (`AndroidNoSecretStore`), so sessions go to the JSON fallback store in the app's
private data directory. keyring has no Android backend and uses an in-memory mock there,
which accepted the session and lost it whenever the core restarted.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Zortos
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+17
View File
@@ -0,0 +1,17 @@
# OpenNOW (vendored)
This folder holds parts of **OpenNOW**, an open-source GeForce NOW client by
**Zortos** ([zortos293](https://github.com/zortos293)) and the OpenNOW contributors:
<https://github.com/OpenCloudGaming/OpenNOW>, MIT License (see `LICENSE`).
Imported from OpenCloudGaming/OpenNOW commit `a49b124ce31e87113fd4961f6a321fbf0ad1fdc5`
(2026-10-18). Only the parts DroidDeck's GeForce NOW store uses are kept:
- `native/opennow-core`: accounts, sign-in, catalog and CloudMatch session services
(newline-delimited JSON over stdin/stdout, `docs/core-protocol.md`).
- `native/opennow-streamer`: the native NVST streamer (protocol, transport, core,
platform, FFI) plus its vendored `str0m` and `audiopus-sys`.
DroidDeck's own changes to these files are listed in `CHANGES.md`. NVIDIA and
GeForce NOW are trademarks of NVIDIA Corporation; neither OpenNOW nor DroidDeck is
affiliated with or endorsed by NVIDIA.
File diff suppressed because it is too large. Load diff
+69
View File
@@ -0,0 +1,69 @@
# Qt native streamer lifecycle events
ABI version 13 delivers these events through the generic JSON event callback
without a new C ABI layout.
The native streamer owns wire parsing and termination classification. Qt does not
infer resumability from a wire code or reason.
## Session timers
```json
{"type":"session-timer","startId":"start-42","timerType":4,"secondsLeft":60,"active":true}
```
`timerType` is 4 or 5, `secondsLeft` is an unsigned 32-bit integer, and `active`
is a boolean. `NativeStreamRuntime` validates these fields and emits
`sessionTimerReceived(quint8, quint32, bool)` on the Qt thread. Malformed timer
events do not reach QML. `startId` must match the current start-command generation.
Timer events from a replaced or stopped session, or a previous runtime instance,
are discarded.
`ShellStore.acceptSessionTimer` owns warning state for the current stream. Type 4
with `active:true` starts a display-only countdown from the server-provided seconds.
The countdown clamps at zero and never clears the warning or ends the session.
Type 4 with `active:false` clears the warning after the transport confirms successful input. Type 5 clears
the warning. Qt neither clears on local input submission nor ends a session when
a timer arrives. Session end, replacement, native restart, and terminal native
status also clear the warning.
Both desktop and console compose `StreamIdleWarning` above the same
`StreamVideoItem`. It has no input handlers, focus requests, or overlay route, so
it does not pause gameplay input or recreate the session. A refreshed server timer
resets the display-only countdown.
## Server termination
Terminal error and status events can include this object:
```json
{"source":"nvst-server","code":"server-terminated","startId":"start-42","wireCode":2147680291,"reason":56,"extendedCode":2147680263,"resumable":false}
```
`reason` and `extendedCode` can be null. `resumable` can be true, false, or null.
The native streamer retains the numeric values through the existing JSON callback.
Qt rejects server termination events whose `startId` does not match the current
start-command generation, before invalidating input or presentation. The matching
error and stopped pair can both arrive after presentation has been invalidated.
Qt treats `nvst-server` with `code:"server-terminated"` and `resumable:false` as an
authoritative session end, cancels pending recovery, and never auto-resumes that
session. It retains the server message in `lastError` and the accessibility
announcement, and the full termination object in the streamer snapshot.
True or unknown classification follows the existing bounded
CloudMatch reconciliation path. Existing authoritative CloudMatch status 7 and
HTTP 404 handling remains unchanged.
The evidence baseline is `reports/opennow-gfn-parity/audio-input-lifecycle.md`,
rows L3 through L5, and Windows `transport-feedback.md`, section 8. Offline Qt
callback, orchestration, and smoke tests cover delivery and passive composition;
they do not connect to GFN or execute GFN binaries.
## Text retry feedback
`text-input-error` carries the current `startId` and a fixed `reason`, with no
paste contents. C++ rejects stale generations before forwarding it through the
existing `eventReceived` signal. ShellStore announces localized retry feedback,
without changing streamer state, input ownership, error telemetry, or incidents.
Desktop and console display it for five seconds in the existing passive input
notice, including when the Guide is closed. The normal stream video item and
gameplay focus remain unchanged. Temporary SCTP deferral queues one bounded paste
behind older input; only rejected local paste admission needs this notice.
+3128
View File
File diff suppressed because it is too large. Load diff
+47
View File
@@ -0,0 +1,47 @@
[package]
name = "opennow-core"
version = "1.0.0"
edition = "2024"
license = "MIT"
rust-version = "1.85"
[dependencies]
aes-gcm = "0.10"
base64 = "0.22"
chrono = { version = "0.4", default-features = false, features = ["clock"] }
ed25519-dalek = "2.2"
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
hkdf = "0.12"
httpdate = "1"
md5 = "0.7"
keyring = { version = "3.6", features = ["apple-native", "windows-native", "sync-secret-service", "crypto-rust"] }
p256 = { version = "0.13", features = ["ecdh", "pkcs8"] }
qrcode = { version = "0.14", default-features = false }
rand = "0.9"
regex = "1"
reqwest = { version = "0.12", default-features = false, features = ["blocking", "json", "multipart", "rustls-tls", "socks"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
hmac = "0.12"
icu_normalizer = { version = "2.1", default-features = false, features = ["compiled_data"] }
scrypt = "0.11"
semver = "1"
subtle = "2"
url = "2"
webpki-roots = "1"
zip = { version = "2.4", default-features = false, features = ["deflate"] }
fs2 = "0.4"
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_System_Threading", "Win32_System_JobObjects", "Win32_System_ProcessStatus", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_SystemServices", "Win32_System_IO", "Win32_Storage_FileSystem", "Wdk_System_Threading"] }
[dev-dependencies]
tempfile = "3"
[profile.release]
lto = "thin"
codegen-units = 1
strip = true
@@ -0,0 +1,116 @@
{
"version": 1,
"source": "opennow-stable/src/shared/gfn/api.ts:OpenNowApi",
"columns": ["legacy", "kind", "requestSchema", "resultSchema", "owner", "replacement", "status", "requestFixture", "resultFixture"],
"operations": [
["getAuthSession","request","AuthSessionRequest | undefined","AuthSessionResult","core","auth.session.get","ported",{}, {"session":null}],
["getLoginProviders","request","void","LoginProvider[]","core","auth.providers.list","ported",{}, []],
["getRegions","request","RegionsFetchRequest | undefined","StreamRegion[]","core","network.regions.list","ported",{}, []],
["login","request","AuthLoginRequest","AuthSession","core","auth.device.start + auth.device.poll + auth.device.complete","superseded",{"provider":"nvidia"},{"session":null}],
["startDeviceLogin","request","AuthDeviceLoginStartRequest","AuthDeviceLoginChallenge","core","auth.device.start","ported",{"provider":"nvidia"},{"attemptId":"fixture","userCode":"ABCD-EFGH"}],
["pollDeviceLogin","request","AuthDeviceLoginPollRequest","AuthDeviceLoginPollResult","core","auth.device.poll","ported",{"attemptId":"fixture","deviceCode":"redacted-fixture"},{"status":"pending"}],
["completeDeviceLogin","request","AuthDeviceLoginAttemptRequest","AuthSession","core","auth.device.complete","ported",{"attemptId":"fixture"},{"session":null}],
["cancelDeviceLogin","request","AuthDeviceLoginAttemptRequest","void","core","auth.device.cancel","ported",{"attemptId":"fixture"},null],
["logout","request","void","void","core","auth.logout","ported",{},null],
["logoutAll","request","void","void","core","auth.accounts.logoutAll","ported",{},null],
["getSavedAccounts","request","void","SavedAccount[]","core","auth.accounts.list","ported",{},[]],
["switchAccount","request","{userId:string,pin?:string}","AuthSession","core","auth.accounts.switch","ported",{"userId":"fixture-user"},{"session":null}],
["removeAccount","request","{userId:string}","void","core","auth.accounts.remove","ported",{"userId":"fixture-user"},null],
["getConsolePinStatus","request","{userId:string}","ConsolePinStatus","core","auth.pin.status","ported",{"userId":"fixture-user"},{"configured":false}],
["setConsolePin","request","ConsolePinSetRequest","ConsolePinMutationResult","core","auth.pin.set","ported",{"userId":"fixture-user","pin":"0000"},{"ok":true}],
["clearConsolePin","request","ConsolePinClearRequest","ConsolePinMutationResult","core","auth.pin.clear","ported",{"userId":"fixture-user","pin":"0000"},{"ok":true}],
["verifyConsolePin","request","ConsolePinVerifyRequest","ConsolePinVerifyResult","core","auth.pin.verify","ported",{"userId":"fixture-user","pin":"0000"},{"verified":true}],
["fetchSubscription","request","SubscriptionFetchRequest","SubscriptionInfo","core","account.subscription.get","ported",{},{}],
["fetchPersistentStorageLocations","request","PersistentStorageLocationsFetchRequest | undefined","PersistentStorageLocationsResult","core","account.storage.locations","ported",{}, {"locations":[]}],
["resetPersistentStorage","request","PersistentStorageResetRequest | undefined","PersistentStorageResetResult","core","account.storage.reset","ported",{}, {"ok":true}],
["fetchGameAccountConnections","request","void","GameAccountConnectionsResult","core","account.connections.list","ported",{}, {"connections":[]}],
["linkGameAccount","request","GameAccountOperationRequest","GameAccountOperationResult","core","account.connections.link.start + account.connections.link.poll","superseded",{"provider":"steam"},{"status":"pending"}],
["unlinkGameAccount","request","GameAccountOperationRequest","GameAccountOperationResult","core","account.connections.unlink","ported",{"provider":"steam"},{"ok":true}],
["resyncGameAccount","request","GameAccountOperationRequest","GameAccountOperationResult","core","account.connections.sync","ported",{"provider":"steam"},{"ok":true}],
["fetchMainGames","request","GamesFetchRequest","GameInfo[]","core","catalog.public.list","superseded",{},[]],
["fetchStorePanels","request","GamesFetchRequest","GamePanelResult[]","core","catalog.public.list + Qt catalog projection","superseded",{},[]],
["fetchFeaturedGames","request","GamesFetchRequest","GameInfo[]","core","catalog.public.list + Qt featured projection","superseded",{},[]],
["fetchLibraryGames","request","GamesFetchRequest","GameInfo[]","core","catalog.library.list","ported",{},[]],
["browseCatalog","request","CatalogBrowseRequest","CatalogBrowseResult","core","catalog.public.list + Qt filters","superseded",{}, {"games":[]}],
["fetchPublicGames","request","void","GameInfo[]","core","catalog.public.list","ported",{},[]],
["resolveLaunchAppId","request","ResolveLaunchIdRequest","string | null","core","catalog public/library normalized launchAppId","superseded",{"appId":"123"},"123"],
["resolveStoreUrl","request","ResolveStoreUrlRequest","string | null","core","catalog normalized storeUrl","superseded",{"appId":"123"},null],
["markGameOwned","request","MarkGameOwnedRequest","MarkGameOwnedResult","core","account.connections.sync + catalog.library.list","superseded",{"appId":"123"},{"ok":true}],
["getPendingDirectLaunchRequest","request","void","DirectLaunchRequest | null","qt","AppController.handleArguments","superseded",{},null],
["onDirectLaunchRequest","event","void","DirectLaunchRequest","qt","AppController.directLaunchRequested","ported",{}, {"appId":"123","title":"Fixture Game"}],
["createSession","request","SessionCreateRequest","SessionInfo","core","session.create","ported",{"appId":"123"},{"status":1}],
["pollSession","request","SessionPollRequest","SessionInfo","core","session.poll","ported",{"sessionId":"fixture-session"},{"status":1}],
["reportSessionAd","request","SessionAdReportRequest","SessionInfo","core","session.ad.report","ported",{"sessionId":"fixture-session"},{"status":1}],
["stopSession","request","SessionStopRequest","void","core","session.stop","ported",{"sessionId":"fixture-session"},null],
["getActiveSessions","request","{token?:string,streamingBaseUrl?:string}","ActiveSessionInfo[]","core","session.remote.list","ported",{},[]],
["claimSession","request","SessionClaimRequest","SessionInfo","core","session.claim","ported",{"sessionId":"fixture-session"},{"status":2}],
["getNativeStreamerStatus","request","void","NativeStreamerStatus","core","streamer.status.get","ported",{}, {"state":"idle"}],
["getNativeCloudGsyncCapabilities","request","void","NativeCloudGsyncCapabilities","streamer","capabilities event surfaced by streamer.status.get","superseded",{}, {"supported":false}],
["showSessionConflictDialog","request","void","SessionConflictChoice","qt","SessionConflictScreen","ported",{},"cancel"],
["connectSignaling","request","SignalingConnectRequest","void","core","streamer.start owns signaling lifecycle","superseded",{},null],
["disconnectSignaling","request","void","void","core","streamer.stop owns signaling lifecycle","superseded",{},null],
["sendAnswer","request","SendAnswerRequest","void","core","streamer.start child protocol relay","superseded",{},null],
["sendIceCandidate","request","IceCandidatePayload","void","core","streamer.start child protocol relay","superseded",{},null],
["sendNativeInput","send","NativeInputPacket","void","streamer","native input transport","superseded",{"kind":"keyboard"},null],
["setNativeInputPaused","send","boolean","void","core","streamer.input.pause","ported",{"paused":true},null],
["updateNativeRenderSurface","send","NativeRenderSurfaceUpdate","void","core","streamer.surface.update","ported",{"visible":true},null],
["updateNativeShortcuts","send","NativeStreamerShortcutBindings","void","streamer","streamer.start shortcut bindings","superseded",{},null],
["requestKeyframe","request","KeyframeRequest","void","core","streamer.control request-keyframe","superseded",{},null],
["onSignalingEvent","event","void","MainToRendererSignalingEvent","core","streamer.changed event","superseded",{}, {"type":"status"}],
["onToggleFullscreen","event","void","void","qt","streamer shortcut routed through ShellStore","superseded",{},null],
["onExitFullscreen","event","void","void","qt","deterministic overlay/back handling","superseded",{},null],
["quitApp","request","void","void","qt","QCoreApplication.quit","ported",{},null],
["getUpdaterState","request","void","AppUpdaterState","core","updater.state.get","ported",{}, {"status":"idle"}],
["checkForUpdates","request","void","AppUpdaterState","core","updater.check","ported",{}, {"status":"not-available"}],
["downloadUpdate","request","void","AppUpdaterState","core","updater.download","ported",{}, {"status":"downloaded"}],
["installUpdateAndRestart","request","void","AppUpdaterState","core","updater.install","ported",{}, {"status":"installing"}],
["onUpdaterStateChanged","event","void","AppUpdaterState","core","updater.changed event","ported",{}, {"status":"idle"}],
["setFullscreen","request","boolean","void","qt","Window visibility/fullscreen state","ported",{"value":true},null],
["toggleFullscreen","request","void","void","qt","Window visibility/fullscreen state","ported",{},null],
["togglePointerLock","request","void","void","streamer","native input ownership contract","superseded",{},null],
["notifyPointerLockChange","send","{active:boolean,suppressEscapeFullscreenGrace?:boolean}","void","streamer","native input ownership contract","superseded",{"active":true},null],
["notifyNativeInputModeChange","send","{active:boolean,rawInputOwnsEscape:boolean}","void","streamer","streamer.input.pause + native ownership","superseded",{"active":true,"rawInputOwnsEscape":true},null],
["readClipboardText","request","void","string","qt","AppController.readClipboardText","ported",{},"fixture text"],
["getSettings","request","void","Settings","core","settings.get","ported",{},{}],
["setSetting","request","{key:keyof Settings,value:Settings[key]}","void","core","settings.set","ported",{"key":"resolution","value":"1920x1080"},null],
["getGpuInfo","request","void","GpuBackendInfo","core","streamer.detect","superseded",{}, {"gpuName":null,"hardwareDecodeCodecs":[]}],
["resetSettings","request","void","Settings","core","settings.reset","ported",{},{}],
["selectNativeStreamerExecutable","request","void","string | null","qt","AppController.normalizeNativeStreamerExecutable + FileDialog","ported",{},null],
["getMicrophonePermission","request","void","MicrophonePermissionResult","streamer","native microphone permission/start status","superseded",{}, {"status":"unknown"}],
["exportLogs","request","'text' | 'json' | undefined","string","core","diagnostics.export","ported",{"format":"text"},"/tmp/opennow-diagnostics.txt"],
["submitBugReport","request","DesktopBugReportRequest","DesktopBugReportReceipt","core","bug_report.submit","ported",{"summary":"Fixture report"},{"ok":true}],
["pingRegions","request","StreamRegion[]","PingResult[]","core","network.regions.ping","ported",{"regions":[]},[]],
["saveScreenshot","request","ScreenshotSaveRequest","ScreenshotEntry","qt","AppController.captureScreenRegion + media.list","superseded",{}, {"id":"fixture.png","kind":"screenshot"}],
["listScreenshots","request","void","ScreenshotEntry[]","core","media.list screenshot projection","superseded",{},[]],
["deleteScreenshot","request","ScreenshotDeleteRequest","void","core","media.delete","superseded",{"id":"fixture.png"},null],
["saveScreenshotAs","request","ScreenshotSaveAsRequest","ScreenshotSaveAsResult","qt","AppController.copyScreenshotTo + FileDialog","ported",{"id":"fixture.png"},{"cancelled":true}],
["onTriggerScreenshot","event","void","void","streamer","screenshotRequestGeneration in streamer.changed","superseded",{},null],
["onExternalEscape","event","void","void","qt","deterministic back/overlay state","superseded",{},null],
["onStreamShortcutAction","event","void","NativeStreamerShortcutAction","streamer","shortcut action in streamer.changed","superseded",{},"screenshot"],
["setStreamShortcutInterceptionGate","send","StreamShortcutInterceptionGate","void","streamer","streamer.input.pause ownership gate","superseded",{"enabled":true},null],
["openExternalUrl","request","string","void","qt","AppController.openExternalUrl","ported",{"url":"https://opennow.app"},null],
["beginRecording","request","RecordingBeginRequest","RecordingBeginResult","core","media.recording.target + streamer.recording.start","superseded",{}, {"recordingId":"fixture"}],
["sendRecordingChunk","request","RecordingChunkRequest","void","streamer","source-stream recorder tap","superseded",{},null],
["finishRecording","request","RecordingFinishRequest","RecordingEntry","core","streamer.recording.stop","superseded",{}, {"id":"fixture.mkv","kind":"recording"}],
["abortRecording","request","RecordingAbortRequest","void","streamer","recording disconnect/fail-closed cleanup","superseded",{},null],
["listRecordings","request","void","RecordingEntry[]","core","media.list recording projection","superseded",{},[]],
["deleteRecording","request","RecordingDeleteRequest","void","core","media.delete","superseded",{"id":"fixture.mkv"},null],
["showRecordingInFolder","request","string","void","qt","AppController.openLocalPath(reveal)","ported",{"id":"fixture.mkv"},null],
["listMediaByGame","request","{gameTitle?:string} | undefined","MediaListingResult","core","media.list","ported",{}, {"entries":[]}],
["getMediaThumbnail","request","{filePath:string}","string | null","core","media.list thumbnailPath","superseded",{"filePath":"fixture.mkv"},null],
["showMediaInFolder","request","{filePath:string}","void","qt","AppController.openLocalPath(reveal)","ported",{"filePath":"fixture.mkv"},null],
["getMediaPlaybackUrl","request","{filePath:string}","string | null","qt","trusted local media URL in QML","superseded",{"filePath":"fixture.mkv"},null],
["deleteMediaFile","request","{filePath:string}","{ok:boolean}","core","media.delete","superseded",{"filePath":"fixture.mkv"},{"ok":true}],
["regenMediaThumbnail","request","{filePath:string}","{ok:boolean,thumbnailDataUrl:string|null}","qt","ThumbnailGenerator.regenerate","superseded",{"filePath":"fixture.mkv"},{"ok":true,"thumbnailDataUrl":null}],
["deleteCache","request","void","void","core","cache.delete","ported",{},null],
["fetchPrintedWasteQueue","request","void","PrintedWasteQueueData","core","queue.status.get","ported",{}, {"zone-fixture":{"QueuePosition":1,"Last Updated":1,"Region":"EU"}}],
["fetchPrintedWasteServerMapping","request","void","PrintedWasteServerMapping","core","queue.serverMapping.get","ported",{}, {"zone-fixture":{"title":"Fixture","region":"EU"}}],
["getThanksData","request","void","ThankYouDataResult","core","thanks.data.get","ported",{}, {"contributors":[],"supporters":[]}],
["provisionZortosCommunityProxy","request","void","CommunityProxyProvisionResult","core","communityProxy.provision","ported",{}, {"proxyUrl":"http://fixture:fixture@altaria.proxy.rlwy.net:51545/"}],
["setDiscordActivity","request","DiscordActivityUpdate","void","core","discord.activity.sync","ported",{},null],
["clearDiscordActivity","request","void","void","core","discord.activity.clear","ported",{},null],
["getReleaseHighlights","request","string | undefined","ReleaseHighlightsPayload","core","updater.highlights.get","ported",{"version":"0.5.4"},{"version":"0.5.4"}],
["ackReleaseHighlights","request","void","void","core","updater.highlights.ack","ported",{},null],
["onReleaseHighlightsShow","event","void","ReleaseHighlightsPayload","core","updater.highlights.show event","ported",{}, {"version":"0.5.4"}]
]
}
@@ -0,0 +1,36 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://opennow.app/contracts/legacy-open-now-api.schema.json",
"title": "OpenNOW Electron bridge parity inventory",
"type": "object",
"required": ["version", "source", "columns", "operations"],
"additionalProperties": false,
"properties": {
"version": { "const": 1 },
"source": { "type": "string", "minLength": 1 },
"columns": {
"const": ["legacy", "kind", "requestSchema", "resultSchema", "owner", "replacement", "status", "requestFixture", "resultFixture"]
},
"operations": {
"type": "array",
"minItems": 109,
"maxItems": 109,
"items": {
"type": "array",
"prefixItems": [
{ "type": "string", "pattern": "^[A-Za-z][A-Za-z0-9]*$" },
{ "enum": ["request", "send", "event"] },
{ "type": "string", "minLength": 1 },
{ "type": "string", "minLength": 1 },
{ "enum": ["core", "qt", "streamer"] },
{ "type": "string", "minLength": 1 },
{ "enum": ["ported", "superseded", "pending"] },
{},
{}
],
"minItems": 9,
"maxItems": 9
}
}
}
}
File diff suppressed because it is too large. Load diff
+863
View File
@@ -0,0 +1,863 @@
use reqwest::blocking::Client;
use serde_json::{Map, Value, json};
use std::collections::VecDeque;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Condvar, Mutex, mpsc};
use std::thread;
use std::time::{Duration, Instant};
const MAX_QUEUED_EVENTS: usize = 1_000;
const FLUSH_INTERVAL: Duration = Duration::from_secs(30);
const FLUSH_THRESHOLD: usize = 50;
const MAX_BATCH_EVENTS: usize = 100;
const MAX_SPOOL_BYTES: usize = 1024 * 1024;
const SHUTDOWN_BUDGET: Duration = Duration::from_millis(1_000);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Emitter {
Core,
Shell,
}
#[derive(Clone, Copy)]
enum Prop {
Text(usize),
Id,
Code,
Number(f64),
Bool,
Choice(&'static [&'static str]),
Resolution,
}
const STAGES: &[&str] = &[
"create",
"poll",
"claim",
"prepare",
"start",
"stream",
"presentation",
];
const REPORT_KINDS: &[&str] = &[
"session_error",
"stream_error",
"frame_drops",
"library_error",
"manual",
];
type EventSpec = (&'static str, Emitter, &'static [(&'static str, Prop)]);
const EVENTS: &[EventSpec] = &[
(
"app_opened",
Emitter::Core,
&[
("gpu_vendor", Prop::Code),
(
"package_kind",
Prop::Choice(&["msi", "appimage", "flatpak", "deb", "dmg", "zip"]),
),
],
),
(
"signed_in",
Emitter::Core,
&[
("provider_code", Prop::Id),
("alliance_partner", Prop::Bool),
("membership_tier", Prop::Id),
("restored", Prop::Bool),
],
),
(
"game_launch_requested",
Emitter::Core,
&[
("game_id", Prop::Id),
("game_title", Prop::Text(120)),
("store", Prop::Text(64)),
("zone", Prop::Id),
],
),
(
"session_started",
Emitter::Shell,
&[
("game_id", Prop::Id),
("game_title", Prop::Text(120)),
("codec", Prop::Choice(&["h264", "h265", "av1"])),
("resolution", Prop::Resolution),
("fps_target", Prop::Number(1_000.0)),
("hdr", Prop::Bool),
("decoder_backend", Prop::Code),
("first_frame_ms", Prop::Number(3_600_000.0)),
("queue_wait_s", Prop::Number(86_400.0)),
],
),
(
"session_ended",
Emitter::Shell,
&[
("game_id", Prop::Id),
("game_title", Prop::Text(120)),
("duration_s", Prop::Number(604_800.0)),
(
"outcome",
Prop::Choice(&["clean", "user_stopped", "remote_ended", "error"]),
),
("error_code", Prop::Code),
("recoveries", Prop::Number(100_000.0)),
("video_drop_count", Prop::Number(1e12)),
("avg_fps", Prop::Number(1_000.0)),
("avg_ping_ms", Prop::Number(100_000.0)),
("avg_packet_loss_pct", Prop::Number(100.0)),
("decoder_errors", Prop::Number(1e12)),
],
),
(
"session_error",
Emitter::Shell,
&[
("stage", Prop::Choice(STAGES)),
("code", Prop::Code),
("game_id", Prop::Id),
],
),
(
"frame_drops_detected",
Emitter::Shell,
&[
("dropped", Prop::Number(1e12)),
("window_s", Prop::Number(3_600.0)),
("game_id", Prop::Id),
("decoder_backend", Prop::Code),
],
),
(
"library_load_failed",
Emitter::Core,
&[("code", Prop::Code)],
),
(
"bug_report_sent",
Emitter::Core,
&[
("report_id", Prop::Id),
("issue_id", Prop::Id),
("kind", Prop::Choice(REPORT_KINDS)),
("code", Prop::Code),
("automatic", Prop::Bool),
],
),
(
"consent_changed",
Emitter::Core,
&[
("value", Prop::Choice(&["enabled", "disabled"])),
(
"source",
Prop::Choice(&["signin_notice", "first_run_sheet", "settings"]),
),
],
),
];
pub struct ShellEvent {
pub name: &'static str,
pub props: Map<String, Value>,
}
pub fn ui_surface(params: &Value) -> Result<Option<&'static str>, String> {
match params["uiSurface"].as_str() {
None => Ok(None),
Some("desktop") => Ok(Some("desktop")),
Some("console") => Ok(Some("console")),
Some(_) => Err("Unsupported analytics surface".to_owned()),
}
}
pub fn shell_event(params: &Value) -> Result<ShellEvent, String> {
let name = params["event"].as_str().unwrap_or_default();
let (name, emitter, _) = EVENTS
.iter()
.find(|(event, _, _)| *event == name)
.ok_or_else(|| "Unsupported analytics event".to_owned())?;
if *emitter != Emitter::Shell {
return Err("Unsupported analytics event".to_owned());
}
Ok(ShellEvent {
name,
props: sanitize(name, &params["props"]),
})
}
pub fn sanitize(event: &str, props: &Value) -> Map<String, Value> {
let allowed = EVENTS
.iter()
.find(|(name, _, _)| *name == event)
.map_or(&[][..], |(_, _, props)| *props);
let mut clean = Map::new();
for (key, prop) in allowed {
let value = &props[*key];
let accepted = match prop {
Prop::Text(limit) => value
.as_str()
.map(|text| bounded_text(text, *limit))
.filter(|text| !text.is_empty())
.map(Value::from),
Prop::Id => value
.as_str()
.filter(|text| {
(1..=64).contains(&text.len())
&& text.bytes().all(|byte| {
byte.is_ascii_alphanumeric()
|| matches!(byte, b'_' | b'-' | b'.' | b':')
})
})
.map(Value::from),
Prop::Code => value
.as_str()
.filter(|text| valid_code(text))
.map(Value::from),
Prop::Number(maximum) => value
.as_f64()
.filter(|number| number.is_finite() && (0.0..=*maximum).contains(number))
.map(|number| (number * 100.0).round() / 100.0)
.map(|number| {
if number.fract() == 0.0 && number < 9_007_199_254_740_992.0 {
json!(number as u64)
} else {
json!(number)
}
}),
Prop::Bool => value.as_bool().map(Value::from),
Prop::Choice(choices) => value
.as_str()
.filter(|text| choices.contains(text))
.map(Value::from),
Prop::Resolution => value
.as_str()
.filter(|text| {
text.split_once('x').is_some_and(|(width, height)| {
[width, height].iter().all(|part| {
(1..=5).contains(&part.len())
&& part.bytes().all(|b| b.is_ascii_digit())
})
})
})
.map(Value::from),
};
if let Some(accepted) = accepted {
clean.insert((*key).to_owned(), accepted);
}
}
clean
}
pub fn valid_code(value: &str) -> bool {
(1..=64).contains(&value.len())
&& value
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
}
pub fn gpu_vendor(name: Option<&str>) -> &'static str {
let Some(name) = name.map(str::to_ascii_lowercase) else {
return "unknown";
};
[
("nvidia", &["nvidia", "geforce", "quadro", "rtx", "gtx"][..]),
("amd", &["amd", "radeon", "ati "]),
("intel", &["intel", "iris", "arc "]),
("apple", &["apple"]),
("qualcomm", &["qualcomm", "adreno"]),
]
.iter()
.find(|(_, needles)| needles.iter().any(|needle| name.contains(needle)))
.map_or("other", |(vendor, _)| vendor)
}
fn bounded_text(value: &str, limit: usize) -> String {
value
.chars()
.map(|character| {
if character.is_control() {
' '
} else {
character
}
})
.take(limit)
.collect::<String>()
.trim()
.to_owned()
}
struct Queued {
install_id: String,
account: Value,
event: Value,
}
struct State {
queue: VecDeque<Queued>,
dropped: u64,
generation: u64,
ui_surface: &'static str,
signed_in_user: Option<String>,
app_opened: bool,
device: Value,
shutdown: bool,
}
pub struct AnalyticsService {
client: Client,
endpoint: String,
spool_path: PathBuf,
state: Mutex<State>,
wake: Condvar,
spool_lock: Mutex<()>,
}
impl AnalyticsService {
pub fn new(base: &str, data_dir: &Path) -> Result<Self, String> {
Ok(Self {
client: Client::builder()
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(20))
.build()
.map_err(|error| error.to_string())?,
endpoint: format!("{base}/v1/events"),
spool_path: data_dir.join("analytics").join("spool.jsonl"),
state: Mutex::new(State {
queue: VecDeque::new(),
dropped: 0,
generation: 0,
ui_surface: "desktop",
signed_in_user: None,
app_opened: false,
device: json!({"gpu":null, "decoderBackend":null}),
shutdown: false,
}),
wake: Condvar::new(),
spool_lock: Mutex::new(()),
})
}
pub fn start(self: &Arc<Self>) -> Result<mpsc::Receiver<()>, String> {
let (done, finished) = mpsc::channel();
let service = Arc::clone(self);
thread::Builder::new()
.name("opennow-analytics".to_owned())
.spawn(move || {
service.run();
let _ = done.send(());
})
.map_err(|error| error.to_string())?;
Ok(finished)
}
pub fn shutdown(&self, finished: &mpsc::Receiver<()>) {
self.state.lock().expect("analytics poisoned").shutdown = true;
self.wake.notify_all();
let _ = finished.recv_timeout(SHUTDOWN_BUDGET + Duration::from_millis(200));
}
pub fn enqueue(
&self,
install_id: &str,
account: Value,
event: &str,
props: Map<String, Value>,
) -> u64 {
let mut state = self.state.lock().expect("analytics poisoned");
let mut props = props;
props.insert(
"app_version".to_owned(),
json!(crate::version::APPLICATION_VERSION),
);
props.insert("os".to_owned(), json!(std::env::consts::OS));
props.insert("arch".to_owned(), json!(std::env::consts::ARCH));
props.insert("ui_surface".to_owned(), json!(state.ui_surface));
props.insert(
"channel".to_owned(),
json!(crate::version::update_channel(
crate::version::APPLICATION_VERSION
)),
);
if state.queue.len() >= MAX_QUEUED_EVENTS {
state.queue.pop_front();
state.dropped += 1;
}
state.queue.push_back(Queued {
install_id: install_id.to_owned(),
account,
event: json!({"event":event, "ts":now_ms(), "props":props}),
});
if state.queue.len() >= FLUSH_THRESHOLD {
self.wake.notify_all();
}
state.dropped
}
pub fn wipe(&self) {
let _spool = self.spool_lock.lock().expect("analytics spool poisoned");
let mut state = self.state.lock().expect("analytics poisoned");
state.queue.clear();
state.generation += 1;
drop(state);
let _ = fs::remove_file(&self.spool_path);
}
pub fn set_ui_surface(&self, surface: &'static str) {
self.state.lock().expect("analytics poisoned").ui_surface = surface;
}
pub fn observe_sign_in(&self, user_id: &str) -> bool {
let mut state = self.state.lock().expect("analytics poisoned");
if state.signed_in_user.as_deref() == Some(user_id) {
return false;
}
state.signed_in_user = Some(user_id.to_owned());
true
}
pub fn observe_sign_out(&self) {
self.state
.lock()
.expect("analytics poisoned")
.signed_in_user = None;
}
pub fn observe_runtime(&self, capabilities: &Value) {
let gpu = crate::streamer::active_gpu_label(capabilities);
let backend = capabilities["videoBackends"]
.as_array()
.into_iter()
.flatten()
.filter(|backend| backend["available"].as_bool() == Some(true))
.find_map(|backend| backend["backend"].as_str())
.filter(|backend| valid_code(backend));
if gpu.is_some() || backend.is_some() {
self.state.lock().expect("analytics poisoned").device =
json!({"gpu":gpu, "decoderBackend":backend});
}
}
pub fn open_app(&self, capabilities: &Value) -> Option<Map<String, Value>> {
self.observe_runtime(capabilities);
let mut state = self.state.lock().expect("analytics poisoned");
if std::mem::replace(&mut state.app_opened, true) {
return None;
}
let mut props = Map::new();
props.insert(
"gpu_vendor".to_owned(),
json!(gpu_vendor(state.device["gpu"].as_str())),
);
if let Some(kind) = package_kind() {
props.insert("package_kind".to_owned(), json!(kind));
}
Some(props)
}
pub fn device(&self) -> Value {
self.state
.lock()
.expect("analytics poisoned")
.device
.clone()
}
fn run(&self) {
let generation = self.state.lock().expect("analytics poisoned").generation;
self.deliver(Vec::new(), generation, None);
loop {
let (batches, generation, deadline) = {
let mut state = self.state.lock().expect("analytics poisoned");
let wake_at = Instant::now() + FLUSH_INTERVAL;
while !state.shutdown && state.queue.len() < FLUSH_THRESHOLD {
let now = Instant::now();
if now >= wake_at {
break;
}
state = self
.wake
.wait_timeout(state, wake_at - now)
.expect("analytics poisoned")
.0;
}
let deadline = state.shutdown.then(|| Instant::now() + SHUTDOWN_BUDGET);
(batches(state.queue.drain(..)), state.generation, deadline)
};
if !batches.is_empty() || deadline.is_none() {
self.deliver(batches, generation, deadline);
}
if deadline.is_some() {
return;
}
}
}
fn deliver(&self, batches: Vec<Value>, generation: u64, deadline: Option<Instant>) {
let mut failed = Vec::new();
for batch in batches {
if !failed.is_empty() || self.post(&batch, deadline) == Delivery::Retry {
failed.push(batch);
}
}
if !failed.is_empty() {
self.append_spool(&failed, generation);
} else if deadline.is_none() {
self.resend_spool(generation);
}
}
fn post(&self, batch: &Value, deadline: Option<Instant>) -> Delivery {
let mut request = self.client.post(&self.endpoint).json(batch);
if let Some(deadline) = deadline {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Delivery::Retry;
}
request = request.timeout(remaining);
}
match request.send() {
Ok(response) if response.status().is_success() => Delivery::Sent,
Ok(response)
if response.status().is_client_error()
&& !matches!(response.status().as_u16(), 408 | 429) =>
{
Delivery::Rejected
}
_ => Delivery::Retry,
}
}
fn append_spool(&self, batches: &[Value], generation: u64) {
let _spool = self.spool_lock.lock().expect("analytics spool poisoned");
if self.state.lock().expect("analytics poisoned").generation != generation {
return;
}
let mut lines = read_lines(&self.spool_path);
lines.extend(batches.iter().map(Value::to_string));
self.write_spool(lines);
}
fn resend_spool(&self, generation: u64) {
let lines = {
let _spool = self.spool_lock.lock().expect("analytics spool poisoned");
read_lines(&self.spool_path)
};
if lines.is_empty() {
return;
}
let mut sent = 0;
for line in &lines {
let Ok(batch) = serde_json::from_str::<Value>(line) else {
sent += 1;
continue;
};
if self.post(&batch, None) == Delivery::Retry {
break;
}
sent += 1;
}
let _spool = self.spool_lock.lock().expect("analytics spool poisoned");
if self.state.lock().expect("analytics poisoned").generation != generation {
return;
}
let mut current = read_lines(&self.spool_path);
current.drain(..sent.min(current.len()));
self.write_spool(current);
}
fn write_spool(&self, mut lines: Vec<String>) {
let mut total = lines.iter().map(|line| line.len() + 1).sum::<usize>();
let mut skip = 0;
while total > MAX_SPOOL_BYTES && skip < lines.len() {
total -= lines[skip].len() + 1;
skip += 1;
}
lines.drain(..skip);
if lines.is_empty() {
let _ = fs::remove_file(&self.spool_path);
return;
}
let Some(parent) = self.spool_path.parent() else {
return;
};
let temporary = self.spool_path.with_extension("jsonl.tmp");
let mut text = lines.join("\n");
text.push('\n');
if fs::create_dir_all(parent).is_ok() && fs::write(&temporary, text).is_ok() {
let _ = fs::rename(&temporary, &self.spool_path);
}
}
}
#[derive(PartialEq, Eq)]
enum Delivery {
Sent,
Rejected,
Retry,
}
fn batches(queue: impl Iterator<Item = Queued>) -> Vec<Value> {
let mut batches: Vec<(String, Value, Vec<Value>)> = Vec::new();
for item in queue {
match batches.last_mut() {
Some((install_id, account, events))
if *install_id == item.install_id
&& *account == item.account
&& events.len() < MAX_BATCH_EVENTS =>
{
events.push(item.event)
}
_ => batches.push((item.install_id, item.account, vec![item.event])),
}
}
batches
.into_iter()
.map(|(install_id, account, events)| {
json!({"installId":install_id, "account":account, "events":events})
})
.collect()
}
fn read_lines(path: &Path) -> Vec<String> {
fs::read_to_string(path)
.map(|text| {
text.lines()
.filter(|line| !line.trim().is_empty())
.map(ToOwned::to_owned)
.collect()
})
.unwrap_or_default()
}
fn package_kind() -> Option<&'static str> {
if opennow_core::update_apply::external_update_message().is_some() {
return Some("flatpak");
}
opennow_core::update_apply::compatible_package_extension().ok()
}
fn now_ms() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_millis() as u64)
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpListener;
const INSTALL: &str = "0123456789abcdef0123456789abcdef";
fn service(base: &str) -> (tempfile::TempDir, AnalyticsService) {
let directory = tempfile::tempdir().unwrap();
let service = AnalyticsService::new(base, directory.path()).unwrap();
(directory, service)
}
fn server(statuses: Vec<u16>) -> (String, thread::JoinHandle<Vec<Value>>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let worker = thread::spawn(move || {
let mut bodies = Vec::new();
for status in statuses {
let (mut stream, _) = listener.accept().unwrap();
let mut reader = BufReader::new(&stream);
let mut length = 0;
let mut line = String::new();
reader.read_line(&mut line).unwrap();
assert_eq!(line.trim(), "POST /v1/events HTTP/1.1");
loop {
line.clear();
reader.read_line(&mut line).unwrap();
if line == "\r\n" {
break;
}
if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") {
length = value.trim().parse().unwrap();
}
}
let mut body = vec![0; length];
reader.read_exact(&mut body).unwrap();
bodies.push(serde_json::from_slice(&body).unwrap());
write!(stream, "HTTP/1.1 {status} Fixture\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}").unwrap();
}
bodies
});
(base, worker)
}
fn drain(service: &AnalyticsService) -> (Vec<Value>, u64) {
let mut state = service.state.lock().unwrap();
(batches(state.queue.drain(..)), state.generation)
}
#[test]
fn shell_events_are_allowlisted_and_validated() {
let event = shell_event(&json!({"event":"session_ended", "uiSurface":"console", "props":{
"game_id":"100", "game_title":"Portal\u{0007} 2", "duration_s":61.256, "outcome":"clean",
"error_code":"Bad Code", "avg_fps":-1, "avg_ping_ms":23.4, "token":"secret", "recoveries":0.0,
"avg_packet_loss_pct":140
}}))
.unwrap();
assert_eq!(event.name, "session_ended");
assert_eq!(
ui_surface(&json!({"uiSurface":"console"})),
Ok(Some("console"))
);
assert!(ui_surface(&json!({"uiSurface":"web"})).is_err());
assert_eq!(
Value::Object(event.props),
json!({"game_id":"100", "game_title":"Portal 2", "duration_s":61.26,
"outcome":"clean", "avg_ping_ms":23.4, "recoveries":0})
);
let started = shell_event(&json!({"event":"session_started", "props":{
"resolution":"1920x1080", "codec":"h265", "hdr":true}}))
.unwrap();
assert_eq!(
Value::Object(started.props),
json!({"codec":"h265", "resolution":"1920x1080", "hdr":true})
);
assert!(
shell_event(&json!({"event":"session_started", "props":{"resolution":"1920*1080"}}))
.unwrap()
.props
.is_empty()
);
for rejected in [
json!({"event":"app_opened"}),
json!({"event":"consent_changed"}),
json!({"event":"purchase"}),
] {
assert!(shell_event(&rejected).is_err());
}
assert_eq!(
sanitize(
"bug_report_sent",
&json!({"report_id":"br-7F3A21", "kind":"manual",
"code":"manual", "automatic":false, "issue_id":"iss_01J"})
),
json!({"report_id":"br-7F3A21", "issue_id":"iss_01J", "kind":"manual",
"code":"manual", "automatic":false})
.as_object()
.unwrap()
.clone()
);
}
#[test]
fn gpu_vendors_are_coarse() {
assert_eq!(gpu_vendor(Some("NVIDIA GeForce RTX 4070")), "nvidia");
assert_eq!(gpu_vendor(Some("AMD Radeon RX 7900")), "amd");
assert_eq!(gpu_vendor(Some("Intel(R) Iris(R) Xe Graphics")), "intel");
assert_eq!(gpu_vendor(Some("Virtual Display")), "other");
assert_eq!(gpu_vendor(None), "unknown");
}
#[test]
fn the_queue_is_bounded_and_drops_the_oldest_events() {
let (_directory, service) = service("http://127.0.0.1:9");
for index in 0..MAX_QUEUED_EVENTS + 3 {
let mut props = Map::new();
props.insert("code".to_owned(), json!(format!("e{index}")));
service.enqueue(INSTALL, Value::Null, "library_load_failed", props);
}
let state = service.state.lock().unwrap();
assert_eq!(state.queue.len(), MAX_QUEUED_EVENTS);
assert_eq!(state.dropped, 3);
assert_eq!(state.queue[0].event["props"]["code"], "e3");
assert_eq!(state.queue[0].event["props"]["ui_surface"], "desktop");
}
#[test]
fn batches_group_by_account_and_cap_at_one_hundred_events() {
let (_directory, service) = service("http://127.0.0.1:9");
let account = json!({"userId":"sub", "providerIdpId":"idp"});
for _ in 0..150 {
service.enqueue(INSTALL, account.clone(), "library_load_failed", Map::new());
}
service.enqueue(INSTALL, Value::Null, "consent_changed", Map::new());
let (batches, _) = drain(&service);
assert_eq!(batches.len(), 3);
assert_eq!(batches[0]["events"].as_array().unwrap().len(), 100);
assert_eq!(batches[1]["events"].as_array().unwrap().len(), 50);
assert_eq!(batches[2]["account"], Value::Null);
assert_eq!(batches[2]["installId"], INSTALL);
assert_eq!(batches[2]["events"][0]["event"], "consent_changed");
assert!(batches[2]["events"][0]["ts"].as_u64().unwrap() > 0);
}
#[test]
fn failed_batches_spool_and_resend_once_the_service_recovers() {
let (base, worker) = server(vec![503, 202, 202]);
let (_directory, service) = service(&base);
service.enqueue(INSTALL, Value::Null, "library_load_failed", Map::new());
let (batches, generation) = drain(&service);
service.deliver(batches, generation, None);
assert_eq!(read_lines(&service.spool_path).len(), 1);
service.enqueue(INSTALL, Value::Null, "app_opened", Map::new());
let (batches, generation) = drain(&service);
service.deliver(batches, generation, None);
assert!(!service.spool_path.exists());
let bodies = worker.join().unwrap();
assert_eq!(bodies[0]["events"][0]["event"], "library_load_failed");
assert_eq!(bodies[1]["events"][0]["event"], "app_opened");
assert_eq!(bodies[2], bodies[0]);
}
#[test]
fn the_spool_is_capped_at_one_megabyte_keeping_the_newest_batches() {
let (_directory, service) = service("http://127.0.0.1:9");
let line = "x".repeat(300 * 1024);
service.write_spool((0..5).map(|index| format!("{index}{line}")).collect());
let lines = read_lines(&service.spool_path);
assert_eq!(lines.len(), 3);
assert!(lines[0].starts_with('2'));
assert!(fs::metadata(&service.spool_path).unwrap().len() <= MAX_SPOOL_BYTES as u64);
}
#[test]
fn withdrawing_consent_wipes_the_queue_spool_and_in_flight_batches() {
let (_directory, service) = service("http://127.0.0.1:9");
service.enqueue(INSTALL, Value::Null, "library_load_failed", Map::new());
service.write_spool(vec![json!({"events":[]}).to_string()]);
let (batches, generation) = drain(&service);
service.enqueue(INSTALL, Value::Null, "library_load_failed", Map::new());
service.wipe();
assert!(service.state.lock().unwrap().queue.is_empty());
assert!(!service.spool_path.exists());
service.append_spool(&batches, generation);
assert!(!service.spool_path.exists());
}
#[test]
fn runtime_capabilities_open_the_app_once_and_describe_the_device() {
let (_directory, service) = service("http://127.0.0.1:9");
let capabilities = json!({
"graphicsAdapters":[{"name":"NVIDIA GeForce RTX 4070", "active":true}],
"videoBackends":[{"backend":"software","available":false},{"backend":"d3d11","available":true}]
});
let opened = service.open_app(&capabilities).unwrap();
assert_eq!(opened["gpu_vendor"], "nvidia");
assert!(service.open_app(&capabilities).is_none());
assert_eq!(
service.device(),
json!({"gpu":"NVIDIA GeForce RTX 4070", "decoderBackend":"d3d11"})
);
assert!(service.observe_sign_in("sub"));
assert!(!service.observe_sign_in("sub"));
service.observe_sign_out();
assert!(service.observe_sign_in("sub"));
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,211 @@
use serde_json::Value;
use std::collections::{BTreeMap, BTreeSet};
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
const MAX_LICENSE_BYTES: u64 = 2 * 1024 * 1024;
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
struct Package {
name: String,
version: String,
license: String,
source: String,
directory: PathBuf,
license_file: Option<PathBuf>,
}
fn main() {
if let Err(error) = run() {
eprintln!("opennow-license-report: {error}");
std::process::exit(1);
}
}
fn run() -> Result<(), String> {
let mut arguments = env::args_os().skip(1);
let base = arguments
.next()
.map(PathBuf::from)
.ok_or_else(|| usage("missing base notice path"))?;
let output = arguments
.next()
.map(PathBuf::from)
.ok_or_else(|| usage("missing output path"))?;
let manifests = arguments.map(PathBuf::from).collect::<Vec<_>>();
if manifests.is_empty() {
return Err(usage("at least one Cargo manifest is required"));
}
let mut packages = BTreeSet::new();
for manifest in manifests {
packages.extend(packages_for_manifest(&manifest)?);
}
let mut texts: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
let mut metadata_only = Vec::new();
for package in packages {
let label = format!(
"{} {} — {} — {}",
package.name, package.version, package.license, package.source
);
let license_files = find_license_files(&package)?;
if license_files.is_empty() {
metadata_only.push(label);
continue;
}
for path in license_files {
let contents = fs::read_to_string(&path)
.map_err(|error| format!("could not read {}: {error}", path.display()))?;
texts.entry(contents).or_default().insert(label.clone());
}
}
let mut notice = fs::read_to_string(&base)
.map_err(|error| format!("could not read {}: {error}", base.display()))?;
notice.push_str("\n\nGenerated Rust dependency notices\n=================================\n\n");
notice.push_str(
"This section is generated from the exact Cargo dependency graphs used by the OpenNOW application core and native streamer. Packages sharing identical license text are grouped together.\n",
);
for (index, (license_text, labels)) in texts.into_iter().enumerate() {
notice.push_str(&format!(
"\nLicense text group {}\n---------------------\n",
index + 1
));
for label in labels {
notice.push_str("- ");
notice.push_str(&label);
notice.push('\n');
}
notice.push('\n');
notice.push_str(license_text.trim());
notice.push('\n');
}
if !metadata_only.is_empty() {
notice.push_str("\nSPDX metadata-only packages\n---------------------------\n");
notice.push_str("These packages declared an SPDX expression but shipped no standalone license file in the resolved source archive:\n");
for label in metadata_only {
notice.push_str("- ");
notice.push_str(&label);
notice.push('\n');
}
}
let parent = output
.parent()
.ok_or_else(|| "output path has no parent directory".to_owned())?;
fs::create_dir_all(parent)
.map_err(|error| format!("could not create {}: {error}", parent.display()))?;
let temporary = output.with_extension("tmp");
fs::write(&temporary, notice)
.map_err(|error| format!("could not write {}: {error}", temporary.display()))?;
if output.exists() {
fs::remove_file(&output)
.map_err(|error| format!("could not replace {}: {error}", output.display()))?;
}
fs::rename(&temporary, &output)
.map_err(|error| format!("could not publish {}: {error}", output.display()))?;
Ok(())
}
fn packages_for_manifest(manifest: &Path) -> Result<BTreeSet<Package>, String> {
let cargo = env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
let output = Command::new(cargo)
.args(["metadata", "--format-version", "1", "--manifest-path"])
.arg(manifest)
.output()
.map_err(|error| format!("could not execute cargo metadata: {error}"))?;
if !output.status.success() {
return Err(format!(
"cargo metadata failed for {}: {}",
manifest.display(),
String::from_utf8_lossy(&output.stderr).trim()
));
}
let metadata: Value = serde_json::from_slice(&output.stdout)
.map_err(|error| format!("cargo metadata returned invalid JSON: {error}"))?;
let mut packages = BTreeSet::new();
for value in metadata["packages"].as_array().into_iter().flatten() {
let name = value["name"].as_str().unwrap_or_default();
if name == "opennow-core" || name.starts_with("opennow-streamer") {
continue;
}
let manifest_path = value["manifest_path"]
.as_str()
.map(PathBuf::from)
.ok_or_else(|| format!("package {name} has no manifest path"))?;
let directory = manifest_path
.parent()
.ok_or_else(|| format!("package {name} has an invalid manifest path"))?
.to_path_buf();
let source = value["repository"]
.as_str()
.or_else(|| value["homepage"].as_str())
.or_else(|| value["source"].as_str())
.unwrap_or("resolved local source")
.to_owned();
packages.insert(Package {
name: name.to_owned(),
version: value["version"].as_str().unwrap_or("unknown").to_owned(),
license: value["license"]
.as_str()
.unwrap_or("NOASSERTION")
.to_owned(),
source,
directory,
license_file: value["license_file"].as_str().map(PathBuf::from),
});
}
Ok(packages)
}
fn find_license_files(package: &Package) -> Result<Vec<PathBuf>, String> {
if let Some(path) = package.license_file.as_ref() {
let path = if path.is_absolute() {
path.clone()
} else {
package.directory.join(path)
};
validate_license_file(&path)?;
return Ok(vec![path]);
}
let mut paths = fs::read_dir(&package.directory)
.map_err(|error| format!("could not inspect {}: {error}", package.directory.display()))?
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|path| {
path.is_file()
&& path
.file_name()
.and_then(|name| name.to_str())
.map(str::to_ascii_lowercase)
.is_some_and(|name| {
name.starts_with("license")
|| name.starts_with("copying")
|| name.starts_with("notice")
|| name.starts_with("copyright")
})
})
.collect::<Vec<_>>();
paths.sort();
for path in &paths {
validate_license_file(path)?;
}
Ok(paths)
}
fn validate_license_file(path: &Path) -> Result<(), String> {
let metadata = fs::metadata(path)
.map_err(|error| format!("could not inspect {}: {error}", path.display()))?;
if !metadata.is_file() || metadata.len() > MAX_LICENSE_BYTES {
return Err(format!("unusable license file: {}", path.display()));
}
Ok(())
}
fn usage(message: &str) -> String {
format!("{message}; usage: opennow-license-report BASE_NOTICE OUTPUT MANIFEST [MANIFEST ...]")
}
@@ -0,0 +1,15 @@
use opennow_core::update_apply;
fn main() {
let mut arguments = std::env::args_os().skip(1);
let result = match (arguments.next(), arguments.next(), arguments.next()) {
(Some(flag), Some(path), None) if flag == "--apply" => {
update_apply::run_helper(std::path::Path::new(&path))
}
_ => Err("Usage: opennow-update-helper --apply <prepared-plan.json>".to_owned()),
};
if let Err(error) = result {
eprintln!("opennow-update-helper: {error}");
std::process::exit(1);
}
}
@@ -0,0 +1,231 @@
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64;
use ed25519_dalek::{Signer as _, SigningKey, VerifyingKey};
use serde::Serialize;
use sha2::{Digest, Sha256};
use std::env;
use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Manifest {
schema_version: u32,
version: String,
asset: String,
size: u64,
sha256: String,
signature: String,
}
fn main() {
if let Err(error) = run() {
eprintln!("opennow-update-manifest: {error}");
std::process::exit(1);
}
}
fn run() -> Result<(), String> {
let mut arguments = env::args_os().skip(1);
let asset = arguments
.next()
.map(PathBuf::from)
.ok_or_else(|| "usage: opennow-update-manifest <asset> <version> [output]".to_owned())?;
let version = arguments
.next()
.and_then(|value| value.into_string().ok())
.ok_or_else(|| "update version is required".to_owned())?;
let version = semver::Version::parse(version.strip_prefix('v').unwrap_or(&version))
.map_err(|_| "update version must be valid semver".to_owned())?
.to_string();
let output = arguments.next().map(PathBuf::from).unwrap_or_else(|| {
let name = asset.file_name().unwrap_or_default().to_string_lossy();
asset.with_file_name(format!("{name}.manifest.json"))
});
if arguments.next().is_some() {
return Err("update manifest arguments are invalid".to_owned());
}
let asset_name = asset
.file_name()
.and_then(|value| value.to_str())
.filter(|value| safe_asset_name(value))
.ok_or_else(|| "update asset name is unsafe".to_owned())?
.to_owned();
let key = signing_key()?;
let verifying_key = configured_verifying_key()?;
if key.verifying_key() != verifying_key {
return Err(
"OPENNOW_UPDATE_ED25519_PUBLIC_KEY does not match the protected signing key".to_owned(),
);
}
let (size, sha256) = hash_file(&asset)?;
let mut manifest = Manifest {
schema_version: 1,
version,
asset: asset_name,
size,
sha256,
signature: String::new(),
};
let signature = key.sign(signature_payload(&manifest).as_bytes());
verifying_key
.verify_strict(signature_payload(&manifest).as_bytes(), &signature)
.map_err(|_| "generated update signature did not verify".to_owned())?;
manifest.signature = BASE64.encode(signature.to_bytes());
let bytes = serde_json::to_vec_pretty(&manifest).map_err(|error| error.to_string())?;
let temporary = output.with_extension("json.tmp");
let mut file = fs::File::create(&temporary)
.map_err(|error| format!("could not create manifest: {error}"))?;
file.write_all(&bytes)
.and_then(|()| file.write_all(b"\n"))
.and_then(|()| file.sync_all())
.map_err(|error| format!("could not write manifest: {error}"))?;
fs::rename(&temporary, &output)
.map_err(|error| format!("could not finalize manifest: {error}"))?;
println!("{}", output.display());
Ok(())
}
fn signing_key() -> Result<SigningKey, String> {
let encoded = env::var("OPENNOW_UPDATE_ED25519_PRIVATE_KEY")
.map_err(|_| "OPENNOW_UPDATE_ED25519_PRIVATE_KEY is required".to_owned())?;
let bytes = BASE64
.decode(encoded.trim())
.map_err(|_| "update signing key is not valid base64".to_owned())?;
let bytes: [u8; 32] = bytes
.try_into()
.map_err(|_| "update signing key must be a 32-byte Ed25519 seed".to_owned())?;
Ok(SigningKey::from_bytes(&bytes))
}
fn configured_verifying_key() -> Result<VerifyingKey, String> {
let encoded = env::var("OPENNOW_UPDATE_ED25519_PUBLIC_KEY")
.map_err(|_| "OPENNOW_UPDATE_ED25519_PUBLIC_KEY is required".to_owned())?;
decode_verifying_key(&encoded)
}
fn decode_verifying_key(encoded: &str) -> Result<VerifyingKey, String> {
let bytes = BASE64
.decode(encoded.trim())
.map_err(|_| "update verifying key is not valid base64".to_owned())?;
let bytes: [u8; 32] = bytes
.try_into()
.map_err(|_| "update verifying key must be 32 bytes".to_owned())?;
VerifyingKey::from_bytes(&bytes).map_err(|_| "update verifying key is invalid".to_owned())
}
fn hash_file(path: &Path) -> Result<(u64, String), String> {
let mut file =
fs::File::open(path).map_err(|error| format!("could not read update asset: {error}"))?;
let mut hasher = Sha256::new();
let mut size = 0_u64;
let mut buffer = [0_u8; 128 * 1024];
loop {
let count = file
.read(&mut buffer)
.map_err(|error| format!("could not hash update asset: {error}"))?;
if count == 0 {
break;
}
size = size
.checked_add(count as u64)
.ok_or_else(|| "update asset size overflowed".to_owned())?;
hasher.update(&buffer[..count]);
}
if size == 0 {
return Err("update asset is empty".to_owned());
}
Ok((size, format!("{:x}", hasher.finalize())))
}
fn signature_payload(manifest: &Manifest) -> String {
format!(
"OpenNOW update manifest v1\nversion={}\nasset={}\nsize={}\nsha256={}\n",
manifest.version, manifest.asset, manifest.size, manifest.sha256
)
}
fn safe_asset_name(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 240
&& !value.contains(['/', '\\'])
&& !value.contains("..")
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_'))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn public_key_decoder_rejects_malformed_and_accepts_the_signing_pair() {
assert!(decode_verifying_key("not-base64").is_err());
assert!(decode_verifying_key(&BASE64.encode([0_u8; 31])).is_err());
let signing = SigningKey::from_bytes(&[7_u8; 32]);
let encoded = BASE64.encode(signing.verifying_key().as_bytes());
assert_eq!(
decode_verifying_key(&encoded).unwrap(),
signing.verifying_key()
);
}
#[test]
fn canonical_manifest_signature_verifies_and_detects_tampering() {
let signing = SigningKey::from_bytes(&[9_u8; 32]);
let manifest = Manifest {
schema_version: 1,
version: "1.2.3".to_owned(),
asset: "OpenNOW-Qt-1.2.3.deb".to_owned(),
size: 42,
sha256: "0".repeat(64),
signature: String::new(),
};
let signature = signing.sign(signature_payload(&manifest).as_bytes());
assert!(
signing
.verifying_key()
.verify_strict(signature_payload(&manifest).as_bytes(), &signature)
.is_ok()
);
let mut tampered = manifest;
tampered.size += 1;
assert!(
signing
.verifying_key()
.verify_strict(signature_payload(&tampered).as_bytes(), &signature)
.is_err()
);
}
#[test]
fn nightly_signature_binds_the_full_version() {
let signing = SigningKey::from_bytes(&[9_u8; 32]);
let mut manifest = Manifest {
schema_version: 1,
version: semver::Version::parse("1.0.0-nightly.123456.2")
.unwrap()
.to_string(),
asset: "OpenNOW-Qt-1.0.0-nightly.123456.2-Linux-x64.deb".to_owned(),
size: 42,
sha256: "0".repeat(64),
signature: String::new(),
};
let signature = signing.sign(signature_payload(&manifest).as_bytes());
signing
.verifying_key()
.verify_strict(signature_payload(&manifest).as_bytes(), &signature)
.unwrap();
for version in ["1.0.0-nightly.123456.3", "1.0.0"] {
manifest.version = version.to_owned();
assert!(
signing
.verifying_key()
.verify_strict(signature_payload(&manifest).as_bytes(), &signature)
.is_err()
);
}
}
}
+340
View File
@@ -0,0 +1,340 @@
use serde_json::{Map, Value, json};
use std::collections::{HashSet, VecDeque};
use std::sync::Mutex;
use std::time::{Duration, Instant};
const ENABLED_WHEN_UNSET: bool = true;
const MAXIMUM_REPORTS_PER_RUN: usize = 5;
const MINIMUM_REPORT_INTERVAL: Duration = Duration::from_secs(30);
const RECENT_GAME_LIMIT: usize = 5;
const REPORTED_METHODS: &[(&str, Kind)] = &[
("session.create", Kind::SessionError),
("session.poll", Kind::SessionError),
("session.claim", Kind::SessionError),
("streamer.prepare", Kind::StreamError),
("streamer.start", Kind::StreamError),
("catalog.library.list", Kind::LibraryError),
];
const EXPECTED_CODES: &[&str] = &[
"authentication_required",
"busy",
"cancelled",
"catalog_changed",
"catalog_mutation_busy",
"confirmation_required",
"launch_not_ready",
"rate_limited",
"routing_busy",
"session_cleanup_pending",
"session_conflict",
"session_update_busy",
"stale_account",
"update_pending",
];
const SHELL_METRICS: &[&str] = &[
"droppedFrames",
"windowSeconds",
"framesPerSecond",
"packetLossPercent",
"pingMs",
"decodeTimeMs",
];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
SessionError,
StreamError,
FrameDrops,
LibraryError,
}
impl Kind {
pub fn as_str(self) -> &'static str {
match self {
Self::SessionError => "session_error",
Self::StreamError => "stream_error",
Self::FrameDrops => "frame_drops",
Self::LibraryError => "library_error",
}
}
}
#[derive(Clone, Debug)]
pub struct Incident {
pub kind: Kind,
pub code: String,
pub message: String,
pub details: Value,
}
impl Incident {
pub fn trigger(&self) -> Value {
json!({
"kind": self.kind.as_str(),
"code": self.code,
"message": self.message,
"metrics": self.details.get("metrics").cloned().unwrap_or_else(|| json!({}))
})
}
}
#[derive(Clone, Debug)]
struct Game {
title: String,
app_id: String,
}
impl Game {
fn value(&self) -> Value {
json!({"title":self.title, "appId":self.app_id})
}
}
#[derive(Default)]
struct State {
current: Option<Game>,
recent: VecDeque<Game>,
reported: HashSet<String>,
admitted: usize,
last_admitted: Option<Instant>,
}
#[derive(Default)]
pub struct BugReporter {
state: Mutex<State>,
}
pub fn enabled(settings: &Value) -> bool {
match settings["automaticBugReports"].as_str() {
Some("enabled") => true,
Some("disabled") => false,
_ => ENABLED_WHEN_UNSET,
}
}
impl BugReporter {
pub fn observe_launch(&self, params: &Value) -> String {
let game = Game {
title: bounded_text(params["title"].as_str().unwrap_or("Unknown game"), 120),
app_id: bounded_text(params["appId"].as_str().unwrap_or_default(), 32),
};
let detail = format!("title={} appId={}", game.title, game.app_id);
let mut state = self.state.lock().expect("bug reporter poisoned");
state.recent.retain(|recent| recent.app_id != game.app_id);
state.recent.push_front(game.clone());
state.recent.truncate(RECENT_GAME_LIMIT);
state.current = Some(game);
detail
}
pub fn observe_stop(&self) {
self.state.lock().expect("bug reporter poisoned").current = None;
}
pub fn activity(&self) -> Value {
let state = self.state.lock().expect("bug reporter poisoned");
json!({
"currentGame": state.current.as_ref().map(Game::value),
"recentGames": state.recent.iter().map(Game::value).collect::<Vec<_>>()
})
}
pub fn rpc_incident(method: &str, code: &str, message: &str) -> Option<Incident> {
let kind = REPORTED_METHODS
.iter()
.find(|(reported, _)| *reported == method)
.map(|(_, kind)| *kind)?;
if EXPECTED_CODES.contains(&code) {
return None;
}
Some(Incident {
kind,
code: bounded_code(code),
message: crate::diagnostics::runtime_failure_reason(message),
details: json!({"method":method}),
})
}
pub fn shell_incident(params: &Value) -> Result<Incident, String> {
let kind = match params["kind"].as_str() {
Some("stream_error") => Kind::StreamError,
Some("frame_drops") => Kind::FrameDrops,
_ => return Err("Unsupported automatic report kind".to_owned()),
};
let code = params["code"]
.as_str()
.filter(|code| {
(1..=64).contains(&code.len())
&& code.bytes().all(|byte| {
byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_'
})
})
.ok_or_else(|| "Automatic report code is invalid".to_owned())?;
let mut metrics = Map::new();
for key in SHELL_METRICS {
if let Some(value) = params["metrics"][*key]
.as_f64()
.filter(|value| value.is_finite() && (0.0..=1_000_000.0).contains(value))
{
metrics.insert((*key).to_owned(), json!(value));
}
}
Ok(Incident {
kind,
code: code.to_owned(),
message: crate::diagnostics::runtime_failure_reason(
params["message"].as_str().unwrap_or_default(),
),
details: json!({"source":"shell", "metrics":metrics}),
})
}
pub fn admit(&self, incident: &Incident, now: Instant) -> Option<Value> {
let mut state = self.state.lock().expect("bug reporter poisoned");
let signature = format!("{}:{}", incident.kind.as_str(), incident.code);
if state.reported.contains(&signature)
|| state.admitted >= MAXIMUM_REPORTS_PER_RUN
|| state
.last_admitted
.is_some_and(|last| now.duration_since(last) < MINIMUM_REPORT_INTERVAL)
{
return None;
}
state.reported.insert(signature);
state.admitted += 1;
state.last_admitted = Some(now);
drop(state);
Some(self.activity())
}
}
fn bounded_text(value: &str, limit: usize) -> String {
value
.chars()
.map(|character| {
if character.is_control() && character != '\n' {
' '
} else {
character
}
})
.take(limit)
.collect::<String>()
.trim()
.to_owned()
}
fn bounded_code(value: &str) -> String {
let code = value
.chars()
.filter(|character| character.is_ascii_alphanumeric() || *character == '_')
.map(|character| character.to_ascii_lowercase())
.take(64)
.collect::<String>();
if code.is_empty() {
"unknown".to_owned()
} else {
code
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unset_consent_is_opt_out_and_explicit_choices_win() {
assert!(enabled(&json!({"automaticBugReports":"unset"})));
assert!(enabled(&json!({})));
assert!(enabled(&json!({"automaticBugReports":"enabled"})));
assert!(!enabled(&json!({"automaticBugReports":"disabled"})));
}
#[test]
fn only_unexpected_failures_of_reported_methods_become_incidents() {
let incident = BugReporter::rpc_incident("catalog.library.list", "network_error", "boom")
.expect("library failures are reported");
assert_eq!(incident.kind, Kind::LibraryError);
assert!(BugReporter::rpc_incident("session.create", "cancelled", "user").is_none());
assert!(BugReporter::rpc_incident("settings.set", "invalid_setting", "x").is_none());
let incident =
BugReporter::rpc_incident("session.poll", "session_error", "Bearer abc.def failed")
.unwrap();
assert!(!incident.message.contains("abc.def"));
}
#[test]
fn shell_incidents_accept_only_known_kinds_codes_and_metrics() {
let incident = BugReporter::shell_incident(&json!({
"kind":"frame_drops", "code":"sustained_frame_drops",
"metrics":{"droppedFrames":412, "windowSeconds":60, "secret":"x", "pingMs":-1}
}))
.unwrap();
assert_eq!(incident.kind, Kind::FrameDrops);
assert_eq!(
incident.details["metrics"],
json!({"droppedFrames":412.0, "windowSeconds":60.0})
);
assert!(BugReporter::shell_incident(&json!({"kind":"library_error","code":"x"})).is_err());
assert!(
BugReporter::shell_incident(&json!({"kind":"stream_error","code":"Bad Code"})).is_err()
);
}
#[test]
fn reports_are_deduplicated_spaced_and_capped_per_run() {
let reporter = BugReporter::default();
let start = Instant::now();
let incident = |code: &str| Incident {
kind: Kind::StreamError,
code: code.to_owned(),
message: String::new(),
details: Value::Null,
};
assert!(reporter.admit(&incident("a"), start).is_some());
assert!(
reporter
.admit(&incident("a"), start + Duration::from_secs(60))
.is_none()
);
assert!(
reporter
.admit(&incident("b"), start + Duration::from_secs(5))
.is_none()
);
for (index, code) in ["b", "c", "d", "e"].iter().enumerate() {
let at = start + MINIMUM_REPORT_INTERVAL * (index as u32 + 1);
assert!(reporter.admit(&incident(code), at).is_some());
}
assert!(
reporter
.admit(&incident("f"), start + Duration::from_secs(3600))
.is_none()
);
}
#[test]
fn reports_carry_the_current_game_recent_games_and_the_trigger() {
let reporter = BugReporter::default();
reporter.observe_launch(&json!({"title":"Portal 2", "appId":"100"}));
reporter.observe_launch(&json!({"title":"Cyberpunk 2077", "appId":"200"}));
reporter.observe_launch(&json!({"title":"Portal 2", "appId":"100"}));
let incident =
BugReporter::rpc_incident("session.create", "session_error", "seat lost").unwrap();
let activity = reporter.admit(&incident, Instant::now()).unwrap();
assert_eq!(
activity,
json!({"currentGame":{"title":"Portal 2","appId":"100"},
"recentGames":[{"title":"Portal 2","appId":"100"},{"title":"Cyberpunk 2077","appId":"200"}]})
);
assert_eq!(
incident.trigger(),
json!({"kind":"session_error", "code":"session_error", "message":"seat lost", "metrics":{}})
);
reporter.observe_stop();
assert_eq!(reporter.activity()["currentGame"], Value::Null);
}
}
@@ -0,0 +1,367 @@
use crate::gfn::ServiceError;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "__typename")]
pub enum StoreFeature {
AccountLinkingSso {
supported: Option<bool>,
#[serde(rename = "displayProposition")]
display_proposition: Option<String>,
},
AccountGamesSyncing {
supported: Option<bool>,
#[serde(rename = "displayProposition")]
display_proposition: Option<String>,
},
AccountSubscriptions {
#[serde(rename = "displayProposition")]
display_proposition: Option<String>,
},
#[serde(other)]
Unknown,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum GameFeature {
Rtx,
Hdr,
Reflex,
}
impl GameFeature {
pub fn from_variant_features(features: &Value) -> Vec<GameFeature> {
let entries: Vec<&Value> = match features {
Value::Array(items) => items.iter().collect(),
Value::Object(_) => vec![features],
_ => Vec::new(),
};
let enabled = |key: &str| {
entries.iter().any(|feature| {
feature["key"].as_str() == Some(key)
&& (feature["value"].as_bool() == Some(true)
|| feature["value"]
.as_str()
.is_some_and(|value| value.eq_ignore_ascii_case("true")))
})
};
let hdr_version = entries.iter().any(|feature| {
feature["key"].as_str() == Some("SUPPORTED_HDR_VERSION")
&& [&feature["value"], &feature["values"]]
.into_iter()
.any(|value| match value {
Value::String(text) => !text.is_empty(),
Value::Array(items) => items
.iter()
.any(|item| item.as_str().is_some_and(|text| !text.is_empty())),
_ => false,
})
});
let mut result = Vec::new();
if enabled("RTX_ENABLED") {
result.push(GameFeature::Rtx);
}
if enabled("HDR_ENABLED") || hdr_version {
result.push(GameFeature::Hdr);
}
if enabled("REFLEX_ENABLED") {
result.push(GameFeature::Reflex);
}
result
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LinkingMetadata {
pub supported_variant_ids: Option<Vec<String>>,
pub is_supported: Option<bool>,
pub is_required: Option<bool>,
pub label: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StoreDefinition {
pub store: String,
pub label: String,
pub sort_order: Option<i64>,
pub small_image_url: Option<String>,
#[serde(default)]
pub features: Vec<StoreFeature>,
pub account_linking_metadata: Option<LinkingMetadata>,
}
impl StoreDefinition {
pub fn connection_definition(&self) -> Value {
let provider = normalize_store(&self.store);
let known = matches!(
provider.as_str(),
"UPLAY" | "BATTLENET" | "EPIC" | "GAIJIN" | "GOG" | "STEAM" | "XBOX"
);
json!({
"provider":provider,"store":self.store,"label":self.label,"sortOrder":self.sort_order,
"supportsLinking":known && self.features.iter().any(|feature| matches!(feature, StoreFeature::AccountLinkingSso { supported:Some(true), .. })),
"supportsSync":known && self.features.iter().any(|feature| matches!(feature, StoreFeature::AccountGamesSyncing { supported:Some(true), .. })),
"isRequired":self.account_linking_metadata.as_ref().and_then(|metadata| metadata.is_required),
"accountLinkingMetadata":self.account_linking_metadata,"features":self.features,
"capabilitySource":"server"
})
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GenreDefinition {
pub genre: String,
pub label: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SubscriptionDefinition {
pub subscription: String,
pub label: String,
#[serde(rename = "logoURL")]
pub logo_url: Option<String>,
#[serde(rename = "buySubscriptionURL")]
pub buy_subscription_url: Option<String>,
pub primary_store: Option<String>,
pub additional_stores: Option<Vec<SubscriptionStore>>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SubscriptionStore {
pub store: String,
pub third_party_linking_redirect_keyword: Option<String>,
#[serde(rename = "thirdPartyLinkingShortURL")]
pub third_party_linking_short_url: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "__typename")]
pub enum PatchDetails {
VariantGfnAutoPatchingMetadata {
#[serde(rename = "subType")]
sub_type: Option<String>,
#[serde(rename = "startTime")]
start_time: Option<String>,
#[serde(rename = "endTime")]
end_time: Option<String>,
#[serde(rename = "historicalEtaMins")]
historical_eta_mins: Option<f64>,
#[serde(rename = "etaPredictionType")]
eta_prediction_type: Option<String>,
},
VariantGfnManualPatchingMetadata {
#[serde(rename = "subType")]
sub_type: Option<String>,
#[serde(rename = "startTime")]
start_time: Option<String>,
#[serde(rename = "endTime")]
end_time: Option<String>,
},
VariantGfnMaintenanceMetadata {
#[serde(rename = "subType")]
sub_type: Option<String>,
},
#[serde(other)]
Unknown,
}
pub fn normalize_store(value: &str) -> String {
match value
.trim()
.to_ascii_uppercase()
.replace([' ', '-'], "_")
.as_str()
{
"UBISOFT" | "UBISOFT_CONNECT" => "UPLAY".into(),
"BATTLE_NET" | "BLIZZARD" => "BATTLENET".into(),
"EPIC_GAMES" | "EPIC_GAMES_STORE" => "EPIC".into(),
value => value.into(),
}
}
pub fn parse_list<T: serde::de::DeserializeOwned + Serialize>(
value: &Value,
) -> Result<Value, ServiceError> {
let values = value
.as_array()
.filter(|items| items.len() <= 512)
.ok_or_else(invalid_metadata)?;
if serde_json::to_vec(value).map_or(true, |bytes| bytes.len() > 256 * 1024) {
return Err(invalid_metadata());
}
let parsed: Vec<T> = values
.iter()
.map(|item| serde_json::from_value(item.clone()))
.collect::<Result<_, _>>()
.map_err(|_| invalid_metadata())?;
serde_json::to_value(parsed).map_err(|_| invalid_metadata())
}
pub fn invalid_metadata() -> ServiceError {
ServiceError {
code: "invalid_upstream_response",
message: "Catalog metadata is missing, invalid, or exceeds its size limit".into(),
}
}
pub fn filter_expression(value: &Value) -> Option<Value> {
fn merge(target: &mut Value, source: Value, depth: usize) -> Option<()> {
if depth > 8 {
return None;
}
match (target, source) {
(Value::Object(target), Value::Object(source)) => {
if source.len() > 64 {
return None;
}
for (key, value) in source {
if let Some(target) = target.get_mut(&key) {
merge(target, value, depth + 1)?;
} else {
let mut field = if value.is_object() {
json!({})
} else if value.is_array() {
json!([])
} else {
Value::Null
};
merge(&mut field, value, depth + 1)?;
target.insert(key, field);
}
}
}
(Value::Array(target), Value::Array(source)) => {
if target.len() + source.len() > 128 {
return None;
}
target.extend(source);
}
(target, source) => *target = source,
}
Some(())
}
let inputs = value.as_array().filter(|items| items.len() <= 32)?;
let mut output = json!({});
for input in inputs {
let text = input.as_str().filter(|text| text.len() <= 8192)?;
let parsed: Value = serde_json::from_str(text).ok()?;
if !parsed.is_object() {
return None;
}
merge(&mut output, parsed, 0)?;
}
Some(output)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn game_features_follow_catalog_keys_and_ignore_unbacked_ones() {
let features = json!([
{"__typename":"GfnSubscriptionFeatureValue","key":"RTX_ENABLED","value":"true"},
{"__typename":"GfnSubscriptionFeatureValue","key":"SUPPORTED_HDR_VERSION","value":null},
{"__typename":"GfnSubscriptionFeatureValueList","key":"SUPPORTED_HDR_VERSION","values":["HDR"]},
{"__typename":"GfnSubscriptionFeatureValue","key":"REFLEX_ENABLED","value":"true"},
{"__typename":"GfnSubscriptionFeatureValue","key":"DLSS_ENABLED","value":"true"},
{"__typename":"GfnSubscriptionFeatureValue","key":"IN_GAME_SETTINGS_PERSISTENCE_ENABLED","value":"true"}
]);
assert_eq!(
GameFeature::from_variant_features(&features),
vec![GameFeature::Rtx, GameFeature::Hdr, GameFeature::Reflex]
);
assert_eq!(
serde_json::to_value(GameFeature::from_variant_features(&features)).unwrap(),
json!(["rtx", "hdr", "reflex"])
);
let disabled = json!([
{"key":"RTX_ENABLED","value":"false"},
{"key":"SUPPORTED_HDR_VERSION","value":null},
{"key":"HDR_ENABLED","value":null}
]);
assert!(GameFeature::from_variant_features(&disabled).is_empty());
assert_eq!(
GameFeature::from_variant_features(&json!({"key":"HDR_ENABLED","value":true})),
vec![GameFeature::Hdr]
);
assert!(GameFeature::from_variant_features(&Value::Null).is_empty());
}
#[test]
fn gog_connection_capabilities_follow_server_features() {
for supported in [false, true] {
let store: StoreDefinition = serde_json::from_value(json!({
"store":"GOG","label":"GOG","features":[
{"__typename":"AccountLinkingSso","supported":supported},
{"__typename":"AccountGamesSyncing","supported":supported}
]
}))
.unwrap();
let connection = store.connection_definition();
assert_eq!(connection["provider"], "GOG");
assert_eq!(connection["supportsLinking"], supported);
assert_eq!(connection["supportsSync"], supported);
}
}
#[test]
fn store_definitions_preserve_nullable_variant_scope_and_link_requirements() {
for variants in [Value::Null, json!([]), json!(["123"])] {
let input = json!([{"store":"XBOX","label":"Xbox","features":[],
"accountLinkingMetadata":{"supportedVariantIds":variants,"isRequired":true}}]);
let parsed = parse_list::<StoreDefinition>(&input).unwrap();
let store: StoreDefinition = serde_json::from_value(parsed[0].clone()).unwrap();
let connection = store.connection_definition();
assert_eq!(
connection["accountLinkingMetadata"]["supportedVariantIds"],
variants
);
assert_eq!(connection["isRequired"], true);
}
for invalid in [json!("123"), json!([123]), json!([null])] {
assert!(
parse_list::<StoreDefinition>(&json!([{"store":"XBOX","label":"Xbox",
"accountLinkingMetadata":{"supportedVariantIds":invalid}}]))
.is_err()
);
}
}
#[test]
fn subscription_definitions_accept_null_but_reject_invalid_additional_stores() {
for stores in [Value::Null, json!([]), json!([{"store":"UPLAY"}])] {
let parsed = parse_list::<SubscriptionDefinition>(&json!([{
"subscription":"STORE_PASS","label":"Store Pass","additionalStores":stores
}]))
.unwrap();
assert_eq!(parsed[0]["additionalStores"].is_null(), stores.is_null());
if let Some(stores) = stores.as_array() {
assert_eq!(
parsed[0]["additionalStores"].as_array().unwrap().len(),
stores.len()
);
for (index, store) in stores.iter().enumerate() {
assert_eq!(
parsed[0]["additionalStores"][index]["store"],
store["store"]
);
}
}
}
for invalid in [json!("UPLAY"), json!(["UPLAY"]), json!([null])] {
assert!(
parse_list::<SubscriptionDefinition>(&json!([{
"subscription":"STORE_PASS","label":"Store Pass","additionalStores":invalid
}]))
.is_err()
);
}
}
}
File diff suppressed because it is too large. Load diff
+268
View File
@@ -0,0 +1,268 @@
use reqwest::blocking::Client;
use serde::Deserialize;
use serde_json::{Map, Value, json};
use std::thread;
use std::time::Duration;
use url::Url;
const QUEUE_URL: &str = "https://api.printedwaste.com/gfn/queue/";
const SERVER_MAPPING_URL: &str =
"https://remote.printedwaste.com/config/GFN_SERVERID_TO_REGION_MAPPING";
const PROVISION_URL: &str = "https://opennow-proxy-production.up.railway.app/api/public/proxy";
const COMMUNITY_PROXY_HOST: &str = "altaria.proxy.rlwy.net";
const COMMUNITY_PROXY_PORT: u16 = 51_545;
const MAXIMUM_RESPONSE_BYTES: u64 = 4 * 1024 * 1024;
pub struct CommunityService {
client: Client,
}
impl CommunityService {
pub fn new() -> Result<Self, String> {
let client = Client::builder()
.connect_timeout(Duration::from_secs(8))
.timeout(Duration::from_secs(45))
.pool_idle_timeout(Duration::from_secs(30))
.build()
.map_err(|error| error.to_string())?;
Ok(Self { client })
}
pub fn queue(&self) -> Result<Value, String> {
let payload = self.get_json(QUEUE_URL, Duration::from_secs(7))?;
normalize_queue(&payload)
}
pub fn server_mapping(&self) -> Result<Value, String> {
let payload = self.get_json(SERVER_MAPPING_URL, Duration::from_secs(7))?;
normalize_server_mapping(&payload)
}
pub fn provision_proxy(&self, client_id: &str) -> Result<Value, String> {
if client_id.len() < 16 || client_id.len() > 128 {
return Err("Stable device identity is invalid".to_owned());
}
let mut response = self.provision_request(client_id)?;
if matches!(
response.status().as_u16(),
408 | 425 | 429 | 500 | 502 | 503 | 504
) {
thread::sleep(Duration::from_millis(1_500));
response = self.provision_request(client_id)?;
}
if !response.status().is_success() {
return Err(format!(
"Community proxy provision failed ({})",
response.status().as_u16()
));
}
let length = response.content_length().unwrap_or(0);
if length > MAXIMUM_RESPONSE_BYTES {
return Err("Community proxy response exceeded the size limit".to_owned());
}
let payload = response
.json::<ProvisionResponse>()
.map_err(|_| "Community proxy provision returned invalid JSON".to_owned())?;
let proxy_url = if let Some(value) = payload.proxy_url {
normalize_community_proxy_url(&value)?
} else {
build_community_proxy_url(
payload
.username
.as_deref()
.ok_or_else(|| "Community proxy response omitted credentials".to_owned())?,
payload
.password
.as_deref()
.ok_or_else(|| "Community proxy response omitted credentials".to_owned())?,
)?
};
Ok(json!({"proxyUrl":proxy_url}))
}
fn get_json(&self, url: &str, timeout: Duration) -> Result<Value, String> {
let response = self
.client
.get(url)
.timeout(timeout)
.header(
"User-Agent",
format!("opennow/{}", crate::version::APPLICATION_VERSION),
)
.header("Accept", "application/json")
.send()
.map_err(|_| "Community service is unavailable right now".to_owned())?;
if !response.status().is_success() {
return Err(format!(
"Community service returned HTTP {}",
response.status().as_u16()
));
}
if response.content_length().unwrap_or(0) > MAXIMUM_RESPONSE_BYTES {
return Err("Community response exceeded the size limit".to_owned());
}
response
.json::<Value>()
.map_err(|_| "Community service returned invalid JSON".to_owned())
}
fn provision_request(&self, client_id: &str) -> Result<reqwest::blocking::Response, String> {
self.client
.post(PROVISION_URL)
.timeout(Duration::from_secs(45))
.header(
"User-Agent",
format!(
"OpenNOW-DesktopClient/{}",
crate::version::APPLICATION_VERSION
),
)
.header("Accept", "application/json")
.json(&json!({"clientId":client_id}))
.send()
.map_err(|_| "Community proxy provisioning is unavailable right now".to_owned())
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ProvisionResponse {
proxy_url: Option<String>,
username: Option<String>,
password: Option<String>,
}
fn data_object<'a>(payload: &'a Value, context: &str) -> Result<&'a Map<String, Value>, String> {
if payload["status"].as_bool() != Some(true) {
return Err(format!("{context} returned status:false"));
}
payload["data"]
.as_object()
.ok_or_else(|| format!("{context} response omitted its data object"))
}
fn normalize_queue(payload: &Value) -> Result<Value, String> {
let data = data_object(payload, "PrintedWaste queue")?;
let mut output = Map::new();
for (zone_id, raw) in data {
let Some(zone) = raw.as_object() else {
continue;
};
let (Some(position), Some(updated), Some(region)) = (
zone.get("QueuePosition").and_then(Value::as_f64),
zone.get("Last Updated").and_then(Value::as_f64),
zone.get("Region")
.and_then(Value::as_str)
.filter(|value| !value.is_empty()),
) else {
continue;
};
if !position.is_finite() || !updated.is_finite() {
continue;
}
let mut normalized = json!({
"QueuePosition":position,
"Last Updated":updated,
"Region":region
});
if let Some(eta) = zone
.get("eta")
.and_then(Value::as_f64)
.filter(|value| value.is_finite())
{
normalized["eta"] = json!(eta);
}
output.insert(zone_id.clone(), normalized);
}
if output.is_empty() {
return Err("PrintedWaste queue returned no valid zones".to_owned());
}
Ok(Value::Object(output))
}
fn normalize_server_mapping(payload: &Value) -> Result<Value, String> {
let data = data_object(payload, "PrintedWaste server mapping")?;
let mut output = Map::new();
for (zone_id, raw) in data {
let Some(zone) = raw.as_object() else {
continue;
};
let mut normalized = Map::new();
for key in ["title", "region"] {
if let Some(value) = zone.get(key).and_then(Value::as_str) {
normalized.insert(key.to_owned(), json!(value));
}
}
for key in ["is4080Server", "is5080Server", "nuked"] {
if let Some(value) = zone.get(key).and_then(Value::as_bool) {
normalized.insert(key.to_owned(), json!(value));
}
}
output.insert(zone_id.clone(), Value::Object(normalized));
}
Ok(Value::Object(output))
}
fn build_community_proxy_url(username: &str, password: &str) -> Result<String, String> {
if username.is_empty() {
return Err("Community proxy response omitted credentials".to_owned());
}
let mut url = Url::parse(&format!(
"http://{COMMUNITY_PROXY_HOST}:{COMMUNITY_PROXY_PORT}"
))
.map_err(|_| "Community proxy endpoint is invalid".to_owned())?;
url.set_username(username)
.map_err(|_| "Community proxy username is invalid".to_owned())?;
url.set_password(Some(password))
.map_err(|_| "Community proxy password is invalid".to_owned())?;
Ok(url.to_string())
}
fn normalize_community_proxy_url(raw: &str) -> Result<String, String> {
let url = Url::parse(raw).map_err(|_| "Community proxy returned an invalid URL".to_owned())?;
if url.scheme() != "http"
|| url.host_str() != Some(COMMUNITY_PROXY_HOST)
|| url.port() != Some(COMMUNITY_PROXY_PORT)
|| url.username().is_empty()
|| url.password().is_none()
|| (url.path() != "" && url.path() != "/")
|| url.query().is_some()
|| url.fragment().is_some()
{
return Err("Community proxy returned an invalid URL".to_owned());
}
Ok(url.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn printed_waste_payloads_are_strictly_normalized() {
let queue = normalize_queue(&json!({"status":true,"data":{
"zone-a":{"QueuePosition":42,"Last Updated":123,"Region":"EU","eta":9},
"bad":{"QueuePosition":"many"}
}}))
.unwrap();
assert_eq!(queue.as_object().unwrap().len(), 1);
assert_eq!(queue["zone-a"]["Region"], "EU");
let mapping = normalize_server_mapping(&json!({"status":true,"data":{
"zone-a":{"title":"Paris","region":"EU","nuked":false,"ignored":"x"}
}}))
.unwrap();
assert_eq!(mapping["zone-a"]["title"], "Paris");
assert!(mapping["zone-a"].get("ignored").is_none());
}
#[test]
fn community_proxy_credentials_are_encoded_and_endpoint_scoped() {
let value = build_community_proxy_url("player name", "p@ss/word").unwrap();
let parsed = Url::parse(&value).unwrap();
assert_eq!(parsed.host_str(), Some(COMMUNITY_PROXY_HOST));
assert_eq!(parsed.port(), Some(COMMUNITY_PROXY_PORT));
assert_eq!(parsed.username(), "player%20name");
assert!(normalize_community_proxy_url(&value).is_ok());
assert!(normalize_community_proxy_url("http://evil.example:51545/u").is_err());
}
}
@@ -0,0 +1,506 @@
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64;
use rand::RngCore as _;
use scrypt::{Params, scrypt};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use subtle::ConstantTimeEq as _;
const PIN_MAX_ATTEMPTS: u32 = 5;
const LOCKOUT_STEPS_MS: [u64; 4] = [30_000, 60_000, 300_000, 900_000];
const SCRYPT_LOG_N: u8 = 15;
const SCRYPT_R: u32 = 8;
const SCRYPT_P: u32 = 1;
const KEY_LENGTH: usize = 32;
const SALT_LENGTH: usize = 16;
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PinRecord {
version: u32,
algorithm: String,
log_n: u8,
r: u32,
p: u32,
key_length: usize,
salt: String,
hash: String,
}
#[derive(Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct AttemptState {
failed_attempts: u32,
lockout_level: usize,
locked_until_ms: Option<u64>,
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Profile {
user_id: String,
pin: Option<PinRecord>,
attempts: AttemptState,
updated_at_ms: u64,
}
#[derive(Default, Serialize, Deserialize)]
struct Document {
version: u32,
profiles: Vec<Profile>,
}
pub struct ConsoleProfiles {
path: PathBuf,
mutation: Mutex<()>,
profiles: Mutex<HashMap<String, Profile>>,
}
impl ConsoleProfiles {
pub fn load(data_dir: &Path) -> Self {
// Electron owns console-profiles.json and wraps it with safeStorage.
// Keep the Qt/Rust format separate so a migration trial never makes
// the shipping rollback client unable to read its profile locks.
let path = data_dir.join("console-profiles-qt.json");
let profiles = fs::read_to_string(&path)
.ok()
.and_then(|text| serde_json::from_str::<Document>(&text).ok())
.map(|document| {
document
.profiles
.into_iter()
.filter(|profile| !profile.user_id.is_empty())
.map(|profile| (profile.user_id.clone(), profile))
.collect()
})
.unwrap_or_default();
Self {
path,
mutation: Mutex::new(()),
profiles: Mutex::new(profiles),
}
}
pub fn has_pin(&self, user_id: &str) -> bool {
self.profiles
.lock()
.expect("console profiles poisoned")
.get(user_id)
.is_some_and(|profile| profile.pin.is_some())
}
pub fn status(&self, user_id: &str) -> Value {
let profiles = self.profiles.lock().expect("console profiles poisoned");
let Some(profile) = profiles
.get(user_id)
.filter(|profile| profile.pin.is_some())
else {
return json!({
"userId":user_id,"hasPin":false,"lockedUntilMs":null,
"remainingAttempts":PIN_MAX_ATTEMPTS
});
};
let gate = gate(&profile.attempts, now_ms());
json!({
"userId":user_id,"hasPin":true,"lockedUntilMs":gate.locked_until_ms,
"remainingAttempts":gate.remaining_attempts
})
}
pub fn set_pin(
&self,
user_id: &str,
pin: &str,
current_pin: Option<&str>,
) -> Result<Value, String> {
let _mutation = self
.mutation
.lock()
.expect("console profile mutation poisoned");
if !valid_pin(pin) {
return Ok(
json!({"ok":false,"reason":"invalid_format","hasPin":self.has_pin(user_id)}),
);
}
let mut next = self
.profiles
.lock()
.expect("console profiles poisoned")
.clone();
let now = now_ms();
let profile = next.entry(user_id.to_owned()).or_insert_with(|| Profile {
user_id: user_id.to_owned(),
pin: None,
attempts: AttemptState::default(),
updated_at_ms: 0,
});
if let Some(existing) = profile.pin.as_ref() {
let gate = gate(&profile.attempts, now);
if !gate.allowed {
return Ok(
json!({"ok":false,"reason":"locked_out","hasPin":true,"lockedUntilMs":gate.locked_until_ms}),
);
}
let Some(current_pin) = current_pin.filter(|pin| valid_pin(pin)) else {
return Ok(json!({"ok":false,"reason":"invalid_format","hasPin":true}));
};
if !verify_hash(current_pin, existing) {
register_failure(&mut profile.attempts, now);
self.persist_and_replace(next)?;
return Ok(json!({"ok":false,"reason":"invalid_pin","hasPin":true}));
}
}
profile.pin = Some(hash_pin(pin)?);
profile.attempts = AttemptState::default();
profile.updated_at_ms = now;
self.persist_and_replace(next)?;
Ok(json!({"ok":true,"hasPin":true}))
}
pub fn clear_pin(&self, user_id: &str, current_pin: &str) -> Result<Value, String> {
let _mutation = self
.mutation
.lock()
.expect("console profile mutation poisoned");
let mut next = self
.profiles
.lock()
.expect("console profiles poisoned")
.clone();
let Some(profile) = next.get_mut(user_id) else {
return Ok(json!({"ok":false,"reason":"no_pin_set","hasPin":false}));
};
let Some(existing) = profile.pin.as_ref() else {
return Ok(json!({"ok":false,"reason":"no_pin_set","hasPin":false}));
};
let now = now_ms();
let gate = gate(&profile.attempts, now);
if !gate.allowed {
return Ok(
json!({"ok":false,"reason":"locked_out","hasPin":true,"lockedUntilMs":gate.locked_until_ms}),
);
}
if !valid_pin(current_pin) {
return Ok(json!({"ok":false,"reason":"invalid_format","hasPin":true}));
}
if !verify_hash(current_pin, existing) {
register_failure(&mut profile.attempts, now);
self.persist_and_replace(next)?;
return Ok(json!({"ok":false,"reason":"invalid_pin","hasPin":true}));
}
profile.pin = None;
profile.attempts = AttemptState::default();
profile.updated_at_ms = now;
self.persist_and_replace(next)?;
Ok(json!({"ok":true,"hasPin":false}))
}
pub fn verify(&self, user_id: &str, pin: &str) -> Result<Value, String> {
let _mutation = self
.mutation
.lock()
.expect("console profile mutation poisoned");
let mut next = self
.profiles
.lock()
.expect("console profiles poisoned")
.clone();
let Some(profile) = next.get_mut(user_id) else {
return Ok(
json!({"ok":true,"reason":"no_pin_set","remainingAttempts":PIN_MAX_ATTEMPTS,"lockedUntilMs":null}),
);
};
let Some(record) = profile.pin.as_ref() else {
return Ok(
json!({"ok":true,"reason":"no_pin_set","remainingAttempts":PIN_MAX_ATTEMPTS,"lockedUntilMs":null}),
);
};
let now = now_ms();
let current_gate = gate(&profile.attempts, now);
if !current_gate.allowed {
return Ok(
json!({"ok":false,"reason":"locked_out","remainingAttempts":0,"lockedUntilMs":current_gate.locked_until_ms}),
);
}
if !valid_pin(pin) {
return Ok(
json!({"ok":false,"reason":"invalid_format","remainingAttempts":current_gate.remaining_attempts,"lockedUntilMs":null}),
);
}
if verify_hash(pin, record) {
profile.attempts = AttemptState::default();
self.persist_and_replace(next)?;
return Ok(
json!({"ok":true,"remainingAttempts":PIN_MAX_ATTEMPTS,"lockedUntilMs":null}),
);
}
register_failure(&mut profile.attempts, now);
let next_gate = gate(&profile.attempts, now);
self.persist_and_replace(next)?;
Ok(json!({
"ok":false,
"reason":if next_gate.allowed { "invalid_pin" } else { "locked_out" },
"remainingAttempts":next_gate.remaining_attempts,
"lockedUntilMs":next_gate.locked_until_ms
}))
}
pub fn forget(&self, user_id: &str) -> Result<(), String> {
let _mutation = self
.mutation
.lock()
.expect("console profile mutation poisoned");
let mut next = self
.profiles
.lock()
.expect("console profiles poisoned")
.clone();
if next.remove(user_id).is_some() {
self.persist_and_replace(next)?;
}
Ok(())
}
pub fn forget_all(&self) -> Result<(), String> {
let _mutation = self
.mutation
.lock()
.expect("console profile mutation poisoned");
self.persist_and_replace(HashMap::new())
}
fn persist_and_replace(&self, profiles: HashMap<String, Profile>) -> Result<(), String> {
let mut values = profiles.values().cloned().collect::<Vec<_>>();
values.sort_by(|left, right| left.user_id.cmp(&right.user_id));
let document = Document {
version: 1,
profiles: values,
};
let parent = self.path.parent().unwrap_or_else(|| Path::new("."));
fs::create_dir_all(parent).map_err(|error| error.to_string())?;
let temporary = self.path.with_extension("json.tmp");
let bytes = serde_json::to_vec_pretty(&document).map_err(|error| error.to_string())?;
write_private_file(&temporary, &bytes).map_err(|error| error.to_string())?;
fs::rename(&temporary, &self.path).map_err(|error| error.to_string())?;
*self.profiles.lock().expect("console profiles poisoned") = profiles;
Ok(())
}
}
#[derive(Clone, Copy)]
struct Gate {
allowed: bool,
locked_until_ms: Option<u64>,
remaining_attempts: u32,
}
fn gate(state: &AttemptState, now: u64) -> Gate {
let locked = state.locked_until_ms.is_some_and(|until| now < until);
Gate {
allowed: !locked,
locked_until_ms: locked.then_some(state.locked_until_ms).flatten(),
remaining_attempts: if locked {
0
} else {
PIN_MAX_ATTEMPTS.saturating_sub(state.failed_attempts)
},
}
}
fn register_failure(state: &mut AttemptState, now: u64) {
state.failed_attempts += 1;
if state.failed_attempts < PIN_MAX_ATTEMPTS {
state.locked_until_ms = None;
return;
}
let duration = LOCKOUT_STEPS_MS[state.lockout_level.min(LOCKOUT_STEPS_MS.len() - 1)];
state.failed_attempts = 0;
state.lockout_level = (state.lockout_level + 1).min(LOCKOUT_STEPS_MS.len());
state.locked_until_ms = Some(now.saturating_add(duration));
}
fn hash_pin(pin: &str) -> Result<PinRecord, String> {
let mut salt = [0_u8; SALT_LENGTH];
rand::rng().fill_bytes(&mut salt);
let params = Params::new(SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P, KEY_LENGTH)
.map_err(|error| error.to_string())?;
let mut hash = [0_u8; KEY_LENGTH];
scrypt(pin.as_bytes(), &salt, &params, &mut hash).map_err(|error| error.to_string())?;
Ok(PinRecord {
version: 1,
algorithm: "scrypt".to_owned(),
log_n: SCRYPT_LOG_N,
r: SCRYPT_R,
p: SCRYPT_P,
key_length: KEY_LENGTH,
salt: BASE64.encode(salt),
hash: BASE64.encode(hash),
})
}
fn verify_hash(pin: &str, record: &PinRecord) -> bool {
if record.version != 1
|| record.algorithm != "scrypt"
|| record.key_length == 0
|| record.key_length > 64
{
return false;
}
let Ok(salt) = BASE64.decode(&record.salt) else {
return false;
};
let Ok(expected) = BASE64.decode(&record.hash) else {
return false;
};
if expected.len() != record.key_length {
return false;
}
let Ok(params) = Params::new(record.log_n, record.r, record.p, record.key_length) else {
return false;
};
let mut actual = vec![0_u8; record.key_length];
if scrypt(pin.as_bytes(), &salt, &params, &mut actual).is_err() {
return false;
}
bool::from(actual.ct_eq(&expected))
}
fn valid_pin(pin: &str) -> bool {
pin.len() == 4 && pin.bytes().all(|character| character.is_ascii_digit())
}
fn now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64
}
#[cfg(unix)]
fn write_private_file(path: &Path, data: &[u8]) -> io::Result<()> {
use std::io::Write as _;
use std::os::unix::fs::OpenOptionsExt as _;
let mut file = fs::OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.mode(0o600)
.open(path)?;
file.write_all(data)?;
file.sync_all()
}
#[cfg(not(unix))]
fn write_private_file(path: &Path, data: &[u8]) -> io::Result<()> {
fs::write(path, data)
}
#[cfg(test)]
mod tests {
use super::*;
fn temporary_store() -> (ConsoleProfiles, PathBuf) {
let path = std::env::temp_dir().join(format!(
"opennow-profiles-{}-{}-{}",
std::process::id(),
now_ms(),
rand::random::<u64>()
));
(ConsoleProfiles::load(&path), path)
}
#[test]
fn overlapping_pin_writes_preserve_every_acknowledged_account() {
let directory = tempfile::tempdir().unwrap();
let profiles = ConsoleProfiles::load(directory.path());
let barrier = std::sync::Barrier::new(4);
std::thread::scope(|scope| {
let workers: Vec<_> = (0..4)
.map(|index| {
let profiles = &profiles;
let barrier = &barrier;
scope.spawn(move || {
barrier.wait();
profiles.set_pin(&format!("user-{index}"), "1234", None)
})
})
.collect();
for worker in workers {
assert_eq!(worker.join().unwrap().unwrap()["ok"], true);
}
});
let loaded = ConsoleProfiles::load(directory.path());
for index in 0..4 {
assert!(profiles.has_pin(&format!("user-{index}")));
assert!(loaded.has_pin(&format!("user-{index}")));
}
}
#[test]
fn overlapping_pin_failures_all_count_toward_lockout() {
let directory = tempfile::tempdir().unwrap();
let profiles = ConsoleProfiles::load(directory.path());
profiles.set_pin("user", "1234", None).unwrap();
let barrier = std::sync::Barrier::new(PIN_MAX_ATTEMPTS as usize);
std::thread::scope(|scope| {
let workers: Vec<_> = (0..PIN_MAX_ATTEMPTS)
.map(|_| {
scope.spawn(|| {
barrier.wait();
profiles.verify("user", "0000")
})
})
.collect();
for worker in workers {
assert_eq!(worker.join().unwrap().unwrap()["ok"], false);
}
});
assert_eq!(profiles.status("user")["remainingAttempts"], 0);
let loaded = ConsoleProfiles::load(directory.path());
assert_eq!(loaded.status("user")["remainingAttempts"], 0);
}
#[test]
fn profile_persistence_failure_preserves_committed_state() {
let directory = tempfile::tempdir().unwrap();
let profiles = ConsoleProfiles::load(directory.path());
profiles.set_pin("user", "1234", None).unwrap();
let persisted = fs::read(&profiles.path).unwrap();
fs::create_dir(profiles.path.with_extension("json.tmp")).unwrap();
assert!(profiles.clear_pin("user", "1234").is_err());
assert!(profiles.forget_all().is_err());
assert!(profiles.has_pin("user"));
assert_eq!(fs::read(&profiles.path).unwrap(), persisted);
}
#[test]
fn pin_round_trip_and_lockout_are_persisted() {
let (profiles, path) = temporary_store();
assert_eq!(profiles.set_pin("user", "1234", None).unwrap()["ok"], true);
assert!(profiles.has_pin("user"));
assert_eq!(profiles.verify("user", "1234").unwrap()["ok"], true);
for _ in 0..PIN_MAX_ATTEMPTS {
let _ = profiles.verify("user", "0000").unwrap();
}
assert_eq!(profiles.status("user")["remainingAttempts"], 0);
let loaded = ConsoleProfiles::load(&path);
assert_eq!(loaded.status("user")["remainingAttempts"], 0);
let _ = fs::remove_dir_all(path);
}
#[test]
fn malformed_pin_does_not_consume_an_attempt() {
let (profiles, path) = temporary_store();
profiles.set_pin("user", "1234", None).unwrap();
let result = profiles.verify("user", "1234").unwrap();
assert_eq!(result["reason"], "invalid_format");
assert_eq!(result["remainingAttempts"], PIN_MAX_ATTEMPTS);
let _ = fs::remove_dir_all(path);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,451 @@
use super::SecretStore;
use aes_gcm::aead::{Aead, Payload};
use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use sha2::{Digest, Sha256};
use std::fs;
use std::io::{self, Read as _, Write as _};
use std::path::{Path, PathBuf};
const MAX_SESSION_BYTES: usize = 4 * 1024 * 1024;
const NONCE_BYTES: usize = 12;
const TAG_BYTES: usize = 16;
pub(super) struct EncryptedSecretStore {
root: PathBuf,
keys: Box<dyn SecretStore>,
legacy: Box<dyn SecretStore>,
}
impl EncryptedSecretStore {
pub(super) fn new(
root: PathBuf,
keys: Box<dyn SecretStore>,
legacy: Box<dyn SecretStore>,
) -> Self {
Self { root, keys, legacy }
}
fn path(&self, user_id: &str) -> PathBuf {
let digest = Sha256::digest(user_id.as_bytes());
self.root.join(format!("{digest:x}.bin"))
}
fn read_key(&self, user_id: &str) -> Result<Option<[u8; 32]>, String> {
let Some(encoded) = self.keys.get(user_id)? else {
return Ok(None);
};
if encoded.len() != 44 {
return Err("Saved session encryption key is invalid".into());
}
let bytes = STANDARD
.decode(encoded)
.map_err(|_| "Saved session encryption key is invalid")?;
let key = bytes
.try_into()
.map_err(|_| "Saved session encryption key is invalid")?;
Ok(Some(key))
}
fn write_encrypted(&self, path: &Path, user_id: &str, encoded: &str) -> Result<(), String> {
let key = match self.read_key(user_id)? {
Some(key) => key,
None => {
let key = rand::random::<[u8; 32]>();
if path.exists() {
return Err("Saved session encryption key is missing".into());
}
self.keys.set(user_id, &STANDARD.encode(key))?;
key
}
};
let nonce = rand::random::<[u8; NONCE_BYTES]>();
let cipher = Aes256Gcm::new_from_slice(&key)
.map_err(|_| "Saved session encryption key is invalid")?;
let ciphertext = cipher
.encrypt(
Nonce::from_slice(&nonce),
Payload {
msg: encoded.as_bytes(),
aad: user_id.as_bytes(),
},
)
.map_err(|_| "Could not encrypt saved session")?;
fs::create_dir_all(&self.root).map_err(|_| "Could not create secure session directory")?;
let temporary = self
.root
.join(format!("{:032x}.tmp", rand::random::<u128>()));
let result = (|| -> io::Result<()> {
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temporary)?;
file.write_all(&nonce)?;
file.write_all(&ciphertext)?;
file.sync_all()?;
fs::rename(&temporary, path)?;
Ok(())
})();
if result.is_err() {
let _ = fs::remove_file(&temporary);
}
result.map_err(|_| "Could not write encrypted session".into())
}
}
impl SecretStore for EncryptedSecretStore {
fn get(&self, user_id: &str) -> Result<Option<String>, String> {
let file = match fs::File::open(self.path(user_id)) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::NotFound => {
let legacy = self.legacy.get(user_id)?;
if let Some(encoded) = &legacy {
let _ = self.set(user_id, encoded);
}
return Ok(legacy);
}
Err(_) => return Err("Encrypted session could not be read".into()),
};
let mut bytes = Vec::new();
file.take((MAX_SESSION_BYTES + NONCE_BYTES + TAG_BYTES + 1) as u64)
.read_to_end(&mut bytes)
.map_err(|_| "Encrypted session could not be read")?;
if bytes.len() < NONCE_BYTES + TAG_BYTES
|| bytes.len() > MAX_SESSION_BYTES + NONCE_BYTES + TAG_BYTES
{
return Err("Encrypted session exceeds size or format limits".into());
}
let key = self
.read_key(user_id)?
.ok_or("Saved session encryption key is missing")?;
let cipher = Aes256Gcm::new_from_slice(&key)
.map_err(|_| "Saved session encryption key is invalid")?;
let plaintext = cipher
.decrypt(
Nonce::from_slice(&bytes[..NONCE_BYTES]),
Payload {
msg: &bytes[NONCE_BYTES..],
aad: user_id.as_bytes(),
},
)
.map_err(|_| "Encrypted session authentication failed")?;
let encoded =
String::from_utf8(plaintext).map_err(|_| "Encrypted session contains invalid text")?;
let _ = self.legacy.delete(user_id);
Ok(Some(encoded))
}
fn set(&self, user_id: &str, encoded: &str) -> Result<(), String> {
if encoded.len() > MAX_SESSION_BYTES || user_id.trim().is_empty() {
return Err("Saved credential exceeds size or identity limits".into());
}
self.write_encrypted(&self.path(user_id), user_id, encoded)
}
fn delete(&self, user_id: &str) -> Result<(), String> {
let path = self.path(user_id);
let file = match fs::remove_file(path) {
Ok(()) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(_) => Err("Encrypted session could not be removed".into()),
};
let key = self.keys.delete(user_id);
let legacy = self.legacy.delete(user_id);
file.and(key).and(legacy)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
#[derive(Clone, Default)]
struct TestStore {
entries: Arc<Mutex<HashMap<String, String>>>,
limit: Option<usize>,
fail_set: bool,
}
impl SecretStore for TestStore {
fn get(&self, user_id: &str) -> Result<Option<String>, String> {
Ok(self.entries.lock().unwrap().get(user_id).cloned())
}
fn set(&self, user_id: &str, encoded: &str) -> Result<(), String> {
if self.fail_set
|| self
.limit
.is_some_and(|limit| encoded.encode_utf16().count() * 2 > limit)
{
return Err("credential write failed".into());
}
self.entries
.lock()
.unwrap()
.insert(user_id.into(), encoded.into());
Ok(())
}
fn delete(&self, user_id: &str) -> Result<(), String> {
self.entries.lock().unwrap().remove(user_id);
Ok(())
}
}
fn store(root: &Path, keys: TestStore, legacy: TestStore) -> EncryptedSecretStore {
EncryptedSecretStore::new(root.into(), Box::new(keys), Box::new(legacy))
}
#[test]
fn large_session_reopens_without_plaintext_or_credential_blob_overflow() {
let directory = tempfile::tempdir().unwrap();
let root = directory.path().join("secure-sessions");
let keys = TestStore {
limit: Some(2560),
..Default::default()
};
let legacy = TestStore {
limit: Some(2560),
..Default::default()
};
let session = "opaque-payload".repeat(300);
assert!(session.encode_utf16().count() * 2 > 2560);
let first = store(&root, keys.clone(), legacy.clone());
first.set("account", &session).unwrap();
assert!(
!fs::read(first.path("account"))
.unwrap()
.windows(session.len())
.any(|window| window == session.as_bytes())
);
assert_eq!(keys.get("account").unwrap().unwrap().len(), 44);
assert_eq!(
store(&root, keys, legacy).get("account").unwrap(),
Some(session)
);
}
#[test]
fn legacy_migration_survives_failed_write_and_removes_old_entry_after_reopen() {
let directory = tempfile::tempdir().unwrap();
let root = directory.path().join("secure-sessions");
let keys = TestStore::default();
let legacy = TestStore::default();
legacy.set("account", "legacy-session").unwrap();
let blocked = store(
&root,
TestStore {
fail_set: true,
..keys.clone()
},
legacy.clone(),
);
assert_eq!(
blocked.get("account").unwrap().as_deref(),
Some("legacy-session")
);
assert_eq!(
legacy.get("account").unwrap().as_deref(),
Some("legacy-session")
);
assert!(keys.get("account").unwrap().is_none());
keys.set("account", &STANDARD.encode(rand::random::<[u8; 32]>()))
.unwrap();
assert_eq!(
store(&root, keys.clone(), legacy.clone())
.get("account")
.unwrap()
.as_deref(),
Some("legacy-session")
);
assert_eq!(
store(&root, keys, legacy.clone())
.get("account")
.unwrap()
.as_deref(),
Some("legacy-session")
);
assert!(legacy.get("account").unwrap().is_none());
}
#[test]
fn corrupted_or_missing_key_does_not_fall_back_or_rekey_ciphertext() {
let directory = tempfile::tempdir().unwrap();
let root = directory.path().join("secure-sessions");
let keys = TestStore::default();
let legacy = TestStore::default();
let first = store(&root, keys.clone(), legacy.clone());
first.set("account", "current-session").unwrap();
legacy.set("account", "stale-session").unwrap();
let path = first.path("account");
let original = fs::read(&path).unwrap();
keys.delete("account").unwrap();
assert!(first.get("account").unwrap_err().contains("key is missing"));
assert!(
first
.set("account", "replacement")
.unwrap_err()
.contains("key is missing")
);
assert_eq!(fs::read(&path).unwrap(), original);
keys.set("account", &STANDARD.encode(rand::random::<[u8; 32]>()))
.unwrap();
assert!(
first
.get("account")
.unwrap_err()
.contains("authentication failed")
);
assert_eq!(
legacy.get("account").unwrap().as_deref(),
Some("stale-session")
);
first.delete("account").unwrap();
assert!(!path.exists());
assert!(keys.get("account").unwrap().is_none());
assert!(legacy.get("account").unwrap().is_none());
}
#[test]
fn oversized_input_and_ciphertext_are_rejected_without_migration() {
let directory = tempfile::tempdir().unwrap();
let root = directory.path().join("secure-sessions");
let keys = TestStore::default();
let legacy = TestStore::default();
let first = store(&root, keys.clone(), legacy.clone());
assert!(
first
.set("account", &"x".repeat(MAX_SESSION_BYTES + 1))
.is_err()
);
assert!(keys.get("account").unwrap().is_none());
fs::create_dir_all(&root).unwrap();
fs::write(
first.path("account"),
vec![0; MAX_SESSION_BYTES + NONCE_BYTES + TAG_BYTES + 1],
)
.unwrap();
legacy.set("account", "old-session").unwrap();
assert!(first.get("account").unwrap_err().contains("size or format"));
assert_eq!(
legacy.get("account").unwrap().as_deref(),
Some("old-session")
);
}
#[test]
fn sign_out_deletes_both_stores_and_next_sign_in_uses_new_key() {
let directory = tempfile::tempdir().unwrap();
let root = directory.path().join("secure-sessions");
let keys = TestStore::default();
let legacy = TestStore::default();
let vault = store(&root, keys.clone(), legacy.clone());
vault.set("account", "old-session").unwrap();
let old_key = keys.get("account").unwrap().unwrap();
vault.delete("account").unwrap();
assert!(vault.get("account").unwrap().is_none());
vault.set("account", "new-session").unwrap();
assert_ne!(keys.get("account").unwrap().unwrap(), old_key);
assert_eq!(
store(&root, keys, legacy)
.get("account")
.unwrap()
.as_deref(),
Some("new-session")
);
}
#[cfg(windows)]
#[test]
fn windows_credential_manager_migrates_and_restores_after_restart() {
use crate::credential_vault::{
CredentialVault, KEY_SERVICE_NAME, SERVICE_NAME, credential,
};
struct Cleanup(String);
impl Drop for Cleanup {
fn drop(&mut self) {
let _ = credential(SERVICE_NAME, &self.0)
.and_then(|entry| entry.delete_credential().map_err(|error| error.to_string()));
let _ = credential(KEY_SERVICE_NAME, &self.0)
.and_then(|entry| entry.delete_credential().map_err(|error| error.to_string()));
}
}
let directory = tempfile::tempdir().unwrap();
let user_id = format!("opennow-vault-test-{:032x}", rand::random::<u128>());
let _cleanup = Cleanup(user_id.clone());
let mut session = super::super::tests::sample_session(&user_id);
let legacy = serde_json::to_string(&session).unwrap();
credential(SERVICE_NAME, &user_id)
.unwrap()
.set_password(&legacy)
.unwrap();
let vault = CredentialVault::new(directory.path().into());
vault
.write_metadata(&super::super::Metadata {
active_user_id: Some(user_id.clone()),
accounts: vec![super::super::tests::sample_identity(&user_id)],
..Default::default()
})
.unwrap();
assert_eq!(vault.load_active().unwrap().unwrap().user.user_id, user_id);
drop(vault);
let reopened = CredentialVault::new(directory.path().into());
assert_eq!(
reopened.load_active().unwrap().unwrap().user.user_id,
user_id
);
assert!(matches!(
credential(SERVICE_NAME, &user_id).unwrap().get_password(),
Err(keyring::Error::NoEntry)
));
session.tokens.access_token = "x".repeat(1800);
let size = serde_json::to_string(&session).unwrap().len();
assert!((1944..2560).contains(&size), "fixture size: {size}");
reopened.save(&session).unwrap();
drop(reopened);
let restored = CredentialVault::new(directory.path().into());
assert_eq!(
restored.load_active().unwrap().unwrap().tokens.access_token,
session.tokens.access_token
);
let encrypted = directory
.path()
.join("secure-sessions")
.join(format!("{:x}.bin", Sha256::digest(user_id.as_bytes())));
assert!(
!fs::read(encrypted)
.unwrap()
.windows(1800)
.any(|window| window == session.tokens.access_token.as_bytes())
);
session.tokens.access_token = "x".repeat(3200);
assert!(
serde_json::to_string(&session)
.unwrap()
.encode_utf16()
.count()
* 2
> 2560
);
restored.save(&session).unwrap();
drop(restored);
let restored = CredentialVault::new(directory.path().into());
assert_eq!(
restored.load_active().unwrap().unwrap().tokens.access_token,
session.tokens.access_token
);
restored.remove(&user_id).unwrap();
assert!(
CredentialVault::new(directory.path().into())
.load(&user_id)
.unwrap()
.is_none()
);
}
}
@@ -0,0 +1,721 @@
use super::{SecretStore, decode_session, read_bounded};
use sha2::{Digest, Sha256};
use std::fs;
use std::io::{self, Write as _};
use std::path::{Path, PathBuf};
pub(super) struct JsonFallbackStore {
root: PathBuf,
secure: Box<dyn SecretStore>,
}
impl JsonFallbackStore {
pub(super) fn new(root: PathBuf, secure: Box<dyn SecretStore>) -> Self {
Self { root, secure }
}
fn path(&self, user_id: &str) -> PathBuf {
let digest = Sha256::digest(user_id.as_bytes());
self.root.join(format!("{digest:x}.json"))
}
pub(super) fn cleanup_temporary_files(&self) -> Result<(), String> {
let entries = match fs::read_dir(&self.root) {
Ok(entries) => entries,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
Err(_) => return Err("Local session temporary-file cleanup is pending".into()),
};
for entry in entries {
let entry = entry.map_err(|_| "Local session temporary-file cleanup is pending")?;
let name = entry.file_name();
let name = name.to_string_lossy();
if name.strip_suffix(".tmp").is_some_and(|stem| {
stem.len() == 64 && stem.bytes().all(|byte| byte.is_ascii_hexdigit())
}) {
fs::remove_file(entry.path())
.map_err(|_| "Local session temporary-file cleanup is pending")?;
}
}
Ok(())
}
fn write(&self, user_id: &str, encoded: &str) -> Result<(), String> {
let result = (|| -> io::Result<()> {
fs::create_dir_all(&self.root)?;
if !fs::symlink_metadata(&self.root)?.is_dir() {
return Err(io::Error::other("Invalid credential directory"));
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&self.root, fs::Permissions::from_mode(0o700))?;
}
let temporary = self.path(user_id).with_extension("tmp");
match fs::remove_file(&temporary) {
Ok(()) => (),
Err(error) if error.kind() == io::ErrorKind::NotFound => (),
Err(error) => return Err(error),
}
let result = (|| -> io::Result<()> {
let mut file = create_private_file(&temporary)?;
file.write_all(encoded.as_bytes())?;
file.sync_all()?;
drop(file);
fs::rename(&temporary, self.path(user_id))?;
#[cfg(unix)]
fs::File::open(&self.root)?.sync_all()?;
Ok(())
})();
if result.is_err() {
let _ = fs::remove_file(&temporary);
}
result
})();
result.map_err(|_| "Could not save the local session file".into())
}
fn remove_file(&self, user_id: &str) -> Result<(), String> {
let mut result = Ok(());
for path in [self.path(user_id), self.path(user_id).with_extension("tmp")] {
match fs::remove_file(path) {
Ok(()) => (),
Err(error) if error.kind() == io::ErrorKind::NotFound => (),
Err(_) => result = Err("Could not remove the local session file".into()),
}
}
result
}
}
impl SecretStore for JsonFallbackStore {
fn get(&self, user_id: &str) -> Result<Option<String>, String> {
match read_bounded(&self.path(user_id)) {
Ok(bytes) => {
let encoded = String::from_utf8(bytes).map_err(|_| "Local session is invalid")?;
decode_session(&encoded, user_id)?;
Ok(Some(encoded))
}
Err(error) if error.kind() == io::ErrorKind::NotFound => self.secure.get(user_id),
Err(_) => Err("Could not read the local session file".into()),
}
}
fn set(&self, user_id: &str, encoded: &str) -> Result<(), String> {
decode_session(encoded, user_id)?;
let local = self
.path(user_id)
.try_exists()
.map_err(|_| "Could not inspect local session")?;
if local {
self.write(user_id, encoded)?;
}
if self.secure.set(user_id, encoded).is_ok()
&& self.secure.get(user_id).ok().flatten().as_deref() == Some(encoded)
{
self.remove_file(user_id)?;
return Ok(());
}
if !local {
self.write(user_id, encoded)?;
}
Ok(())
}
fn delete(&self, user_id: &str) -> Result<(), String> {
let local = self.remove_file(user_id);
let secure = self.secure.delete(user_id);
local.and(secure)
}
fn remove_all_local(
&self,
remove_account: &dyn Fn(&str) -> Result<(), String>,
) -> Result<(), String> {
match fs::symlink_metadata(&self.root) {
Ok(metadata) if metadata.is_dir() => (),
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
_ => return Err("Local session directory cleanup is pending".into()),
}
let entries =
fs::read_dir(&self.root).map_err(|_| "Local session directory cleanup is pending")?;
let mut failure = None;
for entry in entries {
let entry = match entry {
Ok(entry) => entry,
Err(_) => {
failure.get_or_insert_with(|| "Local session entry cleanup is pending".into());
continue;
}
};
let path = entry.path();
let Some(extension @ ("json" | "tmp")) =
path.extension().and_then(|value| value.to_str())
else {
continue;
};
if !path
.file_stem()
.and_then(|value| value.to_str())
.is_some_and(|stem| {
stem.len() == 64 && stem.bytes().all(|byte| byte.is_ascii_hexdigit())
})
{
continue;
}
let session = if entry.file_type().is_ok_and(|kind| kind.is_file()) {
match read_bounded(&path) {
Ok(bytes) => serde_json::from_slice::<super::AuthSession>(&bytes).ok(),
Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
Err(_) => None,
}
} else {
None
};
if let Some(session) = session.filter(|session| {
!session.user.user_id.trim().is_empty()
&& self.path(&session.user.user_id).with_extension(extension) == path
}) {
if let Err(error) = remove_account(&session.user.user_id) {
failure.get_or_insert(error);
}
} else {
failure.get_or_insert_with(|| {
"Local session identity could not be recovered; secure cleanup is pending"
.into()
});
}
match fs::remove_file(&path) {
Ok(()) => (),
Err(error) if error.kind() == io::ErrorKind::NotFound => (),
Err(_) => {
failure.get_or_insert_with(|| "Could not remove the local session file".into());
}
}
}
failure.map_or(Ok(()), Err)
}
fn is_plaintext(&self, user_id: &str) -> bool {
self.path(user_id).exists()
}
}
#[cfg(unix)]
fn create_private_file(path: &Path) -> io::Result<fs::File> {
use std::os::unix::fs::OpenOptionsExt;
fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(path)
}
#[cfg(windows)]
fn create_private_file(path: &Path) -> io::Result<fs::File> {
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::FromRawHandle;
use windows_sys::Win32::Foundation::{INVALID_HANDLE_VALUE, LocalFree};
use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
use windows_sys::Win32::Storage::FileSystem::{
CREATE_NEW, CreateFileW, FILE_ATTRIBUTE_NORMAL, FILE_GENERIC_WRITE,
};
let text: Vec<u16> = "D:P(A;;FA;;;OW)(A;;FA;;;SY)"
.encode_utf16()
.chain(Some(0))
.collect();
let mut descriptor = std::ptr::null_mut();
if unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
text.as_ptr(),
1,
&mut descriptor,
std::ptr::null_mut(),
)
} == 0
{
return Err(io::Error::last_os_error());
}
let attributes = SECURITY_ATTRIBUTES {
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: descriptor,
bInheritHandle: 0,
};
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
let handle = unsafe {
CreateFileW(
wide.as_ptr(),
FILE_GENERIC_WRITE,
0,
&attributes,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
std::ptr::null_mut(),
)
};
let error = io::Error::last_os_error();
unsafe {
LocalFree(descriptor);
}
if handle == INVALID_HANDLE_VALUE {
return Err(error);
}
Ok(unsafe { fs::File::from_raw_handle(handle) })
}
#[cfg(test)]
mod tests {
use super::*;
use crate::credential_vault::{CredentialVault, MemorySecretStore, tests::sample_session};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
#[derive(Clone, Default)]
struct Store {
entries: Arc<Mutex<HashMap<String, String>>>,
unavailable: Arc<AtomicBool>,
discard_writes: Arc<AtomicBool>,
}
impl SecretStore for Store {
fn get(&self, user_id: &str) -> Result<Option<String>, String> {
if self.unavailable.load(Ordering::SeqCst) {
return Err("unavailable".into());
}
Ok(self.entries.lock().unwrap().get(user_id).cloned())
}
fn set(&self, user_id: &str, encoded: &str) -> Result<(), String> {
if self.unavailable.load(Ordering::SeqCst) {
return Err("unavailable".into());
}
if !self.discard_writes.load(Ordering::SeqCst) {
self.entries
.lock()
.unwrap()
.insert(user_id.into(), encoded.into());
}
Ok(())
}
fn delete(&self, user_id: &str) -> Result<(), String> {
if self.unavailable.load(Ordering::SeqCst) {
return Err("unavailable".into());
}
self.entries.lock().unwrap().remove(user_id);
Ok(())
}
}
#[test]
fn secure_store_is_preferred_without_creating_json() {
let directory = tempfile::tempdir().unwrap();
let vault = CredentialVault::with_store(directory.path().into(), Box::<Store>::default());
let session = sample_session("user");
vault.save(&session).unwrap();
assert_eq!(vault.persistence_state(&session), "secure-store");
assert!(!directory.path().join("fallback-sessions").exists());
}
#[test]
fn logout_all_cleans_orphans_without_readable_metadata() {
for corrupt in [false, true] {
let directory = tempfile::tempdir().unwrap();
let secure = Store::default();
let vault =
CredentialVault::with_store(directory.path().into(), Box::new(secure.clone()));
let session = sample_session("orphan");
vault.save(&session).unwrap();
secure.unavailable.store(true, Ordering::SeqCst);
vault.save(&session).unwrap();
secure.unavailable.store(false, Ordering::SeqCst);
if corrupt {
fs::write(directory.path().join("accounts.json"), "invalid metadata").unwrap();
} else {
fs::remove_file(directory.path().join("accounts.json")).unwrap();
}
let result = vault.remove_all();
assert_eq!(result.is_err(), corrupt);
assert_eq!(
fs::read_dir(directory.path().join("fallback-sessions"))
.unwrap()
.count(),
0
);
assert!(secure.get("orphan").unwrap().is_none());
if corrupt {
assert_eq!(
fs::read_to_string(directory.path().join("accounts.json")).unwrap(),
"invalid metadata"
);
} else {
assert!(vault.load("orphan").unwrap().is_none());
}
}
}
#[test]
fn logout_all_suppresses_orphans_when_secure_delete_fails() {
let directory = tempfile::tempdir().unwrap();
let secure = Store::default();
let vault = CredentialVault::with_store(directory.path().into(), Box::new(secure.clone()));
let session = sample_session("orphan");
vault.save(&session).unwrap();
secure.unavailable.store(true, Ordering::SeqCst);
vault.save(&session).unwrap();
fs::remove_file(directory.path().join("accounts.json")).unwrap();
assert!(vault.remove_all().is_err());
assert_eq!(
fs::read_dir(directory.path().join("fallback-sessions"))
.unwrap()
.count(),
0
);
secure.unavailable.store(false, Ordering::SeqCst);
assert!(secure.get("orphan").unwrap().is_some());
let reopened =
CredentialVault::with_store(directory.path().into(), Box::new(secure.clone()));
assert!(reopened.load_active().unwrap().is_none());
assert!(reopened.load("orphan").unwrap().is_none());
reopened.remove_all().unwrap();
assert!(secure.get("orphan").unwrap().is_none());
}
#[test]
fn logout_all_removes_invalid_and_partial_local_files_without_skipping_valid_accounts() {
let directory = tempfile::tempdir().unwrap();
let secure = Store::default();
let vault = CredentialVault::with_store(directory.path().into(), Box::new(secure.clone()));
let root = directory.path().join("fallback-sessions");
let store = JsonFallbackStore::new(root.clone(), Box::new(secure.clone()));
fs::create_dir_all(&root).unwrap();
let invalid = store.path("invalid");
fs::write(&invalid, "invalid-json").unwrap();
let encoded = serde_json::to_string(&sample_session("partial")).unwrap();
secure.set("partial", &encoded).unwrap();
let partial = store.path("partial").with_extension("tmp");
fs::write(&partial, encoded).unwrap();
let other = root.join("unrelated.json");
fs::write(&other, "unrelated").unwrap();
assert!(vault.remove_all().is_err());
assert!(!invalid.exists());
assert!(!partial.exists());
assert!(other.exists());
assert!(secure.get("partial").unwrap().is_none());
assert!(vault.load("partial").unwrap().is_none());
}
#[test]
fn metadata_failure_does_not_hide_plaintext_storage() {
let directory = tempfile::tempdir().unwrap();
let vault = CredentialVault::without_os_store(directory.path().into());
let mut session = sample_session("user");
vault.save(&session).unwrap();
fs::create_dir(directory.path().join("accounts.json.tmp")).unwrap();
session.tokens.refresh_token = Some("new-test-token".into());
assert!(vault.save(&session).is_err());
assert_eq!(vault.failed_save_state(&session), "local-file");
assert!(!vault.warnings().is_empty());
drop(vault);
let restored = CredentialVault::without_os_store(directory.path().into());
assert_eq!(
restored
.load_active()
.unwrap()
.unwrap()
.tokens
.refresh_token,
session.tokens.refresh_token
);
fs::remove_dir(directory.path().join("accounts.json.tmp")).unwrap();
restored.save(&session).unwrap();
assert!(restored.warnings().is_empty());
}
#[test]
fn restart_cleans_interrupted_plaintext_writes_without_account_metadata() {
let directory = tempfile::tempdir().unwrap();
let root = directory.path().join("fallback-sessions");
fs::create_dir(&root).unwrap();
let store = JsonFallbackStore::new(root.clone(), Box::<Store>::default());
let session = serde_json::to_string(&sample_session("unindexed")).unwrap();
let pending = store.path("unindexed").with_extension("tmp");
fs::write(&pending, &session).unwrap();
let committed = store.path("other");
fs::write(&committed, "not-temporary").unwrap();
CredentialVault::without_os_store(directory.path().into());
assert!(!pending.exists());
assert!(committed.exists());
assert!(!directory.path().join("accounts.json").exists());
}
#[test]
fn logout_and_save_remove_only_the_accounts_interrupted_write() {
let directory = tempfile::tempdir().unwrap();
let store = JsonFallbackStore::new(
directory.path().into(),
Box::new(MemorySecretStore {
unavailable: true,
..Default::default()
}),
);
let encoded = serde_json::to_string(&sample_session("user")).unwrap();
let pending = store.path("user").with_extension("tmp");
let other = store.path("other").with_extension("tmp");
fs::write(&pending, &encoded).unwrap();
fs::write(&other, &encoded).unwrap();
assert!(store.delete("user").is_err());
assert!(!pending.exists());
assert!(other.exists());
fs::write(&pending, &encoded).unwrap();
store.set("user", &encoded).unwrap();
assert!(!pending.exists());
assert!(other.exists());
assert_eq!(
store.get("user").unwrap().as_deref(),
Some(encoded.as_str())
);
}
#[test]
fn latest_json_wins_until_a_verified_secure_save() {
let directory = tempfile::tempdir().unwrap();
let secure = Store::default();
let vault = CredentialVault::with_store(directory.path().into(), Box::new(secure.clone()));
let mut session = sample_session("user");
vault.save(&session).unwrap();
secure.unavailable.store(true, Ordering::SeqCst);
session.tokens.refresh_token = Some("refreshed-test-token".into());
vault.save(&session).unwrap();
assert_eq!(vault.persistence_state(&session), "local-file");
drop(vault);
secure.unavailable.store(false, Ordering::SeqCst);
let restored =
CredentialVault::with_store(directory.path().into(), Box::new(secure.clone()));
assert_eq!(
restored
.load_active()
.unwrap()
.unwrap()
.tokens
.refresh_token,
Some("refreshed-test-token".into())
);
assert_eq!(restored.persistence_state(&session), "local-file");
secure.discard_writes.store(true, Ordering::SeqCst);
restored.save(&session).unwrap();
assert_eq!(restored.persistence_state(&session), "local-file");
secure.discard_writes.store(false, Ordering::SeqCst);
restored.save(&session).unwrap();
assert_eq!(restored.persistence_state(&session), "secure-store");
assert_eq!(
fs::read_dir(directory.path().join("fallback-sessions"))
.unwrap()
.count(),
0
);
assert_eq!(
restored
.load_active()
.unwrap()
.unwrap()
.tokens
.refresh_token,
Some("refreshed-test-token".into())
);
restored.remove("user").unwrap();
assert!(secure.get("user").unwrap().is_none());
}
#[test]
fn logout_removes_json_and_suppresses_old_secure_grant() {
let directory = tempfile::tempdir().unwrap();
let secure = Store::default();
let vault = CredentialVault::with_store(directory.path().into(), Box::new(secure.clone()));
let mut session = sample_session("user");
vault.save(&session).unwrap();
secure.unavailable.store(true, Ordering::SeqCst);
session.tokens.refresh_token = Some("new-test-token".into());
vault.save(&session).unwrap();
assert!(vault.remove("user").is_err());
assert_eq!(
fs::read_dir(directory.path().join("fallback-sessions"))
.unwrap()
.count(),
0
);
secure.unavailable.store(false, Ordering::SeqCst);
let restored = CredentialVault::with_store(directory.path().into(), Box::new(secure));
assert!(restored.load("user").unwrap().is_none());
assert!(restored.load_active().unwrap().is_none());
restored.remove("user").unwrap();
assert!(restored.warnings().is_empty());
}
#[test]
fn windows_encryption_store_without_vault_keys_uses_json() {
let directory = tempfile::tempdir().unwrap();
let unavailable = || {
Box::new(MemorySecretStore {
unavailable: true,
..Default::default()
}) as Box<dyn SecretStore>
};
let secure = super::super::encrypted_secret_store::EncryptedSecretStore::new(
directory.path().join("secure-sessions"),
unavailable(),
unavailable(),
);
let vault = CredentialVault::with_store(directory.path().into(), Box::new(secure));
let session = sample_session("user");
vault.save(&session).unwrap();
assert_eq!(vault.persistence_state(&session), "local-file");
assert!(vault.durable(&session));
assert!(!directory.path().join("secure-sessions").exists());
}
#[test]
fn malformed_or_mismatched_local_json_does_not_restore_stale_secure_tokens() {
let directory = tempfile::tempdir().unwrap();
let store = JsonFallbackStore::new(directory.path().into(), Box::<Store>::default());
let encoded = serde_json::to_string(&sample_session("user")).unwrap();
store.secure.set("user", &encoded).unwrap();
fs::write(store.path("user"), "invalid-json").unwrap();
assert!(store.get("user").is_err());
fs::write(
store.path("user"),
serde_json::to_string(&sample_session("other")).unwrap(),
)
.unwrap();
assert!(store.get("user").is_err());
assert!(store.set("other", &encoded).is_err());
assert!(store.set("user", &"x".repeat(4 * 1024 * 1024 + 1)).is_err());
assert_ne!(store.path("a/b"), store.path("a_b"));
assert_eq!(store.path("../../outside").parent(), Some(directory.path()));
}
#[test]
fn unwritable_fallback_reports_failure_without_temporary_files() {
let directory = tempfile::tempdir().unwrap();
let root = directory.path().join("not-a-directory");
fs::write(&root, "blocked").unwrap();
let store = JsonFallbackStore::new(
root,
Box::new(MemorySecretStore {
unavailable: true,
..Default::default()
}),
);
assert!(
store
.set(
"user",
&serde_json::to_string(&sample_session("user")).unwrap()
)
.is_err()
);
assert_eq!(fs::read_dir(directory.path()).unwrap().count(), 1);
}
#[cfg(unix)]
#[test]
fn json_permissions_remain_private_across_atomic_replacements() {
use std::os::unix::fs::PermissionsExt;
let directory = tempfile::tempdir().unwrap();
let store = JsonFallbackStore::new(
directory.path().join("fallback"),
Box::new(MemorySecretStore {
unavailable: true,
..Default::default()
}),
);
let mut session = sample_session("user");
for token in ["first-test-token", "second-test-token"] {
session.tokens.refresh_token = Some(token.into());
let encoded = serde_json::to_string(&session).unwrap();
store.set("user", &encoded).unwrap();
assert_eq!(
fs::metadata(store.path("user"))
.unwrap()
.permissions()
.mode()
& 0o777,
0o600
);
assert_eq!(
fs::metadata(&store.root).unwrap().permissions().mode() & 0o777,
0o700
);
assert_eq!(
store.get("user").unwrap().as_deref(),
Some(encoded.as_str())
);
assert_eq!(fs::read_dir(&store.root).unwrap().count(), 1);
}
}
#[cfg(windows)]
#[test]
fn windows_json_has_a_protected_owner_and_system_acl_after_replacement() {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Security::Authorization::{GetNamedSecurityInfoW, SE_FILE_OBJECT};
use windows_sys::Win32::Security::{
DACL_SECURITY_INFORMATION, GetSecurityDescriptorControl, SE_DACL_PROTECTED,
};
let directory = tempfile::tempdir().unwrap();
let store = JsonFallbackStore::new(
directory.path().join("fallback"),
Box::new(MemorySecretStore {
unavailable: true,
..Default::default()
}),
);
let mut session = sample_session("user");
for token in ["first-test-token", "second-test-token"] {
session.tokens.refresh_token = Some(token.into());
let encoded = serde_json::to_string(&session).unwrap();
store.set("user", &encoded).unwrap();
assert_eq!(
store.get("user").unwrap().as_deref(),
Some(encoded.as_str())
);
let path: Vec<u16> = store
.path("user")
.as_os_str()
.encode_wide()
.chain(Some(0))
.collect();
let mut descriptor = std::ptr::null_mut();
let mut acl = std::ptr::null_mut();
assert_eq!(
unsafe {
GetNamedSecurityInfoW(
path.as_ptr(),
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
std::ptr::null_mut(),
std::ptr::null_mut(),
&mut acl,
std::ptr::null_mut(),
&mut descriptor,
)
},
0
);
let mut control = 0;
let mut revision = 0;
let success =
unsafe { GetSecurityDescriptorControl(descriptor, &mut control, &mut revision) };
let entries = unsafe { (*acl).AceCount };
unsafe {
LocalFree(descriptor);
}
assert_ne!(success, 0);
assert_ne!(control & SE_DACL_PROTECTED, 0);
assert_eq!(entries, 2);
}
}
}
@@ -0,0 +1,104 @@
use fs2::FileExt;
use serde::{Deserialize, Serialize};
use std::fs::{self, OpenOptions};
use std::io::{Read, Write};
use std::path::Path;
#[derive(Serialize, Deserialize)]
struct Identity {
version: u8,
id: String,
}
pub fn load(data_dir: &Path, legacy_id: impl FnOnce() -> String) -> Result<String, String> {
let load = || -> Result<String, Box<dyn std::error::Error>> {
fs::create_dir_all(data_dir)?;
let lock = OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.open(data_dir.join("device-identity.lock"))?;
lock.lock_exclusive()?;
let path = data_dir.join("device-identity.json");
match fs::File::open(&path) {
Ok(file) => {
let mut bytes = Vec::new();
file.take(4097).read_to_end(&mut bytes)?;
let identity: Identity = serde_json::from_slice(&bytes)?;
if identity.version != 1
|| identity.id.len() != 64
|| !identity.id.bytes().all(|byte| byte.is_ascii_hexdigit())
{
return Err("Device identity is invalid".into());
}
Ok(identity.id)
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
let upgraded = [
"accounts.json",
"auth-state.json",
"sessions",
"pending-session-cleanup.json",
]
.iter()
.any(|name| data_dir.join(name).exists());
let id = if upgraded {
legacy_id()
} else {
use rand::RngCore as _;
let mut bytes = [0u8; 32];
rand::rng().fill_bytes(&mut bytes);
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
};
let temporary = path.with_extension("json.tmp");
let mut file = fs::File::create(&temporary)?;
file.write_all(&serde_json::to_vec(&Identity {
version: 1,
id: id.clone(),
})?)?;
file.sync_all()?;
fs::rename(temporary, path)?;
#[cfg(unix)]
fs::File::open(data_dir)?.sync_all()?;
Ok(id)
}
Err(error) => Err(error.into()),
}
};
load().map_err(|_| "Persistent device identity is unavailable or invalid; restore access to the data directory before signing in".into())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn freezes_legacy_identity_and_refuses_corruption() {
let directory = tempfile::tempdir().unwrap();
fs::write(directory.path().join("accounts.json"), "{}").unwrap();
let original = "a".repeat(64);
assert_eq!(
load(directory.path(), || original.clone()).unwrap(),
original
);
assert_eq!(load(directory.path(), || "b".repeat(64)).unwrap(), original);
fs::write(directory.path().join("device-identity.json"), "broken").unwrap();
assert!(load(directory.path(), || "c".repeat(64)).is_err());
}
#[test]
fn concurrent_fresh_initialization_chooses_one_identity() {
let directory = tempfile::tempdir().unwrap();
std::thread::scope(|scope| {
let workers: Vec<_> = (0..8)
.map(|_| scope.spawn(|| load(directory.path(), || panic!("fresh installation"))))
.collect();
let ids: Vec<_> = workers
.into_iter()
.map(|worker| worker.join().unwrap().unwrap())
.collect();
assert!(ids.iter().all(|id| id == &ids[0] && id.len() == 64));
});
}
}
Loaded 100 of 862 files, more files were not shown because too many files have changed in this diff. Show more