feat: Epic Games Launcher for Linux (#928)

* feat: Epic Games Launcher for Linux

Install Epic's official Linux launcher (EGLv2) from Epic's CDN with Valve's
Steam Runtime 4 and run it under FEX, signed in with the linked Epic account.
Epic games launch through a hidden launcher instance so they get the
launcher's own arguments, with the exchange-code launch as the fallback, and
DroidDeck installs show up in the launcher as installed.

In the launcher, touch scrolls like a phone app and the gamepad drives the UI:
D-pad and left stick move the selection, A opens, B goes back, the right stick
and triggers scroll proportionally, X opens the options menu, Y the keyboard
and LB/RB switch tabs.

* feat: Epic Games Launcher for Linux

Install Epic's official Linux launcher (EGLv2) from Epic's CDN with Valve's
Steam Runtime 4 and run it under FEX, signed in with the linked Epic account.
Epic games launch through a hidden launcher instance so they get the
launcher's own arguments, with the exchange-code launch as the fallback, and
DroidDeck installs show up in the launcher as installed.

In the launcher, touch scrolls like a phone app and the gamepad drives the UI:
D-pad and left stick move the selection, A opens, B goes back, the right stick
and triggers scroll proportionally, X opens the options menu, Y the keyboard
and LB/RB switch tabs.

* Route Epic games through Steam, import launcher installs, offer the second library

- Every Epic launch goes Steam -> Epic Games Launcher -> game; Play inside the open launcher hands the game to Steam
- Games installed from inside the launcher get a Games-tab entry and launch through Steam; the launcher installs to the last Stores target
- Stores install picker offers the Steam second library, with side-by-side choices
- uruntime xattr-only failures no longer fail the launcher unpack (app-extract)

* Hand launcher Play and Steam links to Steam, wait for FEX on first run

Play on a game the launcher just installed is matched to its install
record and handed to Steam. Steam games listed in the launcher open
steam://rungameid links, which now start the game in a Steam session.
Opening the launcher before Steam has downloaded FEX asks Steam for it
and starts Steam instead of failing with no-fex.

* Address review: FEX check, play-in-Steam action, touch route thread, scroll scale

fexReady needs a FEX binary in Steam's FEX tool, not just its folder.
The play-in-Steam action stays until the link is handled, so Run Steam
at startup can't start a session first. The pad touch route reads the
mouse mode without side effects off the main thread and posts the pad
update there. Vertical scroll uses the output height. A status-2 unpack
counts only when AppRun is there. The xdg-open command is tested
end to end for Steam links.

* Open the launcher through Steam, recover dropped shortcuts, sign out of both

The Epic Games Launcher now runs as its own Steam shortcut, so opening
it starts Steam, which opens the launcher, and Play inside it goes to
the running Steam.

Steam dropped a running shortcut from its library when the game exited
after a sleep/wake replay or a server re-logon, and launching it then
waited forever at ShowInterstitials. login1 only replays sleep/wake
when Steam is asleep. The session restarts Steam when a requested
shortcut is missing, and when a game exits with its shortcut gone and
nothing else runs.

Resuming after a long pause no longer reports failure while traced
processes are still waking, so "Steam is paused" goes away on the first
tap.

Signing out of the launcher signs DroidDeck's Epic store out, and
signing out in DroidDeck restarts the launcher signed out and clears
the Epic web cookies.

* Address review: one session-switch poll, Epic setup can't block a session

A new switch confirmation replaces the pending poll instead of adding a
second one that could start the session again. Epic library sync and
install-folder setup at session start are each guarded, so a bad
preference no longer stops the guest from launching.

* Uninstall the Epic Games Launcher from the Games tab

An Uninstall button next to Launch asks first, closes a running
session, and removes the launcher and its runtime. The launcher's
sign-in and install records stay, so its games keep their Games-tab
entries and a reinstall comes back signed in. Its Steam shortcut goes
away on the next Steam start.

* Address review: uninstall only after the session has ended

The launcher's files are removed only once the session is not running
and its phase has ended; a shutdown still in progress after the wait
reports failure instead. The confirmation reads the session state from
the front-end state.

* Find FEX that Steam installed on the second library

Steam's tools on a second library live in DroidDeck's private copy,
which the session binds over the library. The launcher's FEX check
only looked on the shared storage, so with FEX there it always asked
Steam for FEX and only Steam opened. It now checks the private copy
too.

* Start games without Steam, per-game Settings menu with Wine sync

"Start without Steam" now really leaves the Steam client out: the game
runs in its own Proton/FEX through droiddeck-proton-run in a run
session, and the Epic Games Launcher opens on its own with its games
playing in it. Run sessions for these games are not pinned to the big
cores and get DirectAudio and the added-games list like Steam.

The Games tab card is now "Settings", titled "<game> Settings": Start
without Steam, FEX preset, Wine sync (ntsync, fsync, esync, wineserver
or the app default) and Default, which puts everything changed for the
game back to the app's settings. The app-wide Wine sync choice is shown
in the Steam settings Session tab.

* Address review: uninstall guard, routed games, shortcut matching

Opening or reinstalling the Epic Games Launcher waits while it is being
uninstalled. Added games that are Steam installs keep their Start
without Steam setting under their Steam app id and start as that Steam
game. Live shortcut lookups wait for Steam's library to load and match
a same-name shortcut by its executable, so no duplicate is added. The
session treats the open launcher as itself even when it could not tell
its Steam app id.

* Address review: drop a queued launcher switch when it is uninstalled

A confirmed switch to the Epic Games Launcher that is still waiting for
the old session to end is cancelled when the launcher is uninstalled,
and never starts while the uninstall runs. The launcher id test sets
its environment for its own runs only.
This commit is contained in:
MaxsTechReview authored and GitHub committed 2026-10-17 14:40:39 -04:00
1 parent 16f9916825
commit 2fe4d5303c
107 files changed
+8860 -371

No files matched your search

@@ -109,6 +109,10 @@ class MainActivity : ComponentActivity() {
private var frameGenLabel by mutableStateOf("")
private var lossless by mutableStateOf(Lossless.State.NONE)
private var showRemove by mutableStateOf(false)
private var pendingSwitch by mutableStateOf<Intent?>(null)
private var switchingTo: Intent? = null
private var switchPoll: Runnable? = null
private var switchDeadline = 0L
private var showResetSettings by mutableStateOf(false)
private var lowSpace by mutableStateOf<Long?>(null)
private var showNonAdreno by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
@@ -506,6 +510,7 @@ class MainActivity : ComponentActivity() {
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return false
}
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome)
if (SessionState.running) {
if (SessionState.mode != SessionService.MODE_STEAM || SessionState.stopRequested) {
android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
@@ -534,6 +539,159 @@ class MainActivity : ComponentActivity() {
}, steamSession = true)
}
private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean): Boolean {
val app = applicationContext
Thread({
val added = if (game.library == Library.ADDED) runCatching { com.droiddeck.launcher.session.NoSteamLaunch.addedGame(app, game) }.getOrNull() else null
val command = com.droiddeck.launcher.session.NoSteamLaunch.command(game, added)
ui.post {
if (isDestroyed) return@post
if (command == null) {
android.widget.Toast.makeText(this, R.string.game_link_failed, android.widget.Toast.LENGTH_LONG).show()
return@post
}
com.droiddeck.launcher.session.NoSteamLaunch.remember(command)
val next = Intent(this, SessionActivity::class.java)
.putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
.putExtra(SessionService.EXTRA_PROGRAM, command.program)
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, command.args.toTypedArray())
when {
!SessionState.running -> startSessionOrWait(next)
SessionState.stopRequested -> android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
SessionState.mode == SessionService.MODE_RUN && SessionState.program == command.program && SessionState.programArgs == command.args ->
startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
.putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
else -> pendingSwitch = next
}
}
}, "no-steam-launch").start()
return true
}
private fun opensEpicLauncher(next: Intent): Boolean =
next.getStringExtra(SessionService.EXTRA_PROGRAM) == com.droiddeck.launcher.session.NoSteamLaunch.EPIC ||
next.getStringExtra(SessionService.EXTRA_STEAM_URL) == com.droiddeck.launcher.frontend.GameLaunchLink.steamUrl(
com.droiddeck.launcher.stores.epic.EpicClient.gameId(com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId))
private fun uninstallEpicLauncher() {
if (com.droiddeck.launcher.stores.epic.EpicClient.uninstalling) return
com.droiddeck.launcher.stores.epic.EpicClient.uninstalling = true
pendingSwitch?.takeIf(::opensEpicLauncher)?.let { pendingSwitch = null }
switchingTo?.takeIf(::opensEpicLauncher)?.let {
switchPoll?.let { poll -> ui.removeCallbacks(poll) }
switchPoll = null
switchingTo = null
}
if (SessionState.running) SessionService.stop(this)
val app = applicationContext
val deadline = android.os.SystemClock.uptimeMillis() + SESSION_SWITCH_WAIT_MS
Thread({
while ((SessionState.running || SessionState.phase !in SESSION_ENDED) && android.os.SystemClock.uptimeMillis() < deadline) {
Thread.sleep(SESSION_SWITCH_POLL_MS)
}
val ended = !SessionState.running && SessionState.phase in SESSION_ENDED
val done = try {
ended && com.droiddeck.launcher.stores.epic.EpicClient.uninstall(app)
} finally {
com.droiddeck.launcher.stores.epic.EpicClient.uninstalling = false
}
ui.post {
if (!isDestroyed) refresh()
android.widget.Toast.makeText(app, if (done) R.string.epic_client_uninstalled else R.string.epic_client_uninstall_failed,
android.widget.Toast.LENGTH_LONG).show()
}
}, "epic-uninstall").start()
}
private fun openEpicLauncher(): Boolean {
if (com.droiddeck.launcher.stores.epic.EpicClient.uninstalling) {
android.widget.Toast.makeText(this, R.string.epic_client_uninstalling, android.widget.Toast.LENGTH_SHORT).show()
return false
}
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
}
if (!com.droiddeck.launcher.stores.epic.EpicClient.launcherRunning(this) && !com.droiddeck.launcher.stores.epic.EpicClient.fexReady(this)) {
com.droiddeck.launcher.stores.epic.EpicClient.requestFex(this)
android.widget.Toast.makeText(this, R.string.epic_client_needs_fex, android.widget.Toast.LENGTH_LONG).show()
if (!SessionState.running) startSteamSession()
else if (SessionState.mode == SessionService.MODE_STEAM) startActivity(Intent(this, SessionActivity::class.java)
.setAction(SessionService.ACTION_RESUME).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
return true
}
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId)) {
com.droiddeck.launcher.stores.epic.EpicClient.launcherEntry(this, Library.EPIC_LAUNCHER_NAME)?.let { return launchWithoutSteam(it, false) }
}
val launcher = Intent(this, SessionActivity::class.java)
.putExtra(SessionActivity.EXTRA_RETURN_HOME, false)
.putExtra(SessionService.EXTRA_STEAM_URL, com.droiddeck.launcher.frontend.GameLaunchLink.steamUrl(
com.droiddeck.launcher.stores.epic.EpicClient.gameId(com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId)))
if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM && !SessionState.stopRequested) {
val app = applicationContext
val shortcut = com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId
val listed = com.droiddeck.launcher.frontend.AddedGames.inSteam(app, shortcut)
if (listed && !SessionService.launchGame(this, com.droiddeck.launcher.stores.epic.EpicClient.gameId(shortcut))) {
android.widget.Toast.makeText(this, R.string.game_link_failed, android.widget.Toast.LENGTH_LONG).show()
return false
}
startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
.putExtra(SessionActivity.EXTRA_RETURN_HOME, false)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
if (!listed) Thread({
com.droiddeck.launcher.frontend.AddedGamesPublisher.republish(app)
val id = com.droiddeck.launcher.stores.epic.EpicClient.steamLauncherId(app) ?: shortcut
ui.post { SessionService.launchGame(app, com.droiddeck.launcher.stores.epic.EpicClient.gameId(id)) }
}, "epic-launcher-open").start()
return true
}
if (SessionState.running) {
if (SessionState.stopRequested) android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
else pendingSwitch = launcher
return true
}
return startSessionOrWait(launcher)
}
private fun startSessionOrWait(next: Intent): Boolean {
val started = startSession(next, steamSession = next.hasExtra(SessionService.EXTRA_STEAM_URL))
if (!started && (busy || LinuxRuntimeInstaller.isBusy())) android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return started
}
private fun startAfterSession(next: Intent) {
SessionService.stop(this)
awaitSessionEnd(next, android.os.SystemClock.uptimeMillis() + SESSION_SWITCH_WAIT_MS)
}
private fun awaitSessionEnd(next: Intent, deadline: Long) {
switchingTo = next
switchDeadline = deadline
switchPoll?.let { ui.removeCallbacks(it) }
val poll = object : Runnable {
override fun run() {
if (isDestroyed) return
if (SessionState.running || SessionState.phase !in SESSION_ENDED) {
if (android.os.SystemClock.uptimeMillis() < deadline) ui.postDelayed(this, SESSION_SWITCH_POLL_MS)
else {
switchPoll = null
switchingTo = null
android.widget.Toast.makeText(this@MainActivity, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
}
return
}
switchPoll = null
switchingTo = null
if (com.droiddeck.launcher.stores.epic.EpicClient.uninstalling && opensEpicLauncher(next)) return
startSessionOrWait(next)
}
}
switchPoll = poll
ui.postDelayed(poll, SESSION_SWITCH_POLL_MS)
}
private fun handleGameLink(games: List<Library.SteamGame>) {
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return
val id = pendingGameLink ?: return
@@ -666,6 +824,8 @@ class MainActivity : ComponentActivity() {
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) { launchGame(g) }
}
},
onEpicLauncher = { openEpicLauncher() },
onUninstallEpicLauncher = { uninstallEpicLauncher() },
onGameShortcut = { g -> com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g) },
onExportGameFile = { g -> pickGameExport(g) },
onSyncGameFiles = { pickGameExport(null) },
@@ -927,6 +1087,15 @@ class MainActivity : ComponentActivity() {
onDismiss = { showNonAdreno = null },
)
}
pendingSwitch?.let { next ->
ConfirmDialog(
title = androidx.compose.ui.res.stringResource(R.string.drawer_stop_title),
text = runningLabel ?: "",
confirm = androidx.compose.ui.res.stringResource(R.string.drawer_stop),
onConfirm = { pendingSwitch = null; startAfterSession(next) },
onDismiss = { pendingSwitch = null },
)
}
if (showRemove) ConfirmDialog(
title = androidx.compose.ui.res.stringResource(R.string.main_remove_runtime_title),
text = androidx.compose.ui.res.stringResource(R.string.main_remove_runtime_text),
@@ -965,6 +1134,10 @@ class MainActivity : ComponentActivity() {
}
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled() }
else {
pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH)
savedIntent(savedInstanceState, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, savedInstanceState.getLong(KEY_SWITCH_DEADLINE)) }
}
val wanted = ArrayList<String>()
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
@@ -1111,6 +1284,19 @@ class MainActivity : ComponentActivity() {
refreshSecondScreenDisplays()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
switchingTo?.let {
outState.putParcelable(KEY_SWITCHING_TO, it)
outState.putLong(KEY_SWITCH_DEADLINE, switchDeadline)
}
}
private fun savedIntent(state: Bundle, key: String): Intent? =
if (Build.VERSION.SDK_INT >= 33) state.getParcelable(key, Intent::class.java)
else @Suppress("DEPRECATION") state.getParcelable(key)
override fun onDestroy() {
updates.unregister()
super.onDestroy()
@@ -1877,6 +2063,12 @@ class MainActivity : ComponentActivity() {
companion object {
private const val TAG = "MainActivity"
private const val MEDIA_SETTLE_MS = 1500L
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_SWITCHING_TO = "switching_to"
private const val KEY_SWITCH_DEADLINE = "switch_deadline"
private val SESSION_ENDED = setOf(SessionPhase.IDLE, SessionPhase.FAILED)
private val ZIP_EXT = listOf("zip")
private val WCP_EXT = listOf("wcp")
}
@@ -48,6 +48,7 @@ import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreAchievements
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreLaunchRequests
import com.droiddeck.launcher.stores.epic.EpicClient
import com.droiddeck.launcher.ui.SessionAchievements
import com.droiddeck.launcher.gpu.Cardboard
import com.droiddeck.launcher.gpu.FrameGen
@@ -69,12 +70,15 @@ import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.SessionClipboard
import com.droiddeck.launcher.input.OnScreenControls
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.PadMouse
import com.droiddeck.launcher.input.PadState
import com.droiddeck.launcher.input.SteamControllerBle
import com.droiddeck.launcher.input.PointerGestures
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenDisplays
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.input.TouchpadGestures
import com.droiddeck.launcher.input.ScrollTouchGestures
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.LoadingState
import com.droiddeck.launcher.session.PerfHud
@@ -183,6 +187,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var watching = true
private lateinit var touchpad: TouchpadGestures
private lateinit var threeFingerTap: com.droiddeck.launcher.input.ThreeFingerTap
private lateinit var scrollTouch: ScrollTouchGestures
private lateinit var padMouse: PadMouse
@Volatile private var padMouseOn = false
private var padMouseCheckedAt = 0L
private var scrollTouchGesture = false
private var scrollRestX = 0f
private var scrollRestY = 0f
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
private var cursorPos by mutableStateOf(androidx.compose.ui.geometry.Offset(-100f, -100f))
private var cursorVisible by mutableStateOf(false)
@@ -198,6 +209,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (pointerLocked == locked) return@post
pointerLocked = locked
Log.i(TAG, "pointer lock " + if (locked) "taken by a program" else "released")
padMouseCheckedAt = 0L
if (::padMouse.isInitialized) padMouseMode()
// Touchpad deltas are measured from the middle while locked (moveLockedPointer).
if (locked && ::touchpad.isInitialized) {
drawnRect()?.let { touchpad.place(it.centerX(), it.centerY()) }
@@ -363,6 +376,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Log.i(TAG, "input device $deviceId disconnected")
joyConVr?.refresh()
padBridge?.onDeviceRemoved(deviceId)
if (::padMouse.isInitialized) padMouse.reset()
refreshControls()
updatePointerCapture()
updateHandCamera()
@@ -465,6 +479,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
keyboard = KeyboardHost(this).also { root.addView(it) }
touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener)
threeFingerTap = com.droiddeck.launcher.input.ThreeFingerTap(PointerGestures.slop(this) * 2)
padMouse = PadMouse(padMouseListener)
bridge.setTouchRoute(object : PadBridge.TouchRoute {
override fun active(): Boolean = if (Looper.myLooper() == Looper.getMainLooper()) padMouseMode() else padMouseOn
override fun accept(state: PadState) {
if (Looper.myLooper() == Looper.getMainLooper()) padMouse.onTouchPad(state)
else PadState().also { it.copyFrom(state) }.let { copy -> uiHandler.post { padMouse.onTouchPad(copy) } }
}
})
scrollTouch = ScrollTouchGestures(PointerGestures.slop(this),
android.view.ViewConfiguration.get(this).scaledMinimumFlingVelocity.toFloat(), scrollListener)
val noCursor = android.view.PointerIcon.getSystemIcon(this, android.view.PointerIcon.TYPE_NULL)
root.pointerIcon = noCursor
surfaceView.pointerIcon = noCursor
@@ -614,6 +638,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (found == null) achievementsOpen = false
}
androidx.compose.runtime.LaunchedEffect(pcKeyboardOpen) { if (pcKeyboardOpen) releasePads() }
LaunchedEffect(pcKeyboardOpen, drawerOpen, achievementsOpen) {
if (pcKeyboardOpen || drawerOpen || achievementsOpen) padMouse.reset()
}
if (pcKeyboardOpen) com.droiddeck.launcher.ui.PcKeyboard(
sendKey = { code, down -> if (CompositorHost.isStarted) sendGuestKey(code, down) },
onAndroidKeyboard = { pcKeyboardOpen = false; keyboard?.toggle() },
@@ -1224,6 +1251,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val nextTouchMode = SessionPrefs.touchMode(this)
if (touchMode != nextTouchMode) {
if (::touchpad.isInitialized) touchpad.cancel()
if (::scrollTouch.isInitialized) scrollTouch.cancel()
if (CompositorHost.isStarted) {
WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
listOf(PointerGestures.BTN_LEFT, PointerGestures.BTN_RIGHT, PointerGestures.BTN_MIDDLE).forEach {
@@ -1774,6 +1802,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
if ((pcKeyboardOpen || achievementsOpen) && fromController) return super.dispatchKeyEvent(event)
if (joyConVr?.onKeyEvent(event) == true) return true
if (fromController && event.keyCode != KeyEvent.KEYCODE_BACK && padMouseMode() && padMouse.onKey(event)) return true
if (event.keyCode != KeyEvent.KEYCODE_BACK && padBridge?.onKeyEvent(event) == true) return true
if (CompositorHost.isStarted && event.keyCode != KeyEvent.KEYCODE_BACK && !fromController) {
val down = event.action == KeyEvent.ACTION_DOWN
@@ -1818,6 +1847,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (drawerDirectionKey != KeyEvent.KEYCODE_UNKNOWN) releaseDrawerDirection()
if ((pcKeyboardOpen || achievementsOpen) && PadBridge.isControllerMotionEvent(event)) return super.dispatchGenericMotionEvent(event)
if (joyConVr?.onMotionEvent(event) == true) return true
if (PadBridge.isControllerMotionEvent(event) && padMouseMode() && padMouse.onMotion(event)) return true
if (padBridge?.onMotionEvent(event) == true) return true
if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE) && !drawerOpen && onMouse(event)) return true
return super.dispatchGenericMotionEvent(event)
@@ -1920,6 +1950,67 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
private val scrollListener = object : ScrollTouchGestures.Listener {
override fun onMove(x: Float, y: Float) {
val rect = drawnRect() ?: return
val cx = x.coerceIn(rect.left, rect.right)
val cy = y.coerceIn(rect.top, rect.bottom)
WaylandCompositor.nativeSendPointer(1, InputSpace.x(cx, surfaceView.width), InputSpace.y(cy, surfaceView.height))
cursorVisible = false
}
override fun onButton(button: Int, pressed: Boolean) {
WaylandCompositor.nativeSendSceneInput(3, button, if (pressed) 1 else 0)
}
override fun onScroll(dx: Float, dy: Float) {
val rect = drawnRect() ?: return
val out = SessionState.outputSize
scrollRestX += dx * out.first / rect.width()
scrollRestY += dy * out.second / rect.height()
val h = scrollRestX.toInt()
val v = scrollRestY.toInt()
if (h == 0 && v == 0) return
scrollRestX -= h
scrollRestY -= v
WaylandCompositor.nativeSendSceneInput(11, ScrollTouchGestures.wheelUnits(v, out.second), ScrollTouchGestures.wheelUnits(h, out.first))
}
override fun onLongPress() = pointerListener.onLongPress()
}
private val padMouseListener = object : PadMouse.Listener {
override fun active(): Boolean = padMouseMode()
override fun onScrollStart() {
scrollRestX = 0f
scrollRestY = 0f
val rect = drawnRect() ?: return
val x = rect.left + rect.width() * PAD_SCROLL_POINTER_X
WaylandCompositor.nativeSendPointer(1, InputSpace.x(x, surfaceView.width), InputSpace.y(rect.centerY(), surfaceView.height))
cursorVisible = false
}
override fun onScroll(dx: Float, dy: Float) = scrollListener.onScroll(dx, dy)
override fun onKey(evdev: Int, pressed: Boolean) = sendGuestKey(evdev, pressed)
override fun onKeyboard() {
uiHandler.post { togglePcKeyboard() }
}
override fun onNavigate() {
cursorVisible = false
}
override fun scrollSpeed(): Float = (drawnRect()?.height() ?: 0f) * PAD_SCROLL_HEIGHTS_PER_S
}
private fun padMouseMode(): Boolean {
val now = android.os.SystemClock.uptimeMillis()
if (now - padMouseCheckedAt < PAD_MOUSE_CHECK_MS) return padMouseOn
padMouseCheckedAt = now
val on = !pointerLocked && EpicClient.launcherFocused(this) && !EpicClient.playing(this)
if (padMouseOn && !on) padMouse.reset()
if (!padMouseOn && on) padBridge?.releaseAll()
padMouseOn = on
return on
}
private fun scrollTouchMode(): Boolean =
(routedTouchMode == SessionPrefs.TOUCH_AUTO || routedTouchMode == SessionPrefs.TOUCH_DIRECT) && padMouseMode()
private fun moveLockedPointer(x: Float, y: Float) {
val rect = drawnRect() ?: return
val scale = SessionState.outputSize.first / rect.width()
@@ -2147,6 +2238,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
if (next == routedTouchMode) return
if (::touchpad.isInitialized) touchpad.cancel()
if (::scrollTouch.isInitialized) scrollTouch.cancel()
if (CompositorHost.isStarted) WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
if (next == SessionPrefs.TOUCH_OFF) cursorVisible = false
routedTouchMode = next
@@ -2180,6 +2272,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onTouchEvent(event: MotionEvent): Boolean {
if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE)) return onMouse(event)
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
scrollTouchGesture = scrollTouchMode()
scrollRestX = 0f
scrollRestY = 0f
}
if (scrollTouchGesture) return scrollTouch.onTouch(event)
if (routedTouchMode == SessionPrefs.TOUCH_OFF) return true
if (SessionState.mode == SessionService.MODE_STEAM && SessionState.steamUi != "desktop") {
val wasActive = threeFingerTap.active
@@ -2429,6 +2527,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onScreenControls?.releaseAll()
releasePads()
touchpad.cancel()
scrollTouch.cancel()
guestKeysDown.toList().forEach { sendGuestKey(it, false) }
keyboard?.hide()
sessionClipboard.stop()
@@ -2481,6 +2580,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper()))
refreshSecondScreenDisplays()
if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
startedScreens++
SessionService.setActivityVisible(this, true)
Glasses.rescan()
updateGlassesScreen()
@@ -2493,8 +2593,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
updateHandCamera()
displayManager.unregisterDisplayListener(displayListener)
closeSecondScreen(reset = false)
startedScreens = (startedScreens - 1).coerceAtLeast(0)
updateGlassesScreen()
SessionService.setActivityVisible(this, false)
if (startedScreens == 0) SessionService.setActivityVisible(this, false)
super.onStop()
}
@@ -2559,6 +2660,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
(getSystemService(INPUT_SERVICE) as? InputManager)?.unregisterInputDeviceListener(deviceListener)
releaseDrawerDirection()
onScreenControls?.releaseAll()
if (::scrollTouch.isInitialized) scrollTouch.cancel()
if (::padMouse.isInitialized) padMouse.reset()
resumed = false
updatePointerCapture()
updatePadMotion()
@@ -2873,6 +2976,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (!hasFocus && ::padMouse.isInitialized) padMouse.reset()
if (runtimeRemovalBlocked) return
if (hasFocus && !pipUi) {
goFullscreen()
@@ -2986,9 +3090,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
const val EXTRA_STEAMVR = "steamVr"
private const val LEAVE_TIMEOUT_MS = 1_500L
private const val TAG = "SessionActivity"
private var startedScreens = 0
private const val FEX_MISSING = "droiddeck-fex: x86 Linux programs need"
private const val UNBUFFERED_SOURCES = InputDevice.SOURCE_CLASS_JOYSTICK or InputDevice.SOURCE_CLASS_TRACKBALL or InputDevice.SOURCE_CLASS_POSITION
private const val CURSOR_PAD_HOLD_MS = 1200L
private const val PAD_MOUSE_CHECK_MS = 500L
private const val PAD_SCROLL_POINTER_X = 0.985f
private const val PAD_SCROLL_HEIGHTS_PER_S = 3f
private const val DRAWER_HAT_THRESHOLD = 0.5f
private const val DRAWER_STICK_ENTER_THRESHOLD = 0.55f
private const val DRAWER_STICK_EXIT_THRESHOLD = 0.35f
@@ -136,8 +136,12 @@ object AgentGuest {
return null
}
fun call(context: Context, request: JSONObject, timeoutMs: Long): JSONObject {
if (request.optString("kind") in setOf("exec", "cdp")) AgentAccess.requireCommands(context)
fun steamEval(context: Context, expression: String, timeoutMs: Long): JSONObject =
call(context, JSONObject().put("kind", "cdp").put("expression", expression).put("timeout", timeoutMs / 1000.0),
timeoutMs + 2_000, trusted = true)
fun call(context: Context, request: JSONObject, timeoutMs: Long, trusted: Boolean = false): JSONObject {
if (!trusted && request.optString("kind") in setOf("exec", "cdp")) AgentAccess.requireCommands(context)
if (!SessionState.running) throw AgentException("NO_ACTIVE_SESSION", "There is no running session")
hello(context) ?: throw AgentException("AGENT_UNAVAILABLE", "The guest agent is not running in this session (yet)")
val dir = dir(context)
@@ -1,5 +1,7 @@
package com.droiddeck.launcher.core
import com.droiddeck.launcher.session.SessionPrefs
object GameEnvironment {
data class Config(
val shared: Map<String, String?> = emptyMap(),
@@ -83,4 +85,34 @@ object GameEnvironment {
}
const val CUSTOM_FEX_PRESET = "__custom__"
val syncBackends = listOf(SessionPrefs.SYNC_NTSYNC, SessionPrefs.SYNC_FSYNC, SessionPrefs.SYNC_ESYNC, SessionPrefs.SYNC_WINESERVER)
val syncKeys = listOf("BL_SYNC", "BL_FSYNC_FIRST", "BL_SYNC_FALLBACK", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
fun syncEnvironment(backend: String): Map<String, String> {
require(backend in syncBackends) { "unknown sync $backend" }
return buildMap {
put("BL_SYNC", if (backend == SessionPrefs.SYNC_NTSYNC) "1" else "0")
put("BL_FSYNC_FIRST", if (backend == SessionPrefs.SYNC_FSYNC) "1" else "0")
put("BL_SYNC_FALLBACK", if (backend == SessionPrefs.SYNC_WINESERVER) "0" else "1")
if (backend == SessionPrefs.SYNC_FSYNC) put("PROTON_NO_ESYNC", "1")
}
}
fun gameSync(config: Config, scope: String): String? {
require(scope.isNotEmpty() && validScope(scope))
val entries = config.games[scope].orEmpty().filterKeys { it in syncKeys }
if (entries.isEmpty()) return null
return syncBackends.firstOrNull { entries == syncEnvironment(it) } ?: CUSTOM_SYNC
}
fun withGameSync(config: Config, scope: String, backend: String?): Config {
require(scope.isNotEmpty() && validScope(scope))
val entries = config.entries(scope).filterKeys { it !in syncKeys }.toMutableMap()
if (backend != null) entries += syncEnvironment(backend)
return config.withEntries(scope, entries)
}
const val CUSTOM_SYNC = "__custom__"
}
@@ -6,6 +6,7 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import java.io.File
@@ -296,13 +297,16 @@ object AddedGames {
private fun scanGame(context: Context, folder: File, out: MutableList<Game>, single: AddedExes.Entry? = null) {
run {
val sidecar = StoreGameSidecar.read(folder)
sidecar?.takeIf { it.id.isNotEmpty() }?.let { SessionPrefs.followStoreGame(context, "${it.store.id}:${it.id}", folder.path) { old -> !File(old).exists() } }
val ranking = rank(folder)
val candidates = ranking.exes
val picked = SessionPrefs.addedGameExe(context, folder.path)
val chosen = picked.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
?: single?.takeIf { it.picked }?.let { File(it.exe) }?.takeIf { it.isFile }
val found = chosen ?: sidecar?.exeFile(folder)?.takeIf { it.isFile } ?: candidates.firstOrNull() ?: return
val launch = if (chosen == null) sidecar?.launcherFile(folder)?.takeIf { it.isFile } ?: found else found
val epicLauncher = sidecar?.takeIf { it.store == Store.EPIC && (chosen == null || canonical(chosen) == canonical(it.exeFile(folder))) }
?.launcherFile(folder)?.takeIf { it.isFile }
val launch = epicLauncher ?: if (chosen == null) sidecar?.launcherFile(folder)?.takeIf { it.isFile } ?: found else found
val foundGuest = guestPath(context, launch)
if (foundGuest == null) { Log.w(TAG, "${folder.name}: the session cannot see ${launch.path}"); return }
val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name
@@ -343,6 +347,9 @@ object AddedGames {
JSONObject(File(config, ".droiddeck-routes.json").readText()).optInt(appId.toString()).takeIf { it > 0 }
}.getOrNull()
fun inSteam(context: Context, appId: Long): Boolean =
accountConfig(File(LinuxRuntime.rootDir(context), "root/.local/share/Steam"))?.let { shortcutRecord(it, appId) } != null
private fun shortcutRecord(config: File, appId: Long): JSONObject? = runCatching {
JSONObject(File(config, ".droiddeck-shortcuts.json").readText()).optJSONObject("games")?.optJSONObject(appId.toString())
}.getOrNull()
@@ -382,7 +389,8 @@ object AddedGames {
}
}
fun writeListing(context: Context, games: List<Game>): File {
fun writeListing(context: Context, games: List<Game>,
extra: List<JSONObject> = listOfNotNull(com.droiddeck.launcher.stores.epic.EpicClient.steamListing(context))): File {
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
val json = StringBuilder("[")
games.forEachIndexed { i, g ->
@@ -399,6 +407,10 @@ object AddedGames {
if (pieces.isNotEmpty()) json.append(",\"art\":{").append(pieces.joinToString(",") { (k, v) -> quote(k) + ":" + quote(v) }).append('}')
json.append('}')
}
extra.forEachIndexed { i, entry ->
if (games.isNotEmpty() || i > 0) json.append(',')
json.append(entry.toString())
}
file.writeText(json.append(']').toString())
return file
}
@@ -24,6 +24,8 @@ object Library {
val profileKey: String get() = if (library == ADDED) java.lang.Integer.toUnsignedString(appId) else appId.toString()
}
const val ADDED = "added"
const val EPIC_LAUNCHER = "epic-launcher"
const val EPIC_LAUNCHER_NAME = "Epic Games Launcher"
const val SOURCE_STEAM = "steam"
class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null)
@@ -192,7 +194,8 @@ object Library {
if (program == com.droiddeck.launcher.runtime.FlatpakManager.LAUNCHER || program == com.droiddeck.launcher.runtime.AppImageManager.LAUNCHER ||
program == com.droiddeck.launcher.runtime.UserApps.SCRIPT_LAUNCHER) {
com.droiddeck.launcher.session.SessionState.programArgs.firstOrNull()?.let { flatpakNames[it] ?: it.substringAfterLast('.') }
} else specs.firstOrNull { it.program == program }?.name
} else com.droiddeck.launcher.session.NoSteamLaunch.nameFor(program, com.droiddeck.launcher.session.SessionState.programArgs)
?: specs.firstOrNull { it.program == program }?.name
val flatpakNames = java.util.concurrent.ConcurrentHashMap<String, String>()
@@ -30,6 +30,7 @@ public final class PadBridge {
KeyEvent.KEYCODE_BUTTON_THUMBL, KeyEvent.KEYCODE_BUTTON_THUMBR,
KeyEvent.KEYCODE_BUTTON_MODE, KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2
};
private static final int[] ROUTED_PASS_THROUGH = {PadState.GUIDE, PadState.QAM, PadState.SELECT};
private static final long QAM_GUIDE_LEAD_MIN_MS = 80;
private static final long QAM_GUIDE_LEAD_MAX_MS = 1500;
private static final int QAM_GUIDE_LEAD_FRAMES = 8;
@@ -54,6 +55,8 @@ public final class PadBridge {
private final Handler mainHandler = new Handler(Looper.getMainLooper());
private boolean open;
private volatile boolean selectSteam;
private TouchRoute touchRoute;
private final PadState routedTouch = new PadState();
private boolean systemGuidePressed;
private boolean systemQamPressed;
private boolean qamChordActive;
@@ -313,26 +316,11 @@ public final class PadBridge {
}
pad.leftX = axis(event, MotionEvent.AXIS_X);
pad.leftY = axis(event, MotionEvent.AXIS_Y);
boolean wiredXboxLayout = device != null
&& ((device.getVendorId() == 0x20d6 && device.getProductId() == 0x2063)
|| (device.getVendorId() == 0x0e6f && device.getProductId() == 0x02f0))
&& device.getMotionRange(MotionEvent.AXIS_RX, event.getSource()) != null
&& device.getMotionRange(MotionEvent.AXIS_RY, event.getSource()) != null
&& device.getMotionRange(MotionEvent.AXIS_Z, event.getSource()) != null
&& device.getMotionRange(MotionEvent.AXIS_RZ, event.getSource()) != null;
pad.rightX = axis(event, wiredXboxLayout ? MotionEvent.AXIS_RX : MotionEvent.AXIS_Z);
pad.rightY = axis(event, wiredXboxLayout ? MotionEvent.AXIS_RY : MotionEvent.AXIS_RZ);
float lt;
float rt;
if (wiredXboxLayout) {
lt = Math.max(0f, Math.min(1f, (event.getAxisValue(MotionEvent.AXIS_Z) + 1f) / 2f));
rt = Math.max(0f, Math.min(1f, (event.getAxisValue(MotionEvent.AXIS_RZ) + 1f) / 2f));
} else {
lt = event.getAxisValue(MotionEvent.AXIS_LTRIGGER);
rt = event.getAxisValue(MotionEvent.AXIS_RTRIGGER);
if (lt == 0f) lt = event.getAxisValue(MotionEvent.AXIS_BRAKE);
if (rt == 0f) rt = event.getAxisValue(MotionEvent.AXIS_GAS);
}
boolean wired = wiredXboxLayout(event);
pad.rightX = rightX(event, wired);
pad.rightY = rightY(event, wired);
float lt = leftTrigger(event, wired);
float rt = rightTrigger(event, wired);
pad.leftTrigger = lt;
pad.rightTrigger = rt;
float hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X);
@@ -349,7 +337,36 @@ public final class PadBridge {
return true;
}
public interface TouchRoute {
boolean active();
void accept(PadState state);
}
public synchronized void setTouchRoute(TouchRoute route) {
touchRoute = route;
routedTouch.clear();
}
public synchronized void applyTouch(java.util.function.Consumer<PadState> mutation) {
if (touchRoute != null && touchRoute.active()) {
mutation.accept(routedTouch);
touchRoute.accept(routedTouch);
boolean changed = false;
for (int button : ROUTED_PASS_THROUGH) {
boolean down = routedTouch.isDown(button);
if (state.isDown(button) == down) continue;
state.press(button, down);
changed = true;
}
if (changed) {
activeControllerId = NO_CONTROLLER;
slotControllers.set(0, NO_CONTROLLER);
publish();
}
return;
}
routedTouch.clear();
mutation.accept(state);
activeControllerId = NO_CONTROLLER;
slotControllers.set(0, NO_CONTROLLER);
@@ -380,6 +397,7 @@ public final class PadBridge {
}
public synchronized void releaseAll() {
routedTouch.clear();
releaseBackPaddles();
state.clear();
publish();
@@ -607,6 +625,37 @@ public final class PadBridge {
writer.writePad(effectiveState);
}
public static boolean wiredXboxLayout(MotionEvent event) {
InputDevice device = event.getDevice();
return device != null
&& ((device.getVendorId() == 0x20d6 && device.getProductId() == 0x2063)
|| (device.getVendorId() == 0x0e6f && device.getProductId() == 0x02f0))
&& device.getMotionRange(MotionEvent.AXIS_RX, event.getSource()) != null
&& device.getMotionRange(MotionEvent.AXIS_RY, event.getSource()) != null
&& device.getMotionRange(MotionEvent.AXIS_Z, event.getSource()) != null
&& device.getMotionRange(MotionEvent.AXIS_RZ, event.getSource()) != null;
}
public static float rightX(MotionEvent event, boolean wired) {
return axis(event, wired ? MotionEvent.AXIS_RX : MotionEvent.AXIS_Z);
}
public static float rightY(MotionEvent event, boolean wired) {
return axis(event, wired ? MotionEvent.AXIS_RY : MotionEvent.AXIS_RZ);
}
public static float leftTrigger(MotionEvent event, boolean wired) {
if (wired) return Math.max(0f, Math.min(1f, (event.getAxisValue(MotionEvent.AXIS_Z) + 1f) / 2f));
float value = event.getAxisValue(MotionEvent.AXIS_LTRIGGER);
return value != 0f ? value : event.getAxisValue(MotionEvent.AXIS_BRAKE);
}
public static float rightTrigger(MotionEvent event, boolean wired) {
if (wired) return Math.max(0f, Math.min(1f, (event.getAxisValue(MotionEvent.AXIS_RZ) + 1f) / 2f));
float value = event.getAxisValue(MotionEvent.AXIS_RTRIGGER);
return value != 0f ? value : event.getAxisValue(MotionEvent.AXIS_GAS);
}
private static float axis(MotionEvent event, int axis) {
float value = event.getAxisValue(axis);
return Math.abs(value) < DEAD_ZONE ? 0f : value;
@@ -0,0 +1,358 @@
package com.droiddeck.launcher.input
import android.os.SystemClock
import android.view.Choreographer
import android.view.KeyEvent
import android.view.MotionEvent
import kotlin.math.abs
import kotlin.math.hypot
class PadMouse(private val listener: Listener, private val clock: () -> Long = SystemClock::uptimeMillis) {
interface Listener {
fun active(): Boolean
fun onScrollStart()
fun onScroll(dx: Float, dy: Float)
fun onKey(evdev: Int, pressed: Boolean)
fun onKeyboard()
fun onNavigate()
fun scrollSpeed(): Float
}
private class Sticks {
var leftX = 0f
var leftY = 0f
var rightX = 0f
var rightY = 0f
var leftTrigger = 0f
var rightTrigger = 0f
fun clear() {
leftX = 0f
leftY = 0f
rightX = 0f
rightY = 0f
leftTrigger = 0f
rightTrigger = 0f
}
}
private val choreographer = Choreographer.getInstance()
private val physical = HashMap<Int, Sticks>()
private val touch = Sticks()
private val total = Sticks()
private val triggerAxes = HashMap<Int, Boolean>()
private val wiredLayout = HashMap<Int, Boolean>()
private val down = HashMap<Int, MutableSet<Int>>()
private val sent = HashMap<Int, IntArray>()
private val held = LinkedHashMap<Int, Int>()
private var scrolling = false
private var stickDirection = NONE
private var stickRepeatAt = 0L
private var frameAt = 0L
private var running = false
private val frame = object : Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) {
if (!running) return
if (!listener.active()) {
reset()
return
}
val dt = if (frameAt == 0L) 1f / 60f else ((frameTimeNanos - frameAt) / 1e9f).coerceIn(0f, 0.05f)
frameAt = frameTimeNanos
step(dt)
if (moving()) choreographer.postFrameCallback(this) else stop()
}
}
fun onKey(event: KeyEvent): Boolean {
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_L2 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R2) {
if (event.repeatCount == 0 && !hasTriggerAxes(event)) {
val sticks = physical.getOrPut(event.deviceId) { Sticks() }
val value = if (event.action == KeyEvent.ACTION_DOWN) 1f else 0f
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_L2) sticks.leftTrigger = value else sticks.rightTrigger = value
wake()
}
return true
}
val button = BUTTONS[event.keyCode] ?: return false
if (event.repeatCount > 0) return true
when (event.action) {
KeyEvent.ACTION_DOWN -> set(source(event.deviceId, SOURCE_KEYS), button, true)
KeyEvent.ACTION_UP -> set(source(event.deviceId, SOURCE_KEYS), button, false)
}
return true
}
fun onMotion(event: MotionEvent): Boolean {
if (event.actionMasked != MotionEvent.ACTION_MOVE) return true
val sticks = physical.getOrPut(event.deviceId) { Sticks() }
val wired = wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(event) }
sticks.leftX = event.getAxisValue(MotionEvent.AXIS_X)
sticks.leftY = event.getAxisValue(MotionEvent.AXIS_Y)
sticks.rightX = PadBridge.rightX(event, wired)
sticks.rightY = PadBridge.rightY(event, wired)
if (hasTriggerAxes(event)) {
sticks.leftTrigger = PadBridge.leftTrigger(event, wired)
sticks.rightTrigger = PadBridge.rightTrigger(event, wired)
}
val hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X)
val hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y)
val hat = source(event.deviceId, SOURCE_HAT)
set(hat, UP, hatY < -0.5f)
set(hat, DOWN, hatY > 0.5f)
set(hat, LEFT, hatX < -0.5f)
set(hat, RIGHT, hatX > 0.5f)
wake()
return true
}
fun onTouchPad(state: PadState) {
touch.leftX = state.leftX
touch.leftY = state.leftY
touch.rightX = state.rightX
touch.rightY = state.rightY
touch.leftTrigger = state.leftTrigger
touch.rightTrigger = state.rightTrigger
for (button in TOUCH_BUTTONS) {
set(SOURCE_TOUCH, button, state.isDown(button))
}
set(SOURCE_TOUCH, UP, state.up)
set(SOURCE_TOUCH, DOWN, state.down)
set(SOURCE_TOUCH, LEFT, state.left)
set(SOURCE_TOUCH, RIGHT, state.right)
wake()
}
fun reset() {
stop()
physical.clear()
triggerAxes.clear()
wiredLayout.clear()
touch.clear()
down.clear()
sent.clear()
stickDirection = NONE
scrolling = false
held.keys.toList().reversed().forEach { code ->
held.remove(code)
send(code, false)
}
}
internal fun step(dt: Float) {
sum()
val lx = total.leftX
val ly = total.leftY
val held = heldDirection()
val direction = when {
held != NONE -> held
hypot(lx, ly) < STICK_NAVIGATE -> NONE
abs(lx) > abs(ly) -> if (lx > 0) RIGHT else LEFT
else -> if (ly > 0) DOWN else UP
}
val now = clock()
if (direction != stickDirection) {
stickDirection = direction
if (direction != NONE) {
tap(direction)
stickRepeatAt = now + REPEAT_FIRST_MS
}
} else if (direction != NONE && now >= stickRepeatAt) {
tap(direction)
stickRepeatAt = now + REPEAT_MS
}
val gain = gain(total.rightX, total.rightY)
val sx = total.rightX * gain
val triggers = trigger(total.rightTrigger) - trigger(total.leftTrigger)
val vertical = (total.rightY * gain + triggers).coerceIn(-1f, 1f)
if (sx != 0f || vertical != 0f) {
if (!scrolling) {
scrolling = true
listener.onScrollStart()
}
val speed = listener.scrollSpeed() * dt
listener.onScroll(sx * speed, vertical * speed)
} else if (scrolling) {
scrolling = false
press(KEY_SETTLE)
release(KEY_SETTLE)
}
}
private fun set(source: Int, button: Int, pressed: Boolean) {
val sources = down.getOrPut(button) { HashSet() }
val was = sources.isNotEmpty()
if (pressed) sources.add(source) else sources.remove(source)
val now = sources.isNotEmpty()
if (was == now) return
if (button in DIRECTIONS) {
if (now) step(0f)
wake()
return
}
if (now) {
if (button == PadState.Y) {
listener.onKeyboard()
return
}
val codes = codesFor(button)
sent[button] = codes
codes.forEach { press(it) }
} else {
sent.remove(button)?.reversed()?.forEach { release(it) }
}
}
private fun hasTriggerAxes(event: android.view.InputEvent): Boolean = triggerAxes.getOrPut(event.deviceId) {
val device = event.device ?: return@getOrPut true
device.getMotionRange(MotionEvent.AXIS_LTRIGGER) != null || device.getMotionRange(MotionEvent.AXIS_BRAKE) != null ||
(event is MotionEvent && wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(event) })
}
private fun heldDirection(): Int {
for (direction in DIRECTIONS) if (down[direction]?.isNotEmpty() == true) return direction
return NONE
}
private fun sum() {
total.leftX = touch.leftX
total.leftY = touch.leftY
total.rightX = touch.rightX
total.rightY = touch.rightY
total.leftTrigger = touch.leftTrigger
total.rightTrigger = touch.rightTrigger
for (sticks in physical.values) {
total.leftX += sticks.leftX
total.leftY += sticks.leftY
total.rightX += sticks.rightX
total.rightY += sticks.rightY
total.leftTrigger += sticks.leftTrigger
total.rightTrigger += sticks.rightTrigger
}
}
private fun tap(direction: Int) {
listener.onNavigate()
val codes = codesFor(direction)
codes.forEach { press(it) }
codes.reversed().forEach { release(it) }
}
private fun codesFor(button: Int): IntArray = when (button) {
PadState.A -> intArrayOf(KEY_ENTER)
PadState.X -> intArrayOf(KEY_MENU)
PadState.B -> intArrayOf(KEY_ESC, KEY_BACK)
PadState.START -> intArrayOf(KEY_ENTER)
PadState.LB -> intArrayOf(KEY_LEFTCTRL, KEY_PAGEUP)
PadState.RB -> intArrayOf(KEY_LEFTCTRL, KEY_PAGEDOWN)
UP -> intArrayOf(KEY_UP)
DOWN -> intArrayOf(KEY_DOWN)
LEFT -> intArrayOf(KEY_LEFT)
RIGHT -> intArrayOf(KEY_RIGHT)
else -> IntArray(0)
}
private fun wake() {
if (moving() && !running) {
running = true
frameAt = 0L
choreographer.postFrameCallback(frame)
}
}
private fun moving(): Boolean {
if (heldDirection() != NONE || stickDirection != NONE || scrolling) return true
sum()
return hypot(total.leftX, total.leftY) >= STICK_NAVIGATE || gain(total.rightX, total.rightY) != 0f ||
trigger(total.leftTrigger) != 0f || trigger(total.rightTrigger) != 0f
}
private fun stop() {
running = false
frameAt = 0L
choreographer.removeFrameCallback(frame)
}
private fun press(code: Int) {
val count = held[code] ?: 0
held[code] = count + 1
if (count == 0) send(code, true)
}
private fun release(code: Int) {
val count = held[code] ?: return
if (count > 1) {
held[code] = count - 1
return
}
held.remove(code)
send(code, false)
}
private fun send(code: Int, pressed: Boolean) {
listener.onKey(code, pressed)
}
companion object {
private const val DEAD_ZONE = 0.15f
private const val STICK_NAVIGATE = 0.5f
private const val REPEAT_FIRST_MS = 300L
private const val REPEAT_MS = 120L
private const val SOURCE_KEYS = 0
private const val SOURCE_HAT = 1
private const val SOURCE_TOUCH = Int.MIN_VALUE
private const val NONE = -1
private const val UP = 100
private const val DOWN = 101
private const val LEFT = 102
private const val RIGHT = 103
private val DIRECTIONS = intArrayOf(UP, DOWN, LEFT, RIGHT)
private val TOUCH_BUTTONS = intArrayOf(PadState.A, PadState.B, PadState.X, PadState.Y, PadState.LB, PadState.RB, PadState.START)
private const val KEY_ESC = 1
private const val KEY_ENTER = 28
private const val KEY_UP = 103
private const val KEY_LEFT = 105
private const val KEY_RIGHT = 106
private const val KEY_DOWN = 108
private const val KEY_BACK = 158
private const val KEY_LEFTCTRL = 29
private const val KEY_PAGEUP = 104
private const val KEY_PAGEDOWN = 109
private const val KEY_MENU = 127
private const val KEY_SETTLE = 183
private val BUTTONS = mapOf(
KeyEvent.KEYCODE_BUTTON_A to PadState.A,
KeyEvent.KEYCODE_BUTTON_B to PadState.B,
KeyEvent.KEYCODE_BUTTON_X to PadState.X,
KeyEvent.KEYCODE_BUTTON_Y to PadState.Y,
KeyEvent.KEYCODE_BUTTON_L1 to PadState.LB,
KeyEvent.KEYCODE_BUTTON_R1 to PadState.RB,
KeyEvent.KEYCODE_BUTTON_START to PadState.START,
KeyEvent.KEYCODE_DPAD_UP to UP,
KeyEvent.KEYCODE_DPAD_DOWN to DOWN,
KeyEvent.KEYCODE_DPAD_LEFT to LEFT,
KeyEvent.KEYCODE_DPAD_RIGHT to RIGHT,
)
internal fun curve(x: Float, y: Float): Pair<Float, Float> {
val gain = gain(x, y)
return x * gain to y * gain
}
private fun gain(x: Float, y: Float): Float {
val length = hypot(x, y)
if (length <= DEAD_ZONE) return 0f
val scaled = (length.coerceAtMost(1f) - DEAD_ZONE) / (1f - DEAD_ZONE)
return scaled * scaled / length
}
private fun source(deviceId: Int, kind: Int): Int = deviceId * 2 + kind
private fun trigger(value: Float): Float =
if (value <= DEAD_ZONE) 0f else (value.coerceAtMost(1f) - DEAD_ZONE) / (1f - DEAD_ZONE)
}
}
@@ -0,0 +1,190 @@
package com.droiddeck.launcher.input
import android.os.Handler
import android.os.Looper
import android.view.Choreographer
import android.view.MotionEvent
import android.view.VelocityTracker
import kotlin.math.abs
import kotlin.math.exp
import kotlin.math.floor
import kotlin.math.hypot
import kotlin.math.pow
class ScrollTouchGestures(
private val slopPx: Float,
private val minFlingPx: Float,
private val listener: Listener,
) {
interface Listener {
fun onMove(x: Float, y: Float)
fun onButton(button: Int, pressed: Boolean)
fun onScroll(dx: Float, dy: Float)
fun onLongPress()
}
private val handler = Handler(Looper.getMainLooper())
private val choreographer = Choreographer.getInstance()
private var tracker: VelocityTracker? = null
private var pointerId = -1
private var startX = 0f
private var startY = 0f
private var lastX = 0f
private var lastY = 0f
private var movedAt = 0L
private var scrolling = false
private var vertical = true
private var held = false
private var dragging = false
private var stoppedFling = false
private var clicked = 0
private var flingX = 0f
private var flingY = 0f
private var flingAt = 0L
private var flinging = false
private val longPress = Runnable {
held = true
listener.onLongPress()
}
private val clickUp = Runnable { releaseClick() }
private val flingFrame = object : Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) {
if (!flinging) return
val dt = if (flingAt == 0L) 1f / 60f else ((frameTimeNanos - flingAt) / 1e9f).coerceIn(0f, 0.05f)
flingAt = frameTimeNanos
val decay = exp(-dt / FLING_TIME_S)
listener.onScroll(flingX * dt, flingY * dt)
flingX *= decay
flingY *= decay
if (hypot(flingX, flingY) < FLING_STOP_PX) flinging = false else choreographer.postFrameCallback(this)
}
}
fun cancel() {
handler.removeCallbacks(longPress)
stopFling()
releaseClick()
if (dragging) listener.onButton(PointerGestures.BTN_LEFT, false)
dragging = false
held = false
scrolling = false
pointerId = -1
tracker?.recycle()
tracker = null
}
fun onTouch(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
stoppedFling = flinging
cancel()
pointerId = event.getPointerId(0)
startX = event.x
startY = event.y
lastX = startX
lastY = startY
tracker = VelocityTracker.obtain().also { it.addMovement(event) }
listener.onMove(startX, startY)
handler.postDelayed(longPress, HOLD_MS)
}
MotionEvent.ACTION_MOVE -> {
val index = event.findPointerIndex(pointerId).takeIf { it >= 0 } ?: return true
tracker?.addMovement(event)
val x = event.getX(index)
val y = event.getY(index)
if (!scrolling && !dragging && hypot(x - startX, y - startY) > slopPx) {
handler.removeCallbacks(longPress)
if (held) {
dragging = true
listener.onButton(PointerGestures.BTN_LEFT, true)
} else {
scrolling = true
vertical = abs(y - startY) >= abs(x - startX)
lastX = startX
lastY = startY
}
}
if (dragging) listener.onMove(x, y)
follow(event, x, y)
}
MotionEvent.ACTION_POINTER_UP -> {
if (event.getPointerId(event.actionIndex) == pointerId) cancel()
}
MotionEvent.ACTION_UP -> {
handler.removeCallbacks(longPress)
if (pointerId == -1 || event.getPointerId(0) != pointerId) return true
tracker?.addMovement(event)
follow(event, event.x, event.y)
when {
scrolling -> tracker?.takeIf { event.eventTime - movedAt <= FLING_STILL_MS }?.let { t ->
t.computeCurrentVelocity(1000)
val vx = if (vertical) 0f else -t.getXVelocity(pointerId)
val vy = if (vertical) -t.getYVelocity(pointerId) else 0f
if (hypot(vx, vy) >= minFlingPx) startFling(vx, vy)
}
dragging -> listener.onButton(PointerGestures.BTN_LEFT, false)
held -> click(PointerGestures.BTN_RIGHT)
!stoppedFling -> click(PointerGestures.BTN_LEFT)
}
dragging = false
held = false
scrolling = false
pointerId = -1
tracker?.recycle()
tracker = null
}
MotionEvent.ACTION_CANCEL -> cancel()
}
return true
}
private fun follow(event: MotionEvent, x: Float, y: Float) {
if (!scrolling || (x == lastX && y == lastY)) return
movedAt = event.eventTime
if (vertical) listener.onScroll(0f, lastY - y) else listener.onScroll(lastX - x, 0f)
lastX = x
lastY = y
}
private fun click(button: Int) {
releaseClick()
listener.onButton(button, true)
clicked = button
handler.postDelayed(clickUp, CLICK_MS)
}
private fun releaseClick() {
handler.removeCallbacks(clickUp)
if (clicked != 0) listener.onButton(clicked, false)
clicked = 0
}
private fun startFling(vx: Float, vy: Float) {
flingX = vx
flingY = vy
flingAt = 0L
flinging = true
choreographer.postFrameCallback(flingFrame)
}
private fun stopFling() {
flinging = false
choreographer.removeFrameCallback(flingFrame)
}
companion object {
fun wheelUnits(pixels: Int, viewSize: Int): Int {
if (pixels == 0) return 0
val step = floor(viewSize.toDouble().pow(2.0 / 3.0)).coerceAtLeast(1.0)
val units = (abs(pixels) * 120.0 / step).toInt() + 1
return if (pixels < 0) -units else units
}
private const val HOLD_MS = 500L
private const val CLICK_MS = 50L
private const val FLING_TIME_S = 0.45f
private const val FLING_STOP_PX = 40f
private const val FLING_STILL_MS = 60L
}
}
@@ -12,7 +12,7 @@ import java.nio.file.attribute.BasicFileAttributes;
import java.util.function.LongConsumer;
import java.util.function.Predicate;
final class RuntimeFileTree {
public final class RuntimeFileTree {
private RuntimeFileTree() {}
static volatile Predicate<Path> refuseForTest;
@@ -35,7 +35,7 @@ final class RuntimeFileTree {
if (progress != null) progress.accept(++removed[0]);
}
static boolean deleteWhatCan(File root, LongConsumer progress) {
public static boolean deleteWhatCan(File root, LongConsumer progress) {
return deleteWhatCan(root.toPath(), progress, new long[]{0});
}
@@ -64,6 +64,13 @@ object GameEnvironmentStore {
return config
}
@Synchronized
fun setGameSync(context: Context, scope: String, backend: String?): GameEnvironment.Config {
val config = GameEnvironment.withGameSync(read(context), scope, backend)
save(context, config)
return config
}
@Synchronized
fun setGameNoSteam(context: Context, scope: String, on: Boolean): GameEnvironment.Config {
val config = GameEnvironment.withGameNoSteam(read(context), scope, on)
@@ -0,0 +1,62 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.stores.epic.EpicClient
object NoSteamLaunch {
const val PROTON_RUN = "/usr/local/bin/droiddeck-proton-run"
const val EPIC = "/usr/local/bin/droiddeck-epic"
class Command(val program: String, val args: List<String>, val name: String)
fun scope(game: Library.SteamGame): String? = when {
game.library == Library.EPIC_LAUNCHER -> EpicClient.shortcutAppId.toString()
game.library == Library.ADDED || game.appId > 0 -> game.profileKey
else -> null
}?.takeIf { it.isNotEmpty() && GameEnvironment.validScope(it) }
fun enabled(config: GameEnvironment.Config, game: Library.SteamGame): Boolean =
scope(game)?.let { GameEnvironment.gameNoSteam(config, it) } == true
fun enabled(context: Context, game: Library.SteamGame): Boolean =
scope(game) != null && runCatching { enabled(GameEnvironmentStore.read(context), game) }.getOrDefault(false)
fun enabled(context: Context, appId: Long): Boolean = runCatching {
GameEnvironment.gameNoSteam(GameEnvironmentStore.read(context), (appId and 0xFFFFFFFFL).toString())
}.getOrDefault(false)
fun command(game: Library.SteamGame, added: AddedGames.Game?): Command? = when {
game.library == Library.EPIC_LAUNCHER -> Command(EPIC, listOf("run"), game.name)
game.library == Library.ADDED -> added?.let { a -> a.steamAppId?.let { Command(PROTON_RUN, listOf("--app", it.toString()), a.name) } ?: addedCommand(a) }
game.appId > 0 -> Command(PROTON_RUN, listOf("--app", game.appId.toString()), game.name)
else -> null
}
fun addedCommand(game: AddedGames.Game): Command = Command(
PROTON_RUN,
listOf("--app", (game.appId and 0xFFFFFFFFL).toString(), "--dir", game.guestDir, "--options", game.launchOptions, "--", game.guestExe),
game.name,
)
fun settingsId(game: AddedGames.Game): Long = (game.steamAppId?.toLong() ?: game.appId) and 0xFFFFFFFFL
fun addedGame(context: Context, game: Library.SteamGame): AddedGames.Game? {
val id = game.appId.toLong() and 0xFFFFFFFFL
return AddedGames.scan(context).firstOrNull { settingsId(it) == id }
}
fun nameFor(program: String?, args: List<String>): String? = when (program) {
EPIC -> Library.EPIC_LAUNCHER_NAME
PROTON_RUN -> args.getOrNull(args.indexOf("--app") + 1)?.takeIf { args.contains("--app") }?.let { names[it] }
else -> null
}
val names = java.util.concurrent.ConcurrentHashMap<String, String>()
fun remember(command: Command) {
if (command.program == PROTON_RUN) command.args.getOrNull(command.args.indexOf("--app") + 1)?.let { names[it] = command.name }
}
}
@@ -67,6 +67,8 @@ object SessionFiles {
"usr/local/bin/droiddeck-steam-shim" to "usr/local/bin/droiddeck-steam-shim",
"usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts",
"usr/local/bin/droiddeck-store-launch" to "usr/local/bin/droiddeck-store-launch",
"usr/local/bin/droiddeck-epic" to "usr/local/bin/droiddeck-epic",
"usr/local/bin/droiddeck-epic-steam" to "usr/local/bin/droiddeck-epic-steam",
"usr/local/bin/droiddeck-open-url" to "usr/local/bin/droiddeck-open-url",
"usr/local/bin/droiddeck-steam-games" to "usr/local/bin/droiddeck-steam-games",
"usr/local/bin/droiddeck-pad-defaults" to "usr/local/bin/droiddeck-pad-defaults",
@@ -121,7 +123,7 @@ object SessionFiles {
"usr/share/vulkan/implicit_layer.d/droiddeck_vr.json")
val fexPreloads = listOf("x86_64", "i386").flatMap { arch ->
listOf("libblsession.so", "libfakeinput.so", "libfaultreport.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" }
} + listOf("libthunkaudit.so", "libvulkan-thunk.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" }
} + listOf("libthunkaudit.so", "libvulkan-thunk.so", "libwebkitinput.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" }
val optional = (arrayOf(
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
@@ -610,6 +610,36 @@ object SessionPrefs {
fun addedGameStoredAppId(context: Context, folderPath: String): Long? =
prefs(context).getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L }
fun followStoreGame(context: Context, key: String, folderPath: String, gone: (String) -> Boolean) = synchronized(addedGameLock) {
val p = prefs(context)
val previous = p.getString("storeFolder:$key", null)
if (previous == folderPath) return@synchronized
if (previous != null && !gone(previous)) return@synchronized
val edit = p.edit().putString("storeFolder:$key", folderPath)
if (previous != null && !p.contains("addedAppId:$folderPath")) {
val moved = movedAddedGame(p.all, previous, folderPath)
moved.keys.forEach { edit.remove(it) }
moved.values.forEach { (name, value) ->
when (value) {
is String -> edit.putString(name, value)
is Long -> edit.putLong(name, value)
is Int -> edit.putInt(name, value)
is Boolean -> edit.putBoolean(name, value)
is Float -> edit.putFloat(name, value)
}
}
val removed = removedAddedGames(context)
if (previous in removed) edit.putString("removedAddedGames", removed.map { if (it == previous) folderPath else it }.joinToString("\n"))
}
edit.apply()
}
internal fun movedAddedGame(all: Map<String, *>, from: String, to: String): Map<String, Pair<String, Any?>> =
all.filterKeys { it.startsWith("added") && it.endsWith(":$from") }.mapValues { (name, value) ->
val moved = if (value is String && (value == from || value.startsWith("$from/"))) to + value.removePrefix(from) else value
name.removeSuffix(from) + to to moved
}
fun addedGameAppId(context: Context, folderPath: String, first: Long): Long = synchronized(addedGameLock) {
val p = prefs(context)
p.getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L }
@@ -72,7 +72,8 @@ class SessionService : Service() {
private var steamDownloadsInBackground = false
private var activityVisible = true
private var xrActivityVisible = false
private val hasVisibleSurface get() = sessionHasVisibleSurface(activityVisible, screenOn, xrActivityVisible)
private var signInHold = false
private val hasVisibleSurface get() = sessionHasVisibleSurface(activityVisible || signInHold, screenOn, xrActivityVisible)
private var screenOn = true
private var manualPauseRequested = false
private var steamSleepToken: String? = null
@@ -183,6 +184,15 @@ class SessionService : Service() {
updateSuspendPolicy()
return START_NOT_STICKY
}
ACTION_SIGN_IN_HOLD -> {
val hold = intent?.getBooleanExtra(EXTRA_HOLD, false) == true
if (hold == signInHold) return START_NOT_STICKY
signInHold = hold
if (hold) manualPauseRequested = false
suspendAttemptFailed = false
updateSuspendPolicy()
return START_NOT_STICKY
}
ACTION_SUSPEND_POLICY_CHANGED -> {
if (!SessionState.running) return START_NOT_STICKY
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
@@ -219,6 +229,7 @@ class SessionService : Service() {
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
activityVisible = true
xrActivityVisible = false
signInHold = false
screenOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: true
manualPauseRequested = false
suspendDownloadNow = false
@@ -325,6 +336,7 @@ class SessionService : Service() {
.onFailure { Log.w(TAG, "forced components", it) }
}
addClientEnvironment(guest, steamHere)
if (steamHere) guest.add("BL_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId)
val fastPathAt = guest.size
val pulse = startAudio(guest, sessionDir)
@@ -350,7 +362,15 @@ class SessionService : Service() {
addControllerEnvironment(guest, fakeInputDir, sessionDir)
SessionState.padBridge?.syncConnectedControllers()
}
if (steamHere) {
val noSteamGame = noSteamGame()
if (noSteamGame) guest.add("BL_PIN_CORES=0")
if ((steamHere || SessionState.program == NoSteamLaunch.EPIC) && com.droiddeck.launcher.stores.epic.EpicClient.read(this).installed) {
runCatching { com.droiddeck.launcher.stores.epic.EpicClientLibrary.sync(this) }
.onFailure { Log.w(TAG, "Epic library sync failed", it) }
runCatching { com.droiddeck.launcher.stores.epic.EpicClient.prepareInstallDir(this) }
.onFailure { Log.w(TAG, "Epic install directory setup failed", it) }
}
if (steamHere || noSteamGame) {
val added = com.droiddeck.launcher.frontend.AddedGames.scan(this)
val listing = com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added)
guest.add("BL_ADDED_GAMES=" + listing.path)
@@ -457,8 +477,9 @@ class SessionService : Service() {
Log.i(TAG, "an earlier session's process ended ($status); the current one carries on")
return@start
}
Log.i(TAG, "session ended: $status")
stopSession(status ?: -1)
val program = programStatus(sessionRoot)
Log.i(TAG, "session ended: $status" + if (program != null) " (program $program)" else "")
stopSession(program ?: status ?: -1)
}, null)
Log.i(TAG, "session pid $pid, log ${sessionLog.path}")
if (gen != sessionGen || !SessionState.running) {
@@ -579,8 +600,11 @@ class SessionService : Service() {
.takeIf { it.isNotEmpty() }?.let { guest.add("BL_GAME_CPUS=$it") }
}
private fun noSteamGame(): Boolean =
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC)
private fun startAudio(guest: MutableList<String>, sessionDir: File): PulseAudioComponent {
val wantsDirectAudio = (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) &&
val wantsDirectAudio = (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || noSteamGame()) &&
SessionPrefs.directAudio(this)
val wantsMic = SessionPrefs.micEnabled(this) &&
checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
@@ -1005,10 +1029,15 @@ class SessionService : Service() {
private var launchWatcher: android.os.FileObserver? = null
private fun programStatus(dir: File): Int? =
runCatching { File(dir, RUN_STATUS).readText().trim().toInt() }.getOrNull()
private fun watchLaunchRequests(dir: File) {
launchWatcher?.stopWatching()
listOf("steam-sleep", "steam-sleep-state", "steam-sleep-ready", "steam-wake", "steam-wake.tmp",
"steam-native-sleep", "steam-native-sleep.tmp", "steam-native-ready", "steam-native-ready.tmp"
"steam-native-sleep", "steam-native-sleep.tmp", "steam-native-ready", "steam-native-ready.tmp",
RUN_STATUS, "$RUN_STATUS.tmp", "epic-game", "epic-game.tmp", com.droiddeck.launcher.stores.epic.EpicClient.PLAYING,
com.droiddeck.launcher.stores.epic.EpicClient.OPEN, com.droiddeck.launcher.stores.epic.EpicClient.FOCUSED_APP
).forEach { File(dir, it).delete() }
val gen = sessionGen
@Suppress("DEPRECATION")
@@ -1335,6 +1364,7 @@ class SessionService : Service() {
updateDownloadMonitoring()
val stoppedGen = sessionGen
val stoppedSession = SessionState.sessionId
val launcherEnded = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || SessionState.program == NoSteamLaunch.EPIC
SessionState.stopRequested = false
SessionEvents.record("guest.exited", mapOf("status" to status))
GpuClockPin.stop(this)
@@ -1375,15 +1405,25 @@ class SessionService : Service() {
if (prootPid > 1) teardown(prootPid)
killGuestLeftovers()
finishSessionStop(status, stoppedGen)
if (launcherEnded) importLauncherGames()
}, "session-teardown").start()
} else {
Thread({ com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession); finishSessionStop(status, stoppedGen) }, "gog-session-stop").start()
Thread({
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
finishSessionStop(status, stoppedGen)
if (launcherEnded) importLauncherGames()
}, "gog-session-stop").start()
}
}
if (prootPid > 1) acquireLocks()
if (controller != null) controller.closeAndResume(finishAfterTeardown) else finishAfterTeardown()
}
private fun importLauncherGames() {
runCatching { com.droiddeck.launcher.stores.epic.EpicClientLibrary.importClientGames(this) }
.onFailure { Log.w(TAG, "client library scan failed: ${it.javaClass.simpleName}") }
}
override fun onTaskRemoved(rootIntent: Intent?) {
if (pipTask || xrActivityVisible) {
Log.i(TAG, "panel task dismissed - retaining the session under its active surface policy")
@@ -1590,6 +1630,8 @@ class SessionService : Service() {
private const val ACTION_ACTIVITY_HIDDEN = "com.droiddeck.launcher.ACTIVITY_HIDDEN"
private const val ACTION_XR_ACTIVITY_VISIBLE = "com.droiddeck.launcher.XR_ACTIVITY_VISIBLE"
private const val ACTION_XR_ACTIVITY_HIDDEN = "com.droiddeck.launcher.XR_ACTIVITY_HIDDEN"
private const val ACTION_SIGN_IN_HOLD = "com.droiddeck.launcher.SIGN_IN_HOLD"
private const val EXTRA_HOLD = "hold"
private const val ACTION_TRACK_AUXILIARY = "com.droiddeck.launcher.TRACK_AUXILIARY"
private const val ACTION_STOP_AUXILIARY = "com.droiddeck.launcher.STOP_AUXILIARY"
private const val ACTION_AUXILIARY_EXITED = "com.droiddeck.launcher.AUXILIARY_EXITED"
@@ -1613,6 +1655,7 @@ class SessionService : Service() {
const val MODE_DESKTOP = "lxqt"
const val MODE_RUN = "run"
const val EXTRA_PROGRAM = "program"
private const val RUN_STATUS = "run-status"
const val EXTRA_PROGRAM_ARGS = "programArgs"
const val EXTRA_STEAM_UI = "steamUi"
const val EXTRA_STEAM_URL = "steamUrl"
@@ -1655,6 +1698,11 @@ class SessionService : Service() {
context.startService(Intent(context, SessionService::class.java).setAction(action))
}
fun holdForSignIn(context: Context, hold: Boolean) {
if (!SessionState.running) return
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_SIGN_IN_HOLD).putExtra(EXTRA_HOLD, hold))
}
fun resume(context: Context) {
if (!SessionState.running) return
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_RESUME))
@@ -211,11 +211,14 @@ internal class SessionSuspendController(
}
}
for (record in ordered) send(record, SIGCONT)
repeat(8) {
val waiting = ordered.toMutableList()
repeat(RESTORE_CHECKS) { check ->
Thread.sleep(25L)
if (ordered.all(::isRunningOrGone)) return true
waiting.removeAll { isRunningOrGone(it) }
if (waiting.isEmpty()) return true
if (check % 8 == 7) for (record in waiting) send(record, SIGCONT)
}
return ordered.all(::isRunningOrGone)
return false
}
private fun send(record: ProcessRecord, signal: Int) {
@@ -242,5 +245,6 @@ internal class SessionSuspendController(
private companion object {
const val SIGSTOP = 19
const val SIGCONT = 18
const val RESTORE_CHECKS = 80
}
}
@@ -3,47 +3,34 @@ package com.droiddeck.launcher.stores
import android.content.Context
import android.util.Base64
import android.util.Log
import com.droiddeck.launcher.agent.AgentGuest
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.frontend.LogoPosition
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.json.JSONArray
import org.json.JSONObject
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
import java.io.File
import java.io.InputStream
import java.io.OutputStream
import java.net.HttpURLConnection
import java.net.Socket
import java.net.URL
import java.security.SecureRandom
object SteamLiveShortcuts {
private const val TAG = "SteamLive"
private const val TAG_NAME = "droiddeck-app"
private const val COMPAT_TOOL = "droiddeck-proton-arm64"
private const val EVAL_TIMEOUT_MS = 20_000L
private const val THAW_WAIT_MS = 15_000L
fun sync(context: Context, games: List<AddedGames.Game>, include: (AddedGames.Game) -> Boolean = { it.source != Library.ADDED }) {
val wanted = games.filter(include)
if (wanted.isEmpty() || !clientRunning()) return
val list = JSONArray()
for (g in wanted) list.put(JSONObject().put("name", g.name).put("exe", g.guestExe).put("dir", g.guestDir))
for (g in wanted) list.put(JSONObject().put("name", g.name).put("exe", g.guestExe).put("dir", g.guestDir).put("appid", g.appId and 0xFFFFFFFFL))
val js = """
(async () => {
const want = ${list};
const have = await SteamClient.Apps.GetAllShortcuts();
const strip = s => (s || "").replace(/^"|"$/g, "");
let added = 0;
for (const w of want) {
if (have.some(a => a.data && strip(a.data.strExePath) === w.exe && a.data.strAppName === w.name)) continue;
const id = await SteamClient.Apps.AddShortcut(w.name, w.exe, w.dir, "");
if (!id) continue;
try { SteamClient.Apps.AddUserTagToApps([id], ${JSONObject.quote(TAG_NAME)}); } catch (e) {}
try { SteamClient.Apps.SpecifyCompatTool(id, ${JSONObject.quote(COMPAT_TOOL)}); } catch (e) {}
added++;
if (await ${KNOWN}(w.appid, w.name, w.exe)) continue;
if (await ${ADD}(w.name, w.exe, w.dir, true)) added++;
}
return added;
})()
@@ -53,6 +40,36 @@ object SteamLiveShortcuts {
if (result != "0") StoresState.logLine("Steam: $result shortcut(s) added to the running client")
}
fun ensure(context: Context, name: String, exe: String, dir: String, compat: Boolean, appId: Long? = null): Long? {
if (!awake(THAW_WAIT_MS)) return null
val js = """
(async () => {
const known = await ${KNOWN}(${appId?.and(0xFFFFFFFFL) ?: 0}, ${JSONObject.quote(name)}, ${JSONObject.quote(exe)});
if (known) return known;
return await ${ADD}(${JSONObject.quote(name)}, ${JSONObject.quote(exe)}, ${JSONObject.quote(dir)}, $compat);
})()
""".trimIndent()
val id = evaluate(context, js)?.toLongOrNull()?.and(0xFFFFFFFFL)?.takeIf { it != 0L } ?: return null
Log.i(TAG, "live shortcuts: $name is $id")
return id
}
fun known(context: Context, appId: Long): Boolean? {
if (!clientRunning()) return null
val js = """
(() => {
const store = globalThis.appStore;
if (typeof store?.GetAppOverviewByAppID !== 'function' || !store.m_bIsInitialized) return 'unknown';
return store.GetAppOverviewByAppID(${appId and 0xFFFFFFFFL}) != null ? 'yes' : 'no';
})()
""".trimIndent()
return when (evaluate(context, js)) {
"yes" -> true
"no" -> false
else -> null
}
}
fun remove(context: Context, appId: Long) {
if (!clientRunning()) return
val result = evaluate(context, "(async () => { await SteamClient.Apps.RemoveShortcut(${appId and 0xFFFFFFFFL}); return 1; })()")
@@ -100,114 +117,60 @@ object SteamLiveShortcuts {
if (evaluate(context, js) != null) Log.i(TAG, "live shortcuts: logo position for $id")
}
private fun clientRunning(): Boolean = SessionState.running && SessionState.mode == SessionService.MODE_STEAM && !SessionState.stopRequested
private fun clientRunning(): Boolean =
SessionState.running && SessionState.mode == SessionService.MODE_STEAM && !SessionState.stopRequested && !SessionState.suspended
private fun awake(waitMs: Long): Boolean {
val end = android.os.SystemClock.uptimeMillis() + waitMs
while (SessionState.running && SessionState.suspended && android.os.SystemClock.uptimeMillis() < end) Thread.sleep(100)
return clientRunning()
}
private fun evaluate(context: Context, expression: String): String? {
val portFile = File(LinuxRuntime.sessionRoot(context), "agent/cdp-port")
val port = runCatching { portFile.readText().trim().toInt() }.getOrNull() ?: return null
val targets = runCatching { JSONArray(get("http://127.0.0.1:$port/json")) }.getOrNull() ?: return null
var wsUrl: String? = null
for (i in 0 until targets.length()) {
val t = targets.optJSONObject(i) ?: continue
if (t.optString("title").contains("SharedJSContext") || t.optString("url").contains("SharedJSContext")) { wsUrl = t.optString("webSocketDebuggerUrl").ifEmpty { null }; break }
}
if (wsUrl == null) { Log.w(TAG, "no SharedJSContext target"); return null }
return try {
WebSocket(wsUrl, 8000).use { ws ->
ws.sendText(JSONObject().put("id", 1).put("method", "Runtime.evaluate").put("params", JSONObject()
.put("expression", expression).put("returnByValue", true).put("awaitPromise", true).put("userGesture", true)).toString())
val deadline = System.currentTimeMillis() + 15_000
while (System.currentTimeMillis() < deadline) {
val message = JSONObject(ws.receiveText() ?: return null)
if (message.optInt("id") != 1) continue
if (message.has("error")) { Log.w(TAG, "cdp: ${message.optJSONObject("error")}"); return null }
val result = message.optJSONObject("result") ?: return null
result.optJSONObject("exceptionDetails")?.let { Log.w(TAG, "js: ${it.optJSONObject("exception")?.optString("description") ?: it.optString("text")}"); return null }
return result.optJSONObject("result")?.opt("value")?.toString()
}
null
}
val answer = try {
AgentGuest.steamEval(context, expression, EVAL_TIMEOUT_MS)
} catch (e: Exception) {
Log.w(TAG, "cdp: ${e.javaClass.simpleName}: ${e.message}")
null
return null
}
if (!answer.optBoolean("ok")) {
Log.w(TAG, "cdp: ${answer.optJSONObject("error")?.optString("message")}")
return null
}
return answer.opt("value")?.takeIf { it != JSONObject.NULL }?.toString()
}
private fun get(url: String): String {
val c = URL(url).openConnection() as HttpURLConnection
c.connectTimeout = 3000; c.readTimeout = 3000
try { return c.inputStream.bufferedReader().readText() } finally { c.disconnect() }
}
private val KNOWN = """(async (appid, name, exe) => {
const store = globalThis.appStore;
if (typeof store?.GetAppOverviewByAppID !== 'function' || !store.m_bIsInitialized) throw new Error("appStore is not ready");
const byId = appid ? store.GetAppOverviewByAppID(appid) : null;
if (byId) return byId.appid;
const strip = s => (s || "").replace(/^"|"$/g, "");
const details = id => new Promise(done => {
let handle = null, answer;
const finish = d => { clearTimeout(timer); try { handle?.unregister(); } catch (e) {} done(d); };
const timer = setTimeout(() => finish(null), 4000);
handle = SteamClient.Apps.RegisterForAppDetails(id, d => { answer = d; if (handle) finish(d); });
if (answer !== undefined) finish(answer);
});
for (const a of store.allApps.filter(a => a.app_type == 1073741824 && a.display_name === name)) {
const d = await details(a.appid);
if (!d) throw new Error("no details for shortcut " + a.appid);
if (strip(d.strShortcutExe) === strip(exe)) return a.appid;
}
return 0;
})"""
private class WebSocket(url: String, timeoutMs: Int) : AutoCloseable {
private val socket: Socket
private val out: OutputStream
private val input: DataInputStream
init {
val u = URL(url.replaceFirst("ws://", "http://"))
socket = Socket(u.host, if (u.port > 0) u.port else 80).apply { soTimeout = timeoutMs }
out = socket.getOutputStream()
input = DataInputStream(socket.getInputStream())
val key = ByteArray(16).also { SecureRandom().nextBytes(it) }
val path = u.path.ifEmpty { "/" } + (u.query?.let { "?$it" } ?: "")
out.write(("GET $path HTTP/1.1\r\nHost: ${u.host}:${u.port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" +
"Sec-WebSocket-Key: ${Base64.encodeToString(key, Base64.NO_WRAP)}\r\nSec-WebSocket-Version: 13\r\n\r\n").toByteArray())
out.flush()
val status = readLine(input) ?: throw java.io.IOException("no upgrade response")
if (!status.contains(" 101 ")) throw java.io.IOException("upgrade refused: $status")
while (true) { val line = readLine(input) ?: break; if (line.isEmpty()) break }
}
private fun readLine(s: InputStream): String? {
val buf = ByteArrayOutputStream()
while (true) {
val b = s.read()
if (b < 0) return if (buf.size() == 0) null else buf.toString("UTF-8")
if (b == '\n'.code) return buf.toString("UTF-8").trimEnd('\r')
buf.write(b)
}
}
fun sendText(text: String) {
val payload = text.toByteArray()
val mask = ByteArray(4).also { SecureRandom().nextBytes(it) }
val frame = ByteArrayOutputStream()
frame.write(0x81)
when {
payload.size < 126 -> frame.write(0x80 or payload.size)
payload.size < 65536 -> { frame.write(0x80 or 126); frame.write(payload.size ushr 8); frame.write(payload.size and 0xFF) }
else -> { frame.write(0x80 or 127); for (i in 7 downTo 0) frame.write(((payload.size.toLong() ushr (8 * i)) and 0xFF).toInt()) }
}
frame.write(mask)
for (i in payload.indices) frame.write((payload[i].toInt() xor mask[i % 4].toInt()) and 0xFF)
out.write(frame.toByteArray()); out.flush()
}
fun receiveText(): String? {
val message = ByteArrayOutputStream()
while (true) {
val b0 = input.read(); if (b0 < 0) return null
val b1 = input.read(); if (b1 < 0) return null
val fin = b0 and 0x80 != 0
val opcode = b0 and 0x0F
var len = (b1 and 0x7F).toLong()
if (len == 126L) len = input.readUnsignedShort().toLong()
else if (len == 127L) len = input.readLong()
val masked = b1 and 0x80 != 0
val mask = if (masked) ByteArray(4).also { input.readFully(it) } else null
if (len > 16L * 1024 * 1024) throw java.io.IOException("frame too large")
val data = ByteArray(len.toInt()).also { input.readFully(it) }
if (mask != null) for (i in data.indices) data[i] = (data[i].toInt() xor mask[i % 4].toInt()).toByte()
when (opcode) {
0x8 -> return null
0x9 -> { out.write(byteArrayOf(0x8A.toByte(), 0x80.toByte(), 0, 0, 0, 0)); out.flush() }
0x1, 0x0 -> { message.write(data); if (fin) return message.toString("UTF-8") }
else -> {}
}
}
}
override fun close() { runCatching { out.write(byteArrayOf(0x88.toByte(), 0x80.toByte(), 0, 0, 0, 0)); out.flush() }; runCatching { socket.close() } }
}
private val ADD = """(async (name, exe, dir, compat) => {
const id = await SteamClient.Apps.AddShortcut(name, exe, dir, "");
if (!id) return 0;
try { SteamClient.Apps.SetShortcutName(id, name); } catch (e) {}
try { SteamClient.Apps.AddUserTagToApps([id], ${JSONObject.quote(TAG_NAME)}); } catch (e) {}
if (compat) { try { SteamClient.Apps.SpecifyCompatTool(id, ${JSONObject.quote(COMPAT_TOOL)}); } catch (e) {} }
for (let i = 0; i < 40; i++) {
try { if (globalThis.appStore.GetAppOverviewByAppID(id)) break; } catch (e) {}
await new Promise(r => setTimeout(r, 250));
}
return id;
})"""
}
@@ -14,7 +14,7 @@ object StoreInstallRoot {
private const val ON_VOLUME = "Games"
const val GUEST_EXTERNAL = "/mnt/droiddeck-stores"
class Target(val root: File, val label: String, val removable: Boolean) {
class Target(val root: File, val label: String, val removable: Boolean, val folder: Boolean = false) {
val freeBytes: Long get() = availableBytes(root)
}
@@ -77,7 +77,16 @@ object StoreInstallRoot {
fun targets(context: Context): List<Target> {
val internal = Target(internalRoot(context), context.getString(com.droiddeck.launcher.R.string.games_internal), removable = false)
val cards = GameStorage.options(context).map { Target(File(it.path, ON_VOLUME), it.name, removable = true) }
return listOf(internal) + cards
val library = GameStorage.effective(context)?.let { lib ->
val root = File(lib.path, ON_VOLUME)
if (cards.any { it.root.absolutePath == root.absolutePath }) return@let null
val volume = runCatching { context.getSystemService(StorageManager::class.java)?.getStorageVolume(File(lib.path)) }.getOrNull()
val name = File(lib.path).name.ifBlank { lib.label }
val where = volume?.takeUnless { it.isPrimary }?.getDescription(context)
val label = if (where.isNullOrBlank()) name else context.getString(com.droiddeck.launcher.R.string.gstore_folder_on_volume, name, where)
Target(root, label, removable = true, folder = true)
}
return listOf(internal) + cards + listOfNotNull(library)
}
fun installRoot(context: Context): File = internalRoot(context)
@@ -63,6 +63,7 @@ object StoreInstalls {
} catch (e: Exception) {
Log.w(TAG, "registration: ${e.message}")
}
com.droiddeck.launcher.stores.epic.EpicClient.libraryChanged(app)
}
fun uninstall(context: Context, game: InstalledStoreGame, progress: (Float) -> Unit = {}, removed: () -> Unit = {}) {
@@ -9,6 +9,7 @@ object StoreLaunch {
private const val TAG = "StoreLaunch"
const val LAUNCHER = ".droiddeck-launch.bat"
const val EPIC_CODE = ".droiddeck-epic-code"
const val EPIC_ARGS = ".droiddeck-epic-args"
fun writeLauncher(folder: File, sidecar: StoreGameSidecar): StoreGameSidecar {
val needs = sidecar.args.isNotEmpty() || sidecar.env.isNotEmpty() || sidecar.store == Store.EPIC
@@ -30,6 +31,7 @@ object StoreLaunch {
val args = sidecar.args.joinToString(" ") { quoteArg(it) }
val run = "\"%~dp0$exe\"" + (if (args.isNotEmpty()) " $args" else "")
if (sidecar.store == Store.EPIC) {
lines += "if exist \"%~dp0$EPIC_ARGS\" goto client"
lines += "set \"$CODE_VAR=\""
lines += "if exist \"%~dp0$EPIC_CODE\" set /p $CODE_VAR=<\"%~dp0$EPIC_CODE\""
lines += "if exist \"%~dp0$EPIC_CODE\" del \"%~dp0$EPIC_CODE\""
@@ -38,6 +40,13 @@ object StoreLaunch {
lines += "goto :eof"
lines += ":signed"
lines += "set \"$CODE_VAR=\" & $run -AUTH_LOGIN=unused -AUTH_PASSWORD=%$CODE_VAR% -AUTH_TYPE=exchangecode"
lines += "goto :eof"
lines += ":client"
lines += "set \"$CLIENT_VAR=\""
lines += "set /p $CLIENT_VAR=<\"%~dp0$EPIC_ARGS\""
lines += "del \"%~dp0$EPIC_ARGS\""
lines += "if exist \"%~dp0$EPIC_CODE\" del \"%~dp0$EPIC_CODE\""
lines += "set \"$CLIENT_VAR=\" & \"%~dp0$exe\" %$CLIENT_VAR%"
} else {
lines += run
}
@@ -52,6 +61,7 @@ object StoreLaunch {
}
private const val CODE_VAR = "DD_X"
private const val CLIENT_VAR = "DD_A"
fun refreshLauncher(folder: File, sidecar: StoreGameSidecar) {
if (sidecar.launcher != LAUNCHER) return
@@ -88,6 +88,41 @@ object StoreLaunchRequests {
JSONObject().put("ok", false).put("reason", e.javaClass.simpleName)
}
}
"epic-sign-in" -> {
val url = request.optString("url")
try {
if (com.droiddeck.launcher.stores.epic.EpicClient.signIn(app, url, request.optBoolean("auto"))) JSONObject().put("ok", true)
else JSONObject().put("ok", false).put("reason", "not-sign-in")
} catch (e: Exception) {
JSONObject().put("ok", false).put("reason", e.javaClass.simpleName)
}
}
"epic-play-in-steam" -> {
val id = request.optString("id")
if (id.isEmpty()) JSONObject().put("ok", false).put("reason", "no-id")
else try {
com.droiddeck.launcher.stores.epic.EpicClient.playInSteam(app, id)
} catch (e: Exception) {
JSONObject().put("ok", false).put("reason", e.javaClass.simpleName)
}
}
"steam-run" -> try {
com.droiddeck.launcher.stores.epic.EpicClient.runSteamGame(app, request.optString("id"))
} catch (e: Exception) {
JSONObject().put("ok", false).put("reason", e.javaClass.simpleName)
}
"epic-signed-out" -> {
val signedIn = com.droiddeck.launcher.stores.epic.EpicCredentialStore.isLoggedIn(app)
if (signedIn) {
Log.i(TAG, "the Epic Games Launcher was signed out; signing the Epic store out too")
StoresState.signOut(app, Store.EPIC)
}
JSONObject().put("ok", true).put("signedOut", signedIn)
}
"epic-client-handoff" -> {
if (com.droiddeck.launcher.stores.epic.EpicClient.canHandOff(app)) JSONObject().put("ok", true)
else JSONObject().put("ok", false).put("reason", "no-account")
}
else -> JSONObject().put("ok", false).put("reason", "unknown-op")
}
try {
@@ -36,9 +36,10 @@ class StoreLoginActivity : ComponentActivity() {
companion object {
private const val TAG = "StoreLogin"
const val EXTRA_STORE = "store"
const val EXTRA_CLIENT_URL = "client_url"
private const val KEY_STATE = "oauth_state"
@Volatile internal var floodColor: Int? = null
private const val CHROME_UA = "Mozilla/5.0 (Linux; Android 14; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.6533.103 Mobile Safari/537.36"
internal const val CHROME_UA = "Mozilla/5.0 (Linux; Android 14; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.6533.103 Mobile Safari/537.36"
fun generateState(): String {
val bytes = ByteArray(24)
@@ -56,6 +57,7 @@ class StoreLoginActivity : ComponentActivity() {
}
private var store: Store? = null
private var clientUrl: String? = null
private var flow: Flow? = null
private var webViewRef: WebView? = null
private var popupWebView: WebView? = null
@@ -78,8 +80,9 @@ class StoreLoginActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
store = Store.byId(intent.getStringExtra(EXTRA_STORE))
clientUrl = intent.getStringExtra(EXTRA_CLIENT_URL)?.takeIf { store == Store.EPIC }
oauthState = savedInstanceState?.getString(KEY_STATE) ?: generateState()
flow = store?.let { LoginFlows.forStore(it, oauthState!!) }
flow = newFlow(oauthState!!)
floodColor?.let { c ->
floodColor = null
flooded = true
@@ -109,6 +112,12 @@ class StoreLoginActivity : ComponentActivity() {
webView.loadUrl(flow!!.startUrl)
}
private fun newFlow(state: String): Flow? {
val url = clientUrl
if (url != null) return com.droiddeck.launcher.stores.epic.EpicClient.loginFlow(url)
return store?.let { LoginFlows.forStore(it, state) }
}
override fun finish() {
super.finish()
@Suppress("DEPRECATION") if (flooded) overridePendingTransition(0, 0)
@@ -187,7 +196,7 @@ class StoreLoginActivity : ComponentActivity() {
captured.set(false)
val fresh = generateState()
oauthState = fresh
flow = store?.let { LoginFlows.forStore(it, fresh) } ?: return
flow = newFlow(fresh) ?: return
webViewRef?.let { it.settings.userAgentString = flow!!.userAgent; it.loadUrl(flow!!.startUrl) }
}
@@ -323,6 +332,16 @@ class StoreLoginActivity : ComponentActivity() {
oauthState?.let { outState.putString(KEY_STATE, it) }
}
override fun onStart() {
super.onStart()
if (clientUrl != null && !isFinishing) com.droiddeck.launcher.session.SessionService.holdForSignIn(this, true)
}
override fun onStop() {
if (clientUrl != null && !isChangingConfigurations) com.droiddeck.launcher.session.SessionService.holdForSignIn(this, false)
super.onStop()
}
override fun onDestroy() {
popupWebView?.let { popupWebView = null; destroyPopupView(it) }
webViewRef?.let { it.webChromeClient = null; (it.parent as? ViewGroup)?.removeView(it); it.destroy() }
@@ -33,6 +33,8 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
override fun signOut(context: Context) {
runCatching { EpicLibrary.forget(context) }
runCatching { EpicClient.signOut(context) }
EpicClient.forgetWebSignIn()
}
override fun syncLibrary(context: Context, force: Boolean) {
@@ -0,0 +1,427 @@
package com.droiddeck.launcher.stores.epic
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.storage.SteamStorage
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreLog
import com.droiddeck.launcher.stores.StoreLoginActivity
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.SteamLiveShortcuts
import org.json.JSONObject
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.Executors
import java.util.zip.CRC32
object EpicClient {
private const val TAG = "EpicClient"
const val DOWNLOAD_ID = "epic-games-launcher"
const val DOWNLOAD_KEY = "epic:$DOWNLOAD_ID"
const val PROGRAM = "/usr/local/bin/droiddeck-epic"
const val PLAYING = "epic-playing"
const val STEAM_LAUNCHER = "/usr/local/bin/droiddeck-epic-steam"
const val OPEN = "epic-open"
const val FOCUSED_APP = "steam-focused-app"
private const val STEAM_DIR = "/usr/local/bin"
private const val SETTINGS = "settings/app-settings.json"
private const val STOCK_INSTALL_DIR = "/root/Games"
private const val FEX_DIR = "FEX-Emu"
private val FEX_PREFIXES = listOf("usr/", "", "files/usr/", "files/")
private const val FEX_WANTED = "root/.config/droiddeck/fex-wanted"
private const val ICON = "epic-games-launcher.png"
const val LAUNCHER_APP_ID = 0
private const val PREF_CHECKED = "client_checked_at"
private const val CHECK_EVERY_MS = 6 * 60 * 60 * 1000L
private const val IMPORT_EVERY_MS = 15_000L
private const val STATE = "root/.local/share/droiddeck-epic"
private const val DATA = "root/.local/share/com.epicgames.eglv2"
private const val AUTH = "auth/auth.json"
private const val SIGNED_OUT = "signed-out"
private const val AUTO_SIGN_IN = "auto-sign-in"
private val UNINSTALL_PATHS = listOf("current.json", "app", "runtime", "downloads", "bin", "fex", "run", "logs", "status.json", "instance.json")
private const val COOKIE_DOMAIN = ".epicgames.com"
private val COOKIE_PATHS = listOf("/", "/id")
private val COOKIE_URLS = listOf(
"https://www.epicgames.com/id/login", "https://www.epicgames.com/", "https://epicgames.com/",
"https://store.epicgames.com/", "https://accounts.epicgames.com/", "https://launcher.store.epicgames.com/",
)
private val work = Executors.newSingleThreadExecutor { r -> Thread(r, "epic-client") }
@Volatile private var importedAt = 0L
data class Status(
val installed: Boolean = false,
val version: String? = null,
val runtimeVersion: String? = null,
)
var status by mutableStateOf(Status())
private set
fun stateDir(context: Context): File = File(LinuxRuntime.rootDir(context), STATE)
fun dataDir(context: Context): File = File(LinuxRuntime.rootDir(context), DATA)
fun downloadsDir(context: Context): File = File(stateDir(context), "downloads")
fun guestPath(context: Context, file: File): String? {
val root = LinuxRuntime.rootDir(context).absolutePath
val path = file.absolutePath
return if (path.startsWith("$root/")) "/" + path.removePrefix("$root/") else null
}
private fun ready(dir: File): Boolean = File(dir, ".droiddeck-ready").isFile
internal fun canHandOff(context: Context): Boolean = EpicCredentialStore.isLoggedIn(context.applicationContext)
fun signOut(context: Context): Boolean {
val app = context.applicationContext
val auth = File(dataDir(app), AUTH)
val signedIn = launcherSignedIn(auth)
if (signedIn) runCatching { File(stateDir(app), SIGNED_OUT).writeText("${System.currentTimeMillis() / 1000}\n") }
auth.delete()
File(stateDir(app), AUTO_SIGN_IN).delete()
Log.i(TAG, if (signedIn) "signed the Epic Games Launcher out too" else "the Epic Games Launcher was already signed out")
return signedIn
}
internal fun launcherSignedIn(auth: File): Boolean =
runCatching { JSONObject(auth.readText()).optJSONObject("prod")?.optString("refresh_token").orEmpty().isNotEmpty() }.getOrDefault(false)
fun forgetWebSignIn() {
android.os.Handler(android.os.Looper.getMainLooper()).post {
runCatching {
val cookies = android.webkit.CookieManager.getInstance()
var cleared = 0
for (url in COOKIE_URLS) {
val lines = expiredCookies(cookies.getCookie(url), Uri.parse(url).host)
for (line in lines) cookies.setCookie(url, line)
cleared += lines.size
}
cookies.flush()
Log.i(TAG, "cleared the Epic web sign-in ($cleared cookie lines)")
}.onFailure { Log.w(TAG, "could not clear the Epic web sign-in: ${it.javaClass.simpleName}") }
}
}
internal fun expiredCookies(header: String?, host: String? = null): List<String> {
val domains = listOfNotNull(COOKIE_DOMAIN, host?.takeIf { it.endsWith(COOKIE_DOMAIN) })
return header.orEmpty().split(';').map { it.substringBefore('=').trim() }.filter { it.isNotEmpty() }.distinct()
.flatMap { name ->
COOKIE_PATHS.flatMap { path ->
listOf("$name=; Max-Age=0; Path=$path; Secure") + domains.map { "$name=; Max-Age=0; Path=$path; Secure; Domain=$it" }
}
}
}
fun read(context: Context): Status {
val app = context.applicationContext
if (!LinuxRuntime.isInstalled(app)) return Status()
val state = stateDir(app)
val current = runCatching { JSONObject(File(state, "current.json").readText()) }.getOrNull()
val version = current?.optString("app")?.ifEmpty { null }
val runtimeVersion = current?.optString("runtime")?.ifEmpty { null }
val installed = version != null && runtimeVersion != null &&
ready(File(state, "app/$version")) && ready(File(state, "runtime/$runtimeVersion"))
return Status(installed, version, runtimeVersion)
}
fun refresh(context: Context) {
val app = context.applicationContext
work.execute {
val next = runCatching { read(app) }.getOrNull() ?: return@execute
if (next.installed && System.currentTimeMillis() - importedAt >= IMPORT_EVERY_MS) {
importedAt = System.currentTimeMillis()
runCatching { EpicClientLibrary.importClientGames(app) }
.onFailure { Log.w(TAG, "client library scan failed: ${it.javaClass.simpleName}") }
}
StoresState.post { if (status != next) status = next }
}
}
fun ensure(context: Context) {
val app = context.applicationContext
if (!LinuxRuntime.isInstalled(app)) { refresh(app); return }
work.execute {
val before = read(app)
StoresState.post { if (status != before) status = before }
if (DownloadQueue.isActive(DOWNLOAD_KEY) || !before.installed) return@execute
syncLibrary(app)
val prefs = EpicPrefs.get(app)
val now = System.currentTimeMillis()
if (now - prefs.getLong(PREF_CHECKED, 0L) < CHECK_EVERY_MS) return@execute
val latest = EpicClientSources.launcher()?.version
prefs.edit().putLong(PREF_CHECKED, if (latest != null) now else 0L).apply()
val after = read(app)
StoresState.post { if (status != after) status = after }
if (updateWanted(after, latest)) StoresState.post { enqueue(app) }
}
}
internal fun updateWanted(current: Status, latest: String?): Boolean =
current.installed && latest != null && latest != current.version
@Volatile var uninstalling = false
fun install(context: Context) {
val app = context.applicationContext
if (status.installed || uninstalling) return
enqueue(app)
}
private fun syncLibrary(app: Context) {
if (launcherRunning(app)) return
EpicClientLibrary.sync(app)
}
private fun enqueue(app: Context) {
if (DownloadQueue.isActive(DOWNLOAD_KEY)) return
val entry = DownloadEntry(
Store.EPIC, DOWNLOAD_ID, app.getString(R.string.epic_client_title),
location = StoreInstallRoot.labelFor(app, stateDir(app)),
)
DownloadQueue.enqueue(app, entry) { EpicClientInstaller(app) }
}
internal fun installed(context: Context) {
val app = context.applicationContext
EpicPrefs.get(app).edit().putLong(PREF_CHECKED, System.currentTimeMillis()).apply()
refresh(app)
work.execute { syncLibrary(app) }
}
fun libraryChanged(context: Context) {
val app = context.applicationContext
work.execute { if (read(app).installed) syncLibrary(app) }
}
val shortcutAppId: Long = CRC32().apply { update("\"$STEAM_LAUNCHER\"${Library.EPIC_LAUNCHER_NAME}".toByteArray()) }.value or 0x80000000L
fun gameId(appId: Long): String = java.lang.Long.toUnsignedString((appId shl 32) or 0x02000000L)
fun steamListing(context: Context): JSONObject? {
val current = read(context)
if (!current.installed) return null
val entry = JSONObject().put("name", Library.EPIC_LAUNCHER_NAME).put("exe", STEAM_LAUNCHER).put("folder", STEAM_DIR)
.put("dir", STEAM_DIR).put("appid", shortcutAppId).put("seen", 0).put("native", true)
icon(context, current.version)?.let { guestPath(context, it) }?.let { entry.put("art", JSONObject().put("icon", it)) }
return entry
}
fun steamLauncherId(context: Context): Long? =
SteamLiveShortcuts.ensure(context, Library.EPIC_LAUNCHER_NAME, STEAM_LAUNCHER, STEAM_DIR, compat = false, appId = shortcutAppId)
fun icon(context: Context, version: String?): File? =
version?.let { File(stateDir(context), "app/$it/$ICON") }?.takeIf(File::isFile)
fun launcherEntry(context: Context, name: String, current: Status = status, art: File? = icon(context, current.version)): Library.SteamGame? {
if (!current.installed) return null
return Library.SteamGame(
appId = LAUNCHER_APP_ID, name = name, art = art, library = Library.EPIC_LAUNCHER,
gameId = LAUNCHER_APP_ID.toLong(), source = Store.EPIC.id,
)
}
fun withLauncher(games: List<Library.SteamGame>, launcher: Library.SteamGame?): List<Library.SteamGame> {
if (launcher == null) return games
val at = games.indexOfFirst { it.source == Store.EPIC.id }.takeIf { it >= 0 } ?: games.size
return games.subList(0, at) + launcher + games.subList(at, games.size)
}
private fun steamSession(): Boolean =
SessionState.running && !SessionState.stopRequested && SessionState.mode == SessionService.MODE_STEAM
fun launcherSession(): Boolean =
SessionState.running && !SessionState.stopRequested && SessionState.mode == SessionService.MODE_RUN &&
SessionState.program == com.droiddeck.launcher.session.NoSteamLaunch.EPIC
fun uninstall(context: Context): Boolean {
val app = context.applicationContext
val state = stateDir(app)
com.droiddeck.launcher.stores.download.DownloadQueue.clear(app, DOWNLOAD_KEY)
val removed = UNINSTALL_PATHS.map { File(state, it) }
.map { com.droiddeck.launcher.runtime.RuntimeFileTree.deleteWhatCan(it, null) }
.all { it }
val next = read(app)
StoresState.post { status = next }
Log.i(TAG, if (removed) "uninstalled the Epic Games Launcher" else "could not remove every Epic Games Launcher file")
return removed && !next.installed
}
fun launcherRunning(context: Context): Boolean =
(steamSession() || launcherSession()) && File(LinuxRuntime.sessionRoot(context), OPEN).exists()
fun launcherFocused(context: Context): Boolean {
val root = LinuxRuntime.sessionRoot(context)
if (launcherSession()) return File(root, OPEN).exists()
if (!steamSession()) return false
val open = runCatching { File(root, OPEN).readText().trim() }.getOrNull() ?: return false
val focused = runCatching { File(root, FOCUSED_APP).readText().trim() }.getOrNull() ?: return false
return focused == (open.takeIf { it.length > 1 && it.all(Char::isDigit) } ?: shortcutAppId.toString())
}
fun playing(context: Context): Boolean = File(LinuxRuntime.sessionRoot(context), PLAYING).exists()
fun fexReady(context: Context): Boolean {
val usr = File(LinuxRuntime.rootDir(context), "usr/bin")
if (File(usr, "FEXServer").isFile && fexBinary(usr)) return true
return Library.steamLibraries(context).any { (library, _) ->
val manifest = File(library, "steamapps/appmanifest_${SteamStorage.FEX}.acf")
val dir = runCatching { SteamStorage.parseManifest(manifest, manifest.readText())?.installDir }.getOrNull()
val roots = listOf(library, com.droiddeck.launcher.session.SecondaryLibrary.privateRoot(context.filesDir, library))
listOfNotNull(dir, FEX_DIR).distinct().any { name ->
roots.any { root ->
val tool = File(root, "steamapps/common/$name")
FEX_PREFIXES.any { fexBinary(File(tool, "${it}bin")) }
}
}
}
}
private fun fexBinary(bin: File): Boolean = File(bin, "FEX").isFile || File(bin, "FEXInterpreter").isFile
fun requestFex(context: Context) {
runCatching {
File(LinuxRuntime.rootDir(context), FEX_WANTED).apply { parentFile?.mkdirs() }.writeText("1\n")
}.onFailure { Log.w(TAG, "could not ask Steam for FEX: ${it.javaClass.simpleName}") }
}
fun prepareInstallDir(context: Context): String? {
val app = context.applicationContext
val dirs = StoreInstallRoot.targets(app).mapNotNull { t ->
val folder = StoreInstallRoot.storeDir(t.root, Store.EPIC)
AddedGames.guestPath(app, folder)?.let { t.root.absolutePath to (folder to it) }
}.toMap()
if (dirs.isEmpty()) return null
val chosen = dirs[SessionPrefs.storesInstallTarget(app)] ?: dirs[StoreInstallRoot.internalRoot(app).absolutePath] ?: dirs.values.first()
val file = File(dataDir(app), SETTINGS)
val settings = runCatching { JSONObject(file.readText()) }.getOrNull() ?: JSONObject()
val current = settings.optString("defaultInstallDir").trimEnd('/')
if (current.isNotEmpty() && current != STOCK_INSTALL_DIR && dirs.values.none { it.second == current } && !(current.endsWith("/${Store.EPIC.shortLabel}") && (current.startsWith("/mnt/droiddeck-") || current.startsWith("/root/Storage/")))) return current
if (!chosen.first.isDirectory && !chosen.first.mkdirs()) return null
if (current == chosen.second) return current
return runCatching {
file.parentFile?.mkdirs()
val staged = File(file.path + ".tmp")
staged.writeText(settings.put("defaultInstallDir", chosen.second).toString(2))
check(staged.renameTo(file))
Log.i(TAG, "the Epic Games Launcher installs games to ${chosen.second}")
chosen.second
}.onFailure { Log.w(TAG, "could not set the launcher's install folder: ${it.javaClass.simpleName}") }.getOrNull()
}
fun playInSteam(context: Context, id: String): JSONObject {
if (!steamSession()) return failed("no-steam")
runCatching { EpicClientLibrary.importClientGames(context) }.onFailure { Log.w(TAG, "client library scan failed: ${it.javaClass.simpleName}") }
val game = steamShortcut(AddedGames.scan(context), id) ?: return failed("not-registered")
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(context, com.droiddeck.launcher.session.NoSteamLaunch.settingsId(game))) return failed("no-steam-game")
if (!AddedGames.inSteam(context, game.appId) || SteamLiveShortcuts.known(context, game.appId) == false) return failed("not-in-steam")
if (!SessionService.launchGame(context, gameId(game.appId))) return failed("busy")
Log.i(TAG, "the Epic Games Launcher hands $id to Steam as ${gameId(game.appId)}")
return JSONObject().put("ok", true)
}
fun runSteamGame(context: Context, id: String): JSONObject {
if (!com.droiddeck.launcher.frontend.GameLaunchLink.validId(id)) return failed("bad-id")
if (!steamSession()) return failed("no-steam")
if (!SessionService.launchGame(context, id)) return failed("busy")
Log.i(TAG, "the Epic Games Launcher hands Steam game $id to Steam")
return JSONObject().put("ok", true)
}
private fun failed(reason: String): JSONObject = JSONObject().put("ok", false).put("reason", reason)
internal fun steamShortcut(games: List<AddedGames.Game>, id: String): AddedGames.Game? =
games.firstOrNull { it.source == Store.EPIC.id && it.storeId == id }
fun redirectOf(url: String): String? {
val uri = runCatching { Uri.parse(url) }.getOrNull() ?: return null
if (uri.scheme != "https" || uri.host !in SIGN_IN_HOSTS || uri.path?.startsWith("/id/authorize") != true) return null
val redirect = runCatching { uri.getQueryParameter("redirect_uri") }.getOrNull() ?: return null
return redirect.takeIf { loopback(it) }
}
fun loopback(url: String): Boolean {
val uri = runCatching { Uri.parse(url) }.getOrNull() ?: return false
return uri.scheme == "http" && uri.host in LOOPBACK && uri.port in 1..65535 && uri.userInfo == null
}
fun signIn(context: Context, url: String, auto: Boolean): Boolean {
if (redirectOf(url) == null) return false
context.startActivity(
Intent(context, StoreLoginActivity::class.java)
.putExtra(StoreLoginActivity.EXTRA_STORE, Store.EPIC.id)
.putExtra(StoreLoginActivity.EXTRA_CLIENT_URL, if (auto) withoutAccountPrompt(url) else url)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
Log.i(TAG, "sign-in for the Epic Games Launcher: ${StoreLog.redactUrl(url)}")
return true
}
internal fun withoutAccountPrompt(url: String): String {
val query = url.substringAfter('?', "")
if (query.isEmpty()) return url
val kept = query.split('&').filter { it != "prompt=select_account" }
if (kept.size == query.split('&').size) return url
return url.substringBefore('?') + if (kept.isEmpty()) "" else "?" + kept.joinToString("&")
}
fun deliver(url: String): Boolean {
if (!loopback(url)) return false
var conn: HttpURLConnection? = null
return try {
conn = (URL(url).openConnection(java.net.Proxy.NO_PROXY) as HttpURLConnection).apply {
connectTimeout = 10_000
readTimeout = 15_000
instanceFollowRedirects = false
}
val code = conn.responseCode
runCatching { (if (code < 400) conn.inputStream else conn.errorStream)?.use { it.readBytes() } }
Log.i(TAG, "sign-in handed to the launcher: HTTP $code")
code in 200..399
} catch (e: Exception) {
Log.w(TAG, "the launcher's sign-in listener did not answer: ${e.javaClass.simpleName}")
false
} finally {
runCatching { conn?.disconnect() }
}
}
internal fun loginFlow(url: String): StoreLoginActivity.Flow? {
val redirect = redirectOf(url) ?: return null
val agent = runCatching { EpicNative.call("auth.config")?.optString("webViewUserAgent") }.getOrNull()?.ifEmpty { null }
return ClientLogin(url, redirect, agent ?: StoreLoginActivity.CHROME_UA)
}
private class ClientLogin(
override val startUrl: String,
private val redirect: String,
override val userAgent: String,
) : StoreLoginActivity.Flow {
override fun isRedirect(url: String): Boolean =
url == redirect || url.startsWith("$redirect?") || url.startsWith("$redirect#")
override fun finish(activity: StoreLoginActivity, view: android.webkit.WebView, url: String): String? =
if (deliver(url)) null else activity.getString(R.string.epic_client_sign_in_failed)
}
private val SIGN_IN_HOSTS = setOf("www.epicgames.com", "epicgames.com")
private val LOOPBACK = setOf("127.0.0.1", "localhost")
}
@@ -0,0 +1,357 @@
package com.droiddeck.launcher.stores.epic
import android.content.Context
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.formatBytes
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.RandomAccessFile
import java.net.HttpURLConnection
import java.net.URI
import java.net.URL
import java.net.URLDecoder
import java.security.MessageDigest
import java.util.concurrent.atomic.AtomicBoolean
internal object EpicClientSources {
const val LAUNCHER_URL = "https://launcher-public-service-prod06.ol.epicgames.com/launcher/api/installer/download/EpicGamesLauncher-x86_64.AppImage"
const val LAUNCHER_FILE = "EpicGamesLauncher-x86_64.AppImage"
const val RUNTIME_BASE = "https://repo.steampowered.com/steamrt4/images/"
const val RUNTIME_FILE = "com.valvesoftware.SteamRuntime.Platform-amd64,i386-steamrt4-runtime.tar.gz"
const val GLES_URL = "https://deb.debian.org/debian/pool/main/libg/libglvnd/libgles2_1.7.0-1+b2_amd64.deb"
const val GLES_FILE = "libgles2_1.7.0-1+b2_amd64.deb"
const val GLES_SHA256 = "e12c18aa77939d122ee1dea520ba0440b97dc19200b7396e03dff03a3ece74c1"
const val USER_AGENT = "DroidDeck"
private val VERSION = Regex("[A-Za-z0-9._+-]{1,64}")
private val SUM = Regex("^([0-9a-fA-F]{64})\\s+\\*?(.+)$")
class Source(val url: String, val version: String, val sha256: String? = null)
fun launcher(): Source? {
val location = redirect(LAUNCHER_URL) ?: return null
val version = launcherVersion(location) ?: return null
return Source(location, version)
}
fun launcherVersion(location: String): String? {
val uri = runCatching { URI(location) }.getOrNull() ?: return null
if (uri.scheme != "https") return null
val raw = Regex("/Builds/EGLv2/([^/]+)/Linux/").find(uri.rawPath ?: return null)?.groupValues?.get(1) ?: return null
val version = runCatching { URLDecoder.decode(raw.replace("+", "%2B"), "UTF-8") }.getOrNull() ?: return null
return version.takeIf { VERSION.matches(it) && it != "." && it != ".." }
}
fun runtime(): Source? {
val version = text(RUNTIME_BASE + "latest-public-stable/VERSION.txt")?.trim()?.takeIf { VERSION.matches(it) && it.startsWith("4.") } ?: return null
val sums = text("$RUNTIME_BASE$version/SHA256SUMS") ?: return null
val sha = sha256For(sums, RUNTIME_FILE) ?: return null
return Source("$RUNTIME_BASE$version/" + RUNTIME_FILE.replace(",", "%2C"), version, sha)
}
fun gles(): Source = Source(GLES_URL, "1.7.0-1+b2", GLES_SHA256)
fun sha256For(sums: String, file: String): String? = sums.lineSequence()
.mapNotNull { SUM.find(it.trim()) }
.firstOrNull { it.groupValues[2].trim() == file }
?.groupValues?.get(1)?.lowercase()
private fun redirect(url: String): String? {
var conn: HttpURLConnection? = null
return try {
conn = (URL(url).openConnection() as HttpURLConnection).apply {
instanceFollowRedirects = false
connectTimeout = 20_000
readTimeout = 20_000
setRequestProperty("User-Agent", USER_AGENT)
}
val code = conn.responseCode
val location = conn.getHeaderField("Location")
if (code in 300..399 && location != null) URI(url).resolve(location).toString() else null
} catch (e: Exception) {
null
} finally {
runCatching { conn?.disconnect() }
}
}
private fun text(url: String): String? {
var conn: HttpURLConnection? = null
return try {
conn = (URL(url).openConnection() as HttpURLConnection).apply {
connectTimeout = 20_000
readTimeout = 30_000
setRequestProperty("User-Agent", USER_AGENT)
}
if (conn.responseCode != 200) null else conn.inputStream.use { it.readBytes().toString(Charsets.UTF_8) }
} catch (e: Exception) {
null
} finally {
runCatching { conn?.disconnect() }
}
}
private val PART_MIB = longArrayOf(5, 8, 10, 15, 16, 25, 32, 50, 64, 100, 128, 256, 512)
fun etagMatches(file: File, etag: String): Boolean? {
val m = Regex("^(?:W/)?\"?([0-9a-fA-F]{32})(?:-(\\d+))?\"?$").matchEntire(etag.trim()) ?: return null
if (etag.trim().startsWith("W/")) return null
val want = m.groupValues[1].lowercase()
val count = m.groupValues[2].toLongOrNull() ?: return hex(digest(file, "MD5", 0L, file.length())) == want
val size = file.length()
val candidates = PART_MIB.map { it shl 20 }.filter { (size + it - 1) / it == count }
if (candidates.isEmpty()) return null
return candidates.any { multipart(file, it) == want }
}
private fun multipart(file: File, partSize: Long): String {
val outer = MessageDigest.getInstance("MD5")
var start = 0L
val size = file.length()
while (start < size) {
val end = minOf(size, start + partSize)
outer.update(digest(file, "MD5", start, end))
start = end
}
return hex(outer.digest())
}
fun sha256(file: File): String = hex(digest(file, "SHA-256", 0L, file.length()))
private fun digest(file: File, algorithm: String, start: Long, end: Long): ByteArray {
val md = MessageDigest.getInstance(algorithm)
RandomAccessFile(file, "r").use { raf ->
raf.seek(start)
val buf = ByteArray(1 shl 20)
var left = end - start
while (left > 0) {
val n = raf.read(buf, 0, minOf(buf.size.toLong(), left).toInt())
if (n < 0) break
md.update(buf, 0, n)
left -= n
}
}
return md.digest()
}
private fun hex(bytes: ByteArray): String = bytes.joinToString("") { "%02x".format(it) }
fun isAppImage(file: File): Boolean = runCatching {
RandomAccessFile(file, "r").use { raf ->
val head = ByteArray(11)
raf.readFully(head)
head[0] == 0x7f.toByte() && head[1] == 'E'.code.toByte() && head[2] == 'L'.code.toByte() && head[3] == 'F'.code.toByte() &&
head[8] == 'A'.code.toByte() && head[9] == 'I'.code.toByte() && head[10] == 2.toByte()
}
}.getOrDefault(false)
}
internal class EpicClientInstaller(private val app: Context) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
@Volatile private var connection: HttpURLConnection? = null
private class Part(val url: String, val file: File, val sha256: String?, val appImage: Boolean) {
var size = -1L
var mismatch: String? = null
}
override fun run(handle: DownloadQueue.JobHandle): String? {
handle.stage(DownloadStage.MANIFEST, app.getString(R.string.epic_client_checking))
if (!LinuxRuntime.isInstalled(app)) throw IllegalStateException(app.getString(R.string.epic_client_no_runtime))
val launcher = EpicClientSources.launcher() ?: throw IllegalStateException(app.getString(R.string.epic_client_unreachable))
val runtime = EpicClientSources.runtime() ?: throw IllegalStateException(app.getString(R.string.epic_client_unreachable))
if (cancelled.get()) return null
val state = EpicClient.stateDir(app)
val before = EpicClient.read(app)
val needApp = !(before.version == launcher.version && File(state, "app/${launcher.version}/.droiddeck-ready").isFile)
val needRuntime = !(before.runtimeVersion == runtime.version && File(state, "runtime/${runtime.version}/.droiddeck-ready").isFile)
val dir = EpicClient.downloadsDir(app).apply { mkdirs() }
val gles = EpicClientSources.gles()
val parts = buildList {
if (needApp) add(Part(launcher.url, File(dir, "${launcher.version}-${EpicClientSources.LAUNCHER_FILE}"), null, true))
if (needRuntime) {
add(Part(runtime.url, File(dir, "steamrt4-${runtime.version}.tar.gz"), runtime.sha256, false))
add(Part(gles.url, File(dir, EpicClientSources.GLES_FILE), gles.sha256, false))
}
}
val keep = parts.flatMap { listOf(it.file.name, it.file.name + PARTIAL, it.file.name + TAG) }.toSet()
dir.listFiles()?.forEach { if (it.name !in keep) it.deleteRecursively() }
if (parts.isNotEmpty()) {
parts.forEach { it.size = length(it.url) }
val total = parts.sumOf { it.size.coerceAtLeast(0L) }
val have = parts.sumOf { p -> if (p.file.isFile) p.file.length() else File(p.file.path + PARTIAL).length() }
val needed = (total - have).coerceAtLeast(0L) + (if (needApp) APP_ROOM else 0L) + (if (needRuntime) RUNTIME_ROOM else 0L)
val free = StoreInstallRoot.availableBytes(state)
if (StoreInstallRoot.insufficientSpace(needed, free)) {
throw IllegalStateException(app.getString(R.string.stores_storage_insufficient, formatBytes(needed), formatBytes(free)))
}
var base = 0L
for (part in parts) {
fetch(part, handle, base, total)
if (cancelled.get()) return null
base += part.size.coerceAtLeast(part.file.length())
}
}
if (cancelled.get()) return null
handle.stage(DownloadStage.INSTALL, app.getString(R.string.epic_client_unpacking))
val argv = mutableListOf(EpicClient.PROGRAM, "install", "--app-version", launcher.version, "--runtime-version", runtime.version)
fun guest(file: File) = EpicClient.guestPath(app, file) ?: throw IllegalStateException(app.getString(R.string.epic_client_unpack_failed, file.name))
if (needApp) argv += listOf("--app", guest(parts[0].file))
if (needRuntime) argv += listOf("--runtime", guest(parts[parts.size - 2].file), "--gles", guest(parts[parts.size - 1].file))
var answer: JSONObject? = null
val code = GuestCommand.run(app, argv, fakeRoot = true, logName = "epic-client") { line ->
if (line.startsWith("{")) runCatching { JSONObject(line) }.getOrNull()?.let { answer = it }
}
val result = answer
if (code != 0 || result?.optBoolean("installed") != true) {
val reason = result?.optString("reason")?.ifEmpty { null } ?: "exit $code"
throw IllegalStateException(app.getString(R.string.epic_client_unpack_failed, reason))
}
parts.forEach { it.file.delete() }
handle.log("Epic Games Launcher ${launcher.version} installed (runtime ${runtime.version})")
EpicClient.installed(app)
return state.absolutePath
}
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
runCatching { connection?.disconnect() }
if (deleteFiles) EpicClient.downloadsDir(app).deleteRecursively()
}
private fun length(url: String): Long {
var conn: HttpURLConnection? = null
return try {
conn = (URL(url).openConnection() as HttpURLConnection).apply {
requestMethod = "HEAD"
connectTimeout = 20_000
readTimeout = 20_000
setRequestProperty("User-Agent", EpicClientSources.USER_AGENT)
setRequestProperty("Accept-Encoding", "identity")
}
if (conn.responseCode == 200) conn.contentLengthLong else -1L
} catch (e: Exception) {
-1L
} finally {
runCatching { conn?.disconnect() }
}
}
private fun fetch(part: Part, handle: DownloadQueue.JobHandle, base: Long, total: Long) {
if (part.file.isFile && (part.size <= 0 || part.file.length() == part.size)) {
handle.progress(base + part.file.length(), total)
return
}
part.file.delete()
val partial = File(part.file.path + PARTIAL)
val tag = File(part.file.path + TAG)
var attempt = 0
while (true) {
if (cancelled.get()) return
try {
transfer(part, partial, tag, handle, base, total)
if (cancelled.get()) return
verify(part, partial, runCatching { tag.readText().trim() }.getOrDefault(""))
if (!partial.renameTo(part.file)) throw IOException("could not keep ${part.file.name}")
tag.delete()
return
} catch (e: IOException) {
if (cancelled.get()) return
attempt++
handle.log("Epic Games Launcher: ${part.file.name} attempt $attempt: ${e.message ?: e.javaClass.simpleName}")
if (attempt >= ATTEMPTS) throw IllegalStateException(app.getString(R.string.epic_client_download_failed, e.message ?: e.javaClass.simpleName))
val until = System.currentTimeMillis() + (2_000L shl (attempt - 1)).coerceAtMost(30_000L)
while (System.currentTimeMillis() < until && !cancelled.get()) Thread.sleep(100)
}
}
}
private fun transfer(part: Part, partial: File, tag: File, handle: DownloadQueue.JobHandle, base: Long, total: Long) {
val have = if (partial.isFile) partial.length() else 0L
if (part.size > 0 && have > part.size) { partial.delete(); tag.delete(); throw IOException("partial file larger than the download") }
if (part.size > 0 && have == part.size) return
val etag = runCatching { tag.readText().trim() }.getOrDefault("")
val conn = (URL(part.url).openConnection() as HttpURLConnection).apply {
connectTimeout = 20_000
readTimeout = 30_000
setRequestProperty("User-Agent", EpicClientSources.USER_AGENT)
setRequestProperty("Accept-Encoding", "identity")
if (have > 0) {
setRequestProperty("Range", "bytes=$have-")
if (etag.isNotEmpty()) setRequestProperty("If-Range", etag)
}
}
connection = conn
try {
val code = conn.responseCode
val append = when (code) {
206 -> {
val start = Regex("bytes (\\d+)-").find(conn.getHeaderField("Content-Range") ?: "")?.groupValues?.get(1)?.toLongOrNull()
if (start != have) throw IOException("the server resumed at the wrong place")
true
}
200 -> false
416 -> { partial.delete(); tag.delete(); throw IOException("HTTP 416") }
else -> throw IOException("HTTP $code")
}
val served = conn.getHeaderField("ETag")?.takeIf { it.isNotBlank() }
if (served != null) tag.writeText(served) else if (!append) tag.delete()
val length = conn.contentLengthLong
if (length > 0) {
val full = if (append) have + length else length
if (part.size > 0 && full != part.size) throw IOException("the download changed size")
part.size = full
}
var done = if (append) have else 0L
conn.inputStream.use { input ->
FileOutputStream(partial, append).use { out ->
val buf = ByteArray(256 * 1024)
while (!cancelled.get()) {
val n = input.read(buf)
if (n < 0) break
out.write(buf, 0, n)
done += n
handle.progress(base + done, total)
}
out.fd.sync()
}
}
if (!cancelled.get() && part.size > 0 && done != part.size) throw IOException("the download ended early")
} finally {
connection = null
runCatching { conn.disconnect() }
}
}
private fun verify(part: Part, file: File, etag: String) {
if (part.size > 0 && file.length() != part.size) { file.delete(); throw IOException("wrong size") }
part.sha256?.let { want ->
if (EpicClientSources.sha256(file) != want) { file.delete(); throw IOException("checksum mismatch") }
}
if (part.appImage) {
if (!EpicClientSources.isAppImage(file)) { file.delete(); throw IOException("not an AppImage") }
if (EpicClientSources.etagMatches(file, etag) == false) {
val seen = EpicClientSources.sha256(file)
if (part.mismatch != seen) {
part.mismatch = seen
file.delete()
throw IOException("checksum mismatch")
}
}
}
}
private companion object {
const val PARTIAL = ".part"
const val TAG = ".etag"
const val ATTEMPTS = 6
const val APP_ROOM = 600L shl 20
const val RUNTIME_ROOM = 560L shl 20
}
}
@@ -0,0 +1,410 @@
package com.droiddeck.launcher.stores.epic
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.frontend.AddedExes
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.AddedGamesPublisher
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreLaunch
import com.droiddeck.launcher.stores.SteamLiveShortcuts
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.security.MessageDigest
internal object EpicClientLibrary {
private const val TAG = "EpicClientLibrary"
private const val V1 = "root/.local/share/Epic"
private const val NO_GUID = "00000000000000000000000000000000"
class Install(
val appName: String,
val namespace: String,
val catalogItemId: String,
val title: String,
val version: String,
val exe: String,
val location: String,
val folder: File,
val deploymentId: String,
val size: Long,
) {
val signature: String get() = "$location|$version|$exe"
}
fun manifestsDir(context: Context): File = File(LinuxRuntime.rootDir(context), "$V1/EpicGamesLauncher/Data/Manifests")
fun aggregateFile(context: Context): File = File(LinuxRuntime.rootDir(context), "$V1/UnrealEngineLauncher/LauncherInstalled.dat")
fun installationsFile(context: Context): File = File(EpicClient.dataDir(context), "installations.jsonl")
fun importMarker(context: Context): File = File(EpicClient.dataDir(context), "import-scan/imported.json")
private fun ledgerFile(context: Context): File = File(EpicClient.stateDir(context), "registered.json")
private fun importsFile(context: Context): File = File(EpicClient.stateDir(context), "client-imports.json")
fun guid(appName: String): String =
MessageDigest.getInstance("MD5").digest("droiddeck-epic:$appName".toByteArray(Charsets.UTF_8))
.joinToString("") { "%02X".format(it) }
fun installs(context: Context): List<Install> {
val app = context.applicationContext
val prefs = EpicPrefs.get(app)
return StoreInstallRoot.gameFolders(app).mapNotNull { folder ->
val sidecar = StoreGameSidecar.read(folder) ?: return@mapNotNull null
if (sidecar.store != Store.EPIC || !sidecar.isInstalled || sidecar.exe.isEmpty() ||
sidecar.extra["clientManaged"] == "true") return@mapNotNull null
val namespace = sidecar.extra["namespace"].orEmpty()
val item = sidecar.extra["catalogItemId"].orEmpty()
if (namespace.isEmpty() || item.isEmpty()) return@mapNotNull null
val location = AddedGames.guestPath(app, folder) ?: return@mapNotNull null
Install(
sidecar.id, namespace, item, sidecar.title, sidecar.installVersion, sidecar.exe, location, folder,
sidecar.extra["deploymentId"].orEmpty(), prefs.getLong("size_${sidecar.id}", 0L),
)
}.distinctBy { it.appName }
}
fun item(install: Install, tags: List<String>, ownership: Boolean): JSONObject {
val guid = guid(install.appName)
val store = "${install.location}/.egstore"
return JSONObject()
.put("FormatVersion", 0)
.put("bIsIncompleteInstall", false)
.put("LaunchCommand", "")
.put("LaunchExecutable", install.exe)
.put("ManifestLocation", store)
.put("ManifestHash", "")
.put("bIsApplication", true)
.put("bIsExecutable", true)
.put("bIsManaged", false)
.put("bNeedsValidation", false)
.put("bRequiresAuth", true)
.put("bAllowMultipleInstances", false)
.put("bCanRunOffline", false)
.put("bAllowUriCmdArgs", false)
.put("bLaunchElevated", false)
.put("BaseURLs", JSONArray())
.put("BuildLabel", "Live")
.put("AppCategories", JSONArray(listOf("public", "games", "applications")))
.put("ChunkDbs", JSONArray())
.put("CompatibleApps", JSONArray())
.put("DisplayName", install.title)
.put("InstallationGuid", guid)
.put("InstallLocation", install.location)
.put("InstallSessionId", guid)
.put("InstallTags", JSONArray(tags))
.put("InstallComponents", JSONArray())
.put("HostInstallationGuid", NO_GUID)
.put("PrereqIds", JSONArray())
.put("PrereqSHA1Hash", "")
.put("LastPrereqSucceededSHA1Hash", "")
.put("StagingLocation", "$store/bps")
.put("TechnicalType", "games")
.put("VaultThumbnailUrl", "")
.put("VaultTitleText", "")
.put("InstallSize", install.size)
.put("MainWindowProcessName", "")
.put("ProcessNames", JSONArray())
.put("BackgroundProcessNames", JSONArray())
.put("IgnoredProcessNames", JSONArray())
.put("DlcProcessNames", JSONArray())
.put("MandatoryAppFolderName", install.folder.name)
.put("OwnershipToken", if (ownership) "true" else "false")
.put("SidecarConfigRevision", 0)
.put("SidecarDeploymentId", install.deploymentId)
.put("CatalogNamespace", install.namespace)
.put("CatalogItemId", install.catalogItemId)
.put("AppName", install.appName)
.put("AppVersionString", install.version)
.put("MainGameCatalogNamespace", install.namespace)
.put("MainGameCatalogItemId", install.catalogItemId)
.put("MainGameAppName", install.appName)
.put("AllowedUriEnvVars", JSONArray())
}
internal fun aggregateFromManifests(manifests: File, installs: List<Install>, previous: JSONObject? = null): JSONObject {
val entries = linkedMapOf<String, JSONObject>()
val old = previous?.optJSONArray("InstallationList")
if (old != null) for (index in 0 until old.length()) {
val entry = old.optJSONObject(index) ?: continue
val appName = entry.optString("AppName").ifEmpty { entry.optString("ArtifactId") }
if (appName.isNotEmpty()) entries[appName] = entry
}
manifests.listFiles { file -> file.isFile && file.extension == "item" }
.orEmpty().sortedBy { it.name }.forEach { file ->
val item = runCatching { JSONObject(file.readText()) }.getOrNull() ?: return@forEach
if (item.optBoolean("bIsIncompleteInstall", true)) return@forEach
val appName = item.optString("AppName")
val location = item.optString("InstallLocation")
val namespace = item.optString("CatalogNamespace")
val catalogItem = item.optString("CatalogItemId")
if (appName.isEmpty() || location.isEmpty() || namespace.isEmpty() || catalogItem.isEmpty()) return@forEach
entries[appName] = JSONObject().put("InstallLocation", location).put("NamespaceId", namespace)
.put("ItemId", catalogItem).put("ArtifactId", appName).put("AppVersion", item.optString("AppVersionString"))
.put("AppName", appName)
}
installs.forEach { install ->
entries[install.appName] = JSONObject().put("InstallLocation", install.location).put("NamespaceId", install.namespace)
.put("ItemId", install.catalogItemId).put("ArtifactId", install.appName).put("AppVersion", install.version)
.put("AppName", install.appName)
}
return JSONObject().put("InstallationList", JSONArray(entries.values.toList()))
}
internal fun executableRelative(installLocation: String, executable: String): String? {
val location = installLocation.trimEnd('/')
val path = executable.replace('\\', '/').trim()
val raw = when {
path.startsWith("$location/") -> path.removePrefix("$location/")
path.startsWith('/') -> return null
else -> path.removePrefix("./")
}
if (location.isEmpty() || !location.startsWith('/') || raw.isEmpty() ||
!raw.endsWith(".exe", ignoreCase = true) || raw.split('/').any { it.isEmpty() || it == "." || it == ".." } || raw.contains(':')) return null
return raw
}
private fun hostFolder(context: Context, guest: String): File? {
if (!guest.startsWith('/') || guest.split('/').any { it == ".." }) return null
val mounts = mutableListOf<Pair<String, String>>()
SessionPrefs.gameFolderBinds(context).forEach { (host, path) -> mounts += path.trimEnd('/') to host }
StoreInstallRoot.externalRoots(context).forEach { (host, path) -> mounts += path.trimEnd('/') to host.absolutePath }
GameStorage.effective(context)?.let { mounts += "/mnt/droiddeck-sd" to it.path }
SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let { mounts += "/root/ROMs" to it }
mounts.sortedByDescending { it.first.length }.forEach { (mount, host) ->
if (guest == mount || guest.startsWith("$mount/")) {
val suffix = guest.removePrefix(mount).trimStart('/')
return File(host, suffix).takeIf { it.isDirectory && AddedGames.guestPath(context, it)?.trimEnd('/') == guest.trimEnd('/') }
}
}
val root = LinuxRuntime.rootDir(context)
if (guest == "/") return root
return File(root, guest.removePrefix("/")).takeIf { it.isDirectory && AddedGames.guestPath(context, it)?.trimEnd('/') == guest.trimEnd('/') }
}
@Synchronized
internal fun importClientGames(context: Context): Boolean {
val app = context.applicationContext
val manifests = manifestsDir(app)
val before = runCatching { JSONObject(importsFile(app).readText()) }.getOrDefault(JSONObject())
val after = JSONObject()
val imported = ArrayList<AddedGames.Game>()
val addedExes = AddedExes.list(app)
var changed = false
var scanComplete = true
val items = LinkedHashMap<String, JSONObject>()
manifests.listFiles { file -> file.isFile && file.extension == "item" }
.orEmpty().sortedBy { it.name }.forEach { file ->
val item = runCatching { JSONObject(file.readText()) }.getOrNull()
if (item == null) scanComplete = false else items[item.optString("AppName").trim()] = item
}
val (records, readable) = clientInstallations(installationsFile(app))
if (!readable) scanComplete = false
if (records.isNotEmpty()) {
val titles = runCatching { EpicLibrary.cached(app).associate { it.appName to it.title } }.getOrDefault(emptyMap())
for (record in records) {
val appName = record.optString("artifactId").trim()
if (appName.isNotEmpty()) items[appName] = manifestOf(record, titles[appName])
}
}
items.values.forEach { item ->
val appName = item.optString("AppName").trim()
if (item.optBoolean("bIsIncompleteInstall", true)) {
before.optJSONObject(appName)?.let { after.put(appName, it) }
return@forEach
}
val namespace = item.optString("CatalogNamespace").trim()
val catalogItem = item.optString("CatalogItemId").trim()
val location = item.optString("InstallLocation").trimEnd('/')
val exe = executableRelative(location, item.optString("LaunchExecutable"))
if (appName.isEmpty() || namespace.isEmpty() || catalogItem.isEmpty() || exe == null) {
before.optJSONObject(appName)?.let { after.put(appName, it) }
return@forEach
}
val folder = hostFolder(app, location)?.takeIf { it.isDirectory }
if (folder == null) { before.optJSONObject(appName)?.let { after.put(appName, it) }; return@forEach }
val executable = File(folder, exe)
if (!executable.isFile || !runCatching { executable.canonicalPath.startsWith(folder.canonicalPath + File.separator) }.getOrDefault(false)) {
before.optJSONObject(appName)?.let { after.put(appName, it) }
return@forEach
}
val existing = StoreGameSidecar.read(folder)
if (existing != null && (existing.store != Store.EPIC || existing.id != appName || existing.extra["clientManaged"] != "true")) {
before.optJSONObject(appName)?.let { after.put(appName, it) }
return@forEach
}
val previous = before.optJSONObject(appName)
if (previous != null && previous.optString("folder") != folder.path) {
val oldFolder = File(previous.optString("folder"))
StoreGameSidecar.read(oldFolder)?.takeIf { it.store == Store.EPIC && it.extra["clientManaged"] == "true" }?.let {
StoreGameSidecar.file(oldFolder).delete()
File(oldFolder, StoreLaunch.LAUNCHER).delete()
}
AddedExes.drop(app, oldFolder.path)
SessionPrefs.addedGameStoredAppId(app, oldFolder.path)?.let { SteamLiveShortcuts.remove(app, it) }
changed = true
}
val next = StoreGameSidecar(
Store.EPIC, appName, item.optString("DisplayName").ifEmpty { appName }, exe,
installVersion = item.optString("AppVersionString"), installedAt = existing?.installedAt?.takeIf { it > 0 } ?: folder.lastModified(),
cover = existing?.cover, hero = existing?.hero,
extra = mapOf("namespace" to namespace, "catalogItemId" to catalogItem,
"deploymentId" to item.optString("SidecarDeploymentId"), "clientManaged" to "true"),
epic = existing?.epic ?: com.droiddeck.launcher.stores.EpicOptions(),
cloud = existing?.cloud ?: true,
launcher = StoreLaunch.LAUNCHER,
)
val sidecarChanged = existing?.toJson()?.toString(2) != next.toJson().toString(2)
val launcher = File(folder, StoreLaunch.LAUNCHER)
if (sidecarChanged || runCatching { launcher.readText() }.getOrNull() != StoreLaunch.launcherText(next)) {
StoreLaunch.writeLauncher(folder, next)
next.write(folder)
}
if (addedExes.none { it.folder == folder.path && it.exe == executable.path && !it.picked }) {
AddedExes.put(app, AddedExes.Entry(folder.path, executable.path, picked = false))
changed = true
}
val game = AddedGames.single(app, folder.path)
if (game != null) imported += game
after.put(appName, JSONObject().put("folder", folder.path).put("exe", executable.path))
if (sidecarChanged || before.optJSONObject(appName)?.optString("folder") != folder.path ||
before.optJSONObject(appName)?.optString("exe") != executable.path ||
existing?.installVersion != next.installVersion) changed = true
}
for (name in before.keys().asSequence().toList()) {
if (after.has(name)) continue
if (!scanComplete) { before.optJSONObject(name)?.let { after.put(name, it) }; continue }
val record = before.optJSONObject(name) ?: continue
val folder = File(record.optString("folder"))
val sidecar = StoreGameSidecar.read(folder)
if (sidecar?.store == Store.EPIC && sidecar.extra["clientManaged"] == "true") {
StoreGameSidecar.file(folder).delete()
File(folder, StoreLaunch.LAUNCHER).delete()
}
AddedExes.drop(app, folder.path)
SessionPrefs.addedGameStoredAppId(app, folder.path)?.let { SteamLiveShortcuts.remove(app, it) }
changed = true
}
if (changed) {
write(importsFile(app), after.toString(2))
AddedGamesPublisher.later(app) {
SteamLiveShortcuts.sync(app, (imported + AddedGames.scan(app).filter { it.source == Store.EPIC.id }).distinctBy { it.guestExe }) { it.source == Store.EPIC.id }
com.droiddeck.launcher.stores.StoresState.notifyLibraryChanged(app)
}
}
return changed
}
internal fun clientInstallations(file: File): Pair<List<JSONObject>, Boolean> {
if (!file.isFile) return emptyList<JSONObject>() to true
val lines = runCatching { file.readLines() }.getOrNull() ?: return emptyList<JSONObject>() to false
val latest = LinkedHashMap<String, JSONObject>()
var readable = true
for (line in lines) {
if (line.isBlank()) continue
val value = runCatching { JSONObject(line) }.getOrNull()
if (value == null) { readable = false; continue }
val key = value.optString("installationId").ifEmpty { value.optString("artifactId") }
if (key.isEmpty()) continue
latest.remove(key)
if (!value.optBoolean("deleted")) latest[key] = value
}
return latest.values.toList() to readable
}
internal fun manifestOf(record: JSONObject, title: String?): JSONObject {
val dir = record.optString("dir").trimEnd('/')
val complete = record.optBoolean("complete", false) && record.optString("platform") == "Windows"
return JSONObject()
.put("AppName", record.optString("artifactId").trim())
.put("CatalogNamespace", record.optString("namespace"))
.put("CatalogItemId", record.optString("itemId"))
.put("InstallLocation", dir)
.put("LaunchExecutable", record.optString("launchExecutable"))
.put("AppVersionString", record.optString("version"))
.put("SidecarDeploymentId", record.optJSONObject("sidecar")?.optString("deploymentId").orEmpty())
.put("DisplayName", title?.takeIf(String::isNotBlank) ?: dir.substringAfterLast('/'))
.put("bIsIncompleteInstall", !complete)
}
@Synchronized
fun sync(context: Context): Boolean {
val app = context.applicationContext
if (!LinuxRuntime.isInstalled(app)) return false
runCatching { importClientGames(app) }.onFailure { Log.w(TAG, "client library scan failed: ${it.javaClass.simpleName}") }
val list = installs(app)
val manifests = manifestsDir(app)
val ledgerFile = ledgerFile(app)
val before = runCatching { JSONObject(ledgerFile.readText()) }.getOrDefault(JSONObject())
val after = JSONObject()
val tags = runCatching { EpicInstallTags.tagsForDevice() }.getOrDefault(emptyList())
val token by lazy { runCatching { EpicCredentialStore.getValidAccessToken(app) }.getOrNull() }
var changed = false
try {
manifests.mkdirs()
for (install in list) {
val guid = guid(install.appName)
val known = before.optJSONObject(install.appName)
val ownership = known?.takeIf { it.has("ownership") }?.optBoolean("ownership")
?: token?.let { ownershipToken(it, install) }
if (known?.optString("signature") != install.signature) changed = true
write(File(manifests, "$guid.item"), item(install, tags, ownership == true).toString(2))
runCatching { egstore(install, guid) { token } }.onFailure { Log.w(TAG, "${install.appName}: .egstore not written (${it.javaClass.simpleName})") }
after.put(install.appName, JSONObject().put("guid", guid).put("signature", install.signature).apply { if (ownership != null) put("ownership", ownership) })
StoreGameSidecar.read(install.folder)?.let { StoreLaunch.refreshLauncher(install.folder, it) }
}
for (name in before.keys().asSequence().toList()) {
if (after.has(name)) continue
File(manifests, guid(name) + ".item").delete()
changed = true
}
val aggregate = aggregateFile(app)
val previous = runCatching { JSONObject(aggregate.readText()) }.getOrNull()
write(aggregate, aggregateFromManifests(manifests, list, previous).toString(2))
write(ledgerFile, after.toString(2))
if (changed && importMarker(app).delete()) Log.i(TAG, "the launcher rescans installed games at its next start")
} catch (e: Exception) {
Log.w(TAG, "registration failed: ${e.javaClass.simpleName}: ${e.message}")
}
return changed
}
private fun ownershipToken(token: String, install: Install): Boolean? =
runCatching { EpicApiClient.getCustomAttribute(token, install.namespace, install.catalogItemId, "OwnershipToken") }
.getOrNull()?.trim()?.lowercase()?.let { it == "true" }
private fun egstore(install: Install, guid: String, token: () -> String?) {
val dir = File(install.folder, ".egstore")
dir.mkdirs()
write(
File(dir, "$guid.mancpn"),
JSONObject().put("FormatVersion", 0).put("AppName", install.appName).put("CatalogItemId", install.catalogItemId)
.put("CatalogNamespace", install.namespace).toString(2),
)
val manifest = File(dir, "$guid.manifest")
if (manifest.isFile && manifest.length() > 0) return
val access = token() ?: return
val info = EpicApiClient.getManifestApiJson(access, install.namespace, install.catalogItemId, install.appName) ?: return
val build = runCatching { JSONObject(info).optString("buildVersion") }.getOrDefault("")
if (install.version.isNotEmpty() && build != install.version) return
val bytes = EpicDownloadManager.downloadManifest(info, EpicDownloadManager.parseCdnUrls(info)) ?: return
val tmp = File(dir, "$guid.manifest.tmp")
tmp.writeBytes(bytes)
if (!tmp.renameTo(manifest)) tmp.delete()
}
private fun write(file: File, text: String) {
if (runCatching { file.readText() }.getOrNull() == text) return
file.parentFile?.mkdirs()
val tmp = File(file.parentFile, file.name + ".tmp")
tmp.writeText(text)
if (!tmp.renameTo(file)) { file.delete(); if (!tmp.renameTo(file)) throw java.io.IOException("could not write ${file.name}") }
}
}
@@ -59,26 +59,41 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.stores.epic.EpicClient
import kotlinx.coroutines.launch
@Composable
internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, onSelect: (String) -> Unit, modifier: Modifier) {
val games = remember(s.steamGames) { s.steamGames.sortedByDescending { it.lastPlayed } }
val pageContext = androidx.compose.ui.platform.LocalContext.current
LaunchedEffect(Unit) { EpicClient.refresh(pageContext) }
val launcherName = stringResource(R.string.epic_client_title)
val epic = EpicClient.status
val launcherArt by androidx.compose.runtime.produceState<java.io.File?>(null, epic.version) {
value = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { EpicClient.icon(pageContext, epic.version) }
}
val games = remember(s.steamGames, s.shortcutPicker, epic, launcherName, launcherArt) {
val sorted = s.steamGames.sortedByDescending { it.lastPlayed }
if (s.shortcutPicker) sorted else EpicClient.withLauncher(sorted, EpicClient.launcherEntry(pageContext, launcherName, epic, launcherArt))
}
val gameCount = games.count { it.library != Library.EPIC_LAUNCHER }
val narrow = LocalNarrowPane.current
val current = games.firstOrNull { "app:${it.appId}" == selected } ?: games.firstOrNull()
GamesDialogs(a, s.steamGames)
val onAdd: (() -> Unit)? = if (s.shortcutPicker) null else ({ GamesDialogState.adding = true })
val pageContext = androidx.compose.ui.platform.LocalContext.current
val launch: (Library.SteamGame) -> Unit = { g -> if (g.library == Library.EPIC_LAUNCHER) a.onEpicLauncher() else a.onSteamGame(g) }
val onEdit: (Library.SteamGame) -> Unit = { g ->
g.gameFiles?.let { GamesDialogState.editing = EditRequest(it.path, openTarget = false, fromSummary = false, preview = EditPreview.of(pageContext, g, it.path)) }
}
if (current == null) {
if (current == null || gameCount == 0) {
Column(modifier = modifier.padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)) {
Rise(0) { PageHeader(stringResource(R.string.content_games)) { onAdd?.let { AddGameButton(it) } } }
Rise(1) { Note(stringResource(if (s.shortcutPicker && s.shortcutLibraryScanning) R.string.game_shortcut_scanning else R.string.games_empty)) }
if (!s.shortcutPicker) Rise(2) {
Actions { PrimaryButton(stringResource(R.string.games_play_steam), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.padding(top = 12.dp).testTag("play-steam"), onClick = a.onPlay) }
Actions {
PrimaryButton(stringResource(R.string.games_play_steam), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.padding(top = 12.dp).testTag("play-steam"), onClick = a.onPlay)
games.firstOrNull { it.library == Library.EPIC_LAUNCHER }?.let { SecondaryButton(it.name, enabled = !s.busy, modifier = Modifier.padding(top = 12.dp)) { a.onEpicLauncher() } }
}
}
GameFileFolderActions(s, a)
}
@@ -87,12 +102,12 @@ internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, o
val host = rememberMenuHost()
if (games.size == 1) {
Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)) {
if (onAdd != null) Rise(0) { GamesHeader(1, onAdd, Modifier.padding(bottom = 10.dp)) }
if (onAdd != null) Rise(0) { GamesHeader(gameCount, onAdd, Modifier.padding(bottom = 10.dp)) }
Rise(0) {
Row(verticalAlignment = Alignment.Bottom) {
GameHero(current, Modifier.weight(1f).heightIn(min = if (narrow) 190.dp else 250.dp)) {
GameHeroCopy(current, if (narrow) 28.sp else 38.sp)
GameActions(current, s, a, onEdit)
GameActions(current, s, a, onEdit, launch)
}
if (!narrow) Poster(current.art, current.name, Modifier.width(168.dp))
}
@@ -105,7 +120,7 @@ internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, o
}
val pal = LocalPalette.current
Row(modifier = modifier) {
GameList(games, current, onSelect = { onSelect("app:${it.appId}") }, onLaunch = { a.onSteamGame(it) }, onAdd = onAdd,
GameList(games, gameCount, current, onSelect = { onSelect("app:${it.appId}") }, onLaunch = launch, onAdd = onAdd,
modifier = Modifier.width(if (narrow) 168.dp else 250.dp).fillMaxHeight())
Box(Modifier.width(1.dp).fillMaxHeight().background(pal.line))
Column(
@@ -114,7 +129,7 @@ internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, o
) {
GameHero(current, Modifier.fillMaxWidth().heightIn(min = if (narrow) 170.dp else 200.dp)) {
GameHeroCopy(current, if (narrow) 24.sp else 32.sp)
GameActions(current, s, a, onEdit)
GameActions(current, s, a, onEdit, launch)
}
SectionTitle(stringResource(R.string.games_launch_settings), null)
LaunchSettings(s, a, host, current)
@@ -142,9 +157,14 @@ private fun GameFileFolderActions(s: FrontEndState, a: FrontEndActions) {
@Composable
private fun GameActions(g: Library.SteamGame, s: FrontEndState, a: FrontEndActions, onEdit: (Library.SteamGame) -> Unit) {
private fun GameActions(g: Library.SteamGame, s: FrontEndState, a: FrontEndActions, onEdit: (Library.SteamGame) -> Unit, launch: (Library.SteamGame) -> Unit) {
Actions {
PrimaryButton(stringResource(if (s.shortcutPicker) R.string.game_shortcut_choose else R.string.games_launch), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow) { a.onSteamGame(g) }
PrimaryButton(stringResource(if (s.shortcutPicker) R.string.game_shortcut_choose else R.string.games_launch), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow) { launch(g) }
if (g.library == Library.EPIC_LAUNCHER) {
if (!s.shortcutPicker) UninstallEpicLauncher(s, a)
BusyChip(s)
return@Actions
}
g.gameFiles?.takeIf { it.isDirectory }?.let { dir ->
SecondaryButton(stringResource(R.string.games_files), compact = true) { a.onBrowseFiles(dir) }
}
@@ -160,6 +180,22 @@ private fun GameActions(g: Library.SteamGame, s: FrontEndState, a: FrontEndActio
}
}
@Composable
private fun UninstallEpicLauncher(s: FrontEndState, a: FrontEndActions) {
var asking by remember { androidx.compose.runtime.mutableStateOf(false) }
SecondaryButton(stringResource(R.string.common_uninstall), enabled = !s.busy, compact = true) { asking = true }
if (asking) {
val body = stringResource(R.string.epic_client_uninstall_body)
ConfirmDialog(
title = stringResource(R.string.stores_uninstall_title, stringResource(R.string.epic_client_title)),
text = if (s.sessionRunning) body + "\n\n" + stringResource(R.string.epic_client_uninstall_stops) else body,
confirm = stringResource(R.string.common_uninstall),
onConfirm = { a.onUninstallEpicLauncher() },
onDismiss = { asking = false },
)
}
}
@Composable
private fun GameShortcutMenu(g: Library.SteamGame, a: FrontEndActions) {
var open by remember(g.gameId) { androidx.compose.runtime.mutableStateOf(false) }
@@ -292,7 +328,7 @@ private fun ColumnScope.GameHeroCopy(g: Library.SteamGame, titleSize: androidx.c
@Composable
private fun GameList(
games: List<Library.SteamGame>, current: Library.SteamGame,
games: List<Library.SteamGame>, count: Int, current: Library.SteamGame,
onSelect: (Library.SteamGame) -> Unit, onLaunch: (Library.SteamGame) -> Unit, onAdd: (() -> Unit)?, modifier: Modifier,
) {
val colors = MaterialTheme.colorScheme
@@ -300,7 +336,7 @@ private fun GameList(
verticalArrangement = Arrangement.spacedBy(2.dp),
modifier = modifier.verticalScroll(rememberScrollState()).padding(start = 12.dp, end = 10.dp, top = 16.dp, bottom = 16.dp),
) {
GamesHeader(games.size, onAdd, Modifier.padding(start = 6.dp, bottom = 10.dp))
GamesHeader(count, onAdd, Modifier.padding(start = 6.dp, bottom = 10.dp))
val seen = remember { HashSet<Int>() }
var settled by remember { androidx.compose.runtime.mutableStateOf(false) }
for (g in games) key(g.appId) {
@@ -462,7 +498,8 @@ private fun GameRow(g: Library.SteamGame, selected: Boolean, onSelect: () -> Uni
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
SourceChip(g.source, small = true)
Text(
playedSpan(g.lastPlayed)?.replaceFirstChar { it.uppercase() } ?: stringResource(R.string.games_never_played),
if (g.library == Library.EPIC_LAUNCHER) libraryLabel(g)
else playedSpan(g.lastPlayed)?.replaceFirstChar { it.uppercase() } ?: stringResource(R.string.games_never_played),
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
@@ -511,6 +548,7 @@ private fun playedSpan(lastPlayed: Long): String? {
@Composable
private fun libraryLabel(g: Library.SteamGame): String = when {
g.library == Library.EPIC_LAUNCHER -> EpicClient.status.version?.substringBefore('+')?.let { stringResource(R.string.epic_client_version, it) } ?: ""
g.library != Library.ADDED -> if (g.library == "internal") stringResource(R.string.games_internal) else g.library
g.source != Library.ADDED -> stringResource(R.string.games_store_storage)
else -> ""
@@ -520,7 +558,7 @@ private fun libraryLabel(g: Library.SteamGame): String = when {
private fun GameHero(g: Library.SteamGame, modifier: Modifier, content: @Composable ColumnScope.() -> Unit) {
val colors = MaterialTheme.colorScheme
Box(modifier = modifier.clip(Shape16).background(artBrush(hueOf(g.name)))) {
val image = g.hero ?: g.art
val image = g.hero ?: g.art.takeIf { g.library != Library.EPIC_LAUNCHER }
if (image != null) AsyncImage(
model = image, contentDescription = null, contentScale = ContentScale.Crop,
modifier = Modifier.matchParentSize()
@@ -166,6 +166,8 @@ class FrontEndActions(
val onSgdbKey: (String) -> Unit = {},
val onStopGameFileSync: () -> Unit = {},
val onCopyGameLink: (Library.SteamGame) -> Unit = {},
val onEpicLauncher: () -> Unit = {},
val onUninstallEpicLauncher: () -> Unit = {},
val onDesktop: () -> Unit,
val onEmulator: (Library.Emulator) -> Unit,
val onFlatpakApp: (String, String) -> Unit = { _, _ -> },
@@ -500,7 +500,11 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
val wincompKey = game?.takeIf { it.library == com.droiddeck.launcher.frontend.Library.ADDED || it.appId > 0 }?.profileKey
var wincompOpen by remember(wincompKey) { mutableStateOf<Boolean?>(null) }
val wincompPicks = remember(wincompKey, wincompOpen) { wincompKey?.let { com.droiddeck.launcher.session.WinComponents.picks(context, it) }.orEmpty() }
val cards = buildList<@Composable (Modifier) -> Unit> {
val steamScope = game?.let { com.droiddeck.launcher.session.NoSteamLaunch.scope(it) }
val steamCard: (@Composable (Modifier) -> Unit)? = if (game != null && steamScope != null) { m ->
Box(m) { GameSettingsCard(host, game, steamScope) }
} else null
val cards = if (game?.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER) listOfNotNull(steamCard) else buildList<@Composable (Modifier) -> Unit> {
add { m ->
val back = stringResource(R.string.hop_from_games)
SettingCard(stringResource(R.string.setup_card_components), stringResource(R.string.setup_card_components_hint), "card:components", m.hopSource("card:components")) {
@@ -518,6 +522,7 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
}
}
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
if (steamCard != null) add(steamCard)
val cardStore = com.droiddeck.launcher.stores.Store.byId(game?.source.orEmpty())?.takeIf { it == com.droiddeck.launcher.stores.Store.EPIC || it == com.droiddeck.launcher.stores.Store.GOG }
if (cardStore != null && game?.gameFiles != null) add { m ->
Box(m) {
@@ -548,6 +553,122 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
}
}
@Composable
private fun GameSettingsCard(host: MenuHost, game: com.droiddeck.launcher.frontend.Library.SteamGame, scope: String) {
val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext
val colors = MaterialTheme.colorScheme
var config by remember(scope) { mutableStateOf(runCatching { com.droiddeck.launcher.session.GameEnvironmentStore.read(appContext) }.getOrNull()) }
var saving by remember(scope) { mutableStateOf(false) }
val current = config
val noSteam = current != null && com.droiddeck.launcher.core.GameEnvironment.gameNoSteam(current, scope)
val fex = current?.let { runCatching { com.droiddeck.launcher.core.GameEnvironment.gameFexPreset(it, scope) }.getOrNull() }
val sync = current?.let { runCatching { com.droiddeck.launcher.core.GameEnvironment.gameSync(it, scope) }.getOrNull() }
val ready = current != null && !saving
val launcher = game.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER
fun save(change: (android.content.Context) -> com.droiddeck.launcher.core.GameEnvironment.Config?) {
if (saving) return
saving = true
Thread({
val written = runCatching { change(appContext) }
.onFailure { android.util.Log.w("GameSettingsCard", "could not save the settings of $scope: ${it.message}") }.getOrNull()
val next = written ?: runCatching { com.droiddeck.launcher.session.GameEnvironmentStore.read(appContext) }.getOrNull()
com.droiddeck.launcher.stores.StoresState.post {
config = next
saving = false
}
}, "game-settings").start()
}
val key = "game-settings"
val fexKey = "game-settings-fex"
val syncKey = "game-settings-sync"
val syncLabels = mapOf(
com.droiddeck.launcher.session.SessionPrefs.SYNC_NTSYNC to stringResource(R.string.sync_backend_ntsync),
com.droiddeck.launcher.session.SessionPrefs.SYNC_FSYNC to stringResource(R.string.sync_backend_fsync),
com.droiddeck.launcher.session.SessionPrefs.SYNC_ESYNC to stringResource(R.string.sync_backend_esync),
com.droiddeck.launcher.session.SessionPrefs.SYNC_WINESERVER to stringResource(R.string.sync_backend_wineserver),
)
val appSync = syncLabels[com.droiddeck.launcher.session.SessionPrefs.syncBackend(appContext)]
val useDefault = stringResource(R.string.comp_game_use_general)
val custom = stringResource(R.string.comp_game_fex_custom)
val customSync = stringResource(R.string.game_sync_custom)
val resetDone = stringResource(R.string.comp_game_reset_done, game.name)
SettingCard(stringResource(R.string.game_settings_card), stringResource(if (noSteam) R.string.game_steam_without else R.string.game_steam_with), "card:$key", Modifier.fillMaxSize()) {
host.open = if (host.open == key) null else key
}
AnchoredMenu(host.open == key, onDismiss = { if (host.open == key) host.open = null }, title = stringResource(R.string.game_settings_menu_title, game.name)) { first ->
MenuItem(stringResource(R.string.game_no_steam_title), checked = noSteam, enabled = ready,
detail = stringResource(R.string.game_no_steam_detail), focusRequester = first) {
val on = !noSteam
save { com.droiddeck.launcher.session.GameEnvironmentStore.setGameNoSteam(it, scope, on) }
}
if (!launcher) {
val chosen = com.droiddeck.launcher.core.FexPreset.all.firstOrNull { it.id == fex }
MenuItem(
stringResource(R.string.fex_preset_title), checked = false, enabled = ready,
detail = when {
fex == null -> useDefault
chosen == null -> custom
else -> stringResource(chosen.label)
},
trailing = { Text("›", fontSize = 16.sp, color = colors.onSurfaceVariant) },
) { host.open = fexKey }
MenuItem(
stringResource(R.string.sync_backend_title), checked = false, enabled = ready,
detail = when (sync) {
null -> useDefault
com.droiddeck.launcher.core.GameEnvironment.CUSTOM_SYNC -> customSync
else -> syncLabels[sync]
},
trailing = { Text("›", fontSize = 16.sp, color = colors.onSurfaceVariant) },
) { host.open = syncKey }
}
MenuItem(stringResource(R.string.game_settings_default), checked = false, enabled = ready,
detail = stringResource(R.string.game_settings_default_detail)) {
save {
val failure = runCatching { com.droiddeck.launcher.session.GameProfileManager.reset(it, scope) }.exceptionOrNull()
com.droiddeck.launcher.stores.StoresState.post {
android.widget.Toast.makeText(
it,
if (failure == null) resetDone else it.getString(R.string.comp_game_reset_failed, failure.message.orEmpty()),
android.widget.Toast.LENGTH_SHORT,
).show()
}
null
}
}
}
AnchoredMenu(host.open == fexKey, onDismiss = { if (host.open == fexKey) host.open = null }, title = stringResource(R.string.fex_preset_title)) { first ->
MenuItem(useDefault, checked = fex == null, enabled = ready, focusRequester = first) {
host.open = key
save { com.droiddeck.launcher.session.GameEnvironmentStore.setGameFexPreset(it, scope, null) }
}
if (fex == com.droiddeck.launcher.core.GameEnvironment.CUSTOM_FEX_PRESET) {
MenuItem(custom, checked = true, enabled = false) {}
}
com.droiddeck.launcher.core.FexPreset.all.forEach { option ->
MenuItem(stringResource(option.label), checked = fex == option.id, enabled = ready, detail = stringResource(option.detail)) {
host.open = key
save { com.droiddeck.launcher.session.GameEnvironmentStore.setGameFexPreset(it, scope, option.id) }
}
}
}
AnchoredMenu(host.open == syncKey, onDismiss = { if (host.open == syncKey) host.open = null }, title = stringResource(R.string.sync_backend_title)) { first ->
MenuItem(useDefault, checked = sync == null, enabled = ready, detail = appSync, focusRequester = first) {
host.open = key
save { com.droiddeck.launcher.session.GameEnvironmentStore.setGameSync(it, scope, null) }
}
if (sync == com.droiddeck.launcher.core.GameEnvironment.CUSTOM_SYNC) {
MenuItem(customSync, checked = true, enabled = false) {}
}
com.droiddeck.launcher.core.GameEnvironment.syncBackends.forEach { option ->
MenuItem(syncLabels.getValue(option), checked = sync == option, enabled = ready) {
host.open = key
save { com.droiddeck.launcher.session.GameEnvironmentStore.setGameSync(it, scope, option) }
}
}
}
}
private const val EPIC_RESOLVE_URL = "https://www.epicgames.com/id/login?redirectUrl=https%3A%2F%2Fwww.epicgames.com%2Faccount%2Fpersonal"
@Composable
@@ -299,6 +299,15 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
s.zramCompression && s.zramSupported != false, enabled = s.zramSupported == true,
onChange = a.onZramCompression,
)
if (s.syncBackend != null) ChoiceRow(
host, "sync", stringResource(R.string.sync_backend_title), stringResource(R.string.sync_backend_hint),
listOf(
SessionPrefs.SYNC_NTSYNC to stringResource(R.string.sync_backend_ntsync),
SessionPrefs.SYNC_FSYNC to stringResource(R.string.sync_backend_fsync),
SessionPrefs.SYNC_ESYNC to stringResource(R.string.sync_backend_esync),
SessionPrefs.SYNC_WINESERVER to stringResource(R.string.sync_backend_wineserver),
), s.syncBackend, onPick = a.onSyncBackend,
)
}
if (s.pipSupported) SettingsGroup(stringResource(R.string.pip_title)) {
ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto), null,
@@ -15,6 +15,10 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
@@ -22,6 +26,7 @@ import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
@@ -309,6 +314,39 @@ internal fun StepChoice(
}
}
@Composable
internal fun StepTile(
label: String,
icon: ImageVector,
modifier: Modifier = Modifier,
detail: String? = null,
warning: Boolean = false,
enabled: Boolean = true,
onClick: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(18.dp)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = modifier.width(184.dp).height(IntrinsicSize.Min).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface.copy(alpha = 0.5f))
.glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, role = Role.Button, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = 12.dp, vertical = 10.dp),
) {
Icon(icon, null, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.fillMaxHeight().aspectRatio(1f))
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (detail != null) Text(detail, fontSize = 12.sp, color = if (warning) colors.error else colors.onSurfaceVariant, maxLines = 2)
}
}
}
@Composable
internal fun StepOutScope.StepTitle(text: String) {
Text(
@@ -89,6 +89,7 @@ import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.download.DownloadState
import com.droiddeck.launcher.stores.download.StoreDownloadTier
import com.droiddeck.launcher.stores.epic.EpicClient
import com.droiddeck.launcher.stores.formatBytes
import com.droiddeck.launcher.stores.formatSpeed
@@ -215,7 +216,7 @@ private fun FinishedRow(d: DownloadEntry, s: FrontEndState, a: FrontEndActions,
Text(stringResource(if (d.state == DownloadState.INSTALLED) R.string.stores_installed_chip else R.string.stores_dl_cancelled), fontSize = 12.sp, color = Color.White.copy(alpha = 0.72f), maxLines = 1)
Spacer(Modifier.weight(1f))
if (d.state == DownloadState.INSTALLED) Box(Modifier.bloomIn(bloom, GATHER_HOLD_MS + 150)) {
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { launchStoreGame(ctx, d.store, d.id, s, a) }
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else launchStoreGame(ctx, d.store, d.id, s, a) }
}
}
}
@@ -366,7 +367,7 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
CancelAction { DownloadQueue.clear(ctx, d.key) }
}
DownloadState.INSTALLED -> Box(Modifier.bloomIn(true, 420)) {
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { launchStoreGame(ctx, d.store, d.id, s, a) }
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else launchStoreGame(ctx, d.store, d.id, s, a) }
}
DownloadState.CANCELLED -> {}
}
@@ -11,8 +11,13 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Folder
import androidx.compose.material.icons.outlined.SdCard
import androidx.compose.material.icons.outlined.Smartphone
import androidx.compose.material3.Icon
@@ -51,7 +56,7 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
val defaultIndex = targets.indexOfFirst { it.root.absolutePath == remembered }.coerceAtLeast(0)
val focus = remember { List(targets.size) { FocusRequester() } }
LaunchedEffect(Unit) { focusWithinFrames({ false }) { focus[defaultIndex] } }
AppDialog(shown, close, "installWhere", wide = false, maxWidth = 440.dp) {
AppDialog(shown, close, "installWhere", wide = false, maxWidth = if (targets.size > 2) 600.dp else 440.dp) {
Rise(0) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
Text(
@@ -65,7 +70,7 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
}
}
Rise(1) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
targets.forEachIndexed { i, t ->
val needed = com.droiddeck.launcher.stores.StoreInstallRoot.estimatedBytesNeeded(item)
val freeBytes = t.freeBytes
@@ -80,8 +85,8 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
TargetRow(
label = if (t.removable) t.label else stringResource(R.string.stores_target_internal),
free = freeText,
removable = t.removable, focus = focus[i],
warning = isLow,
removable = t.removable, folder = t.folder, focus = focus[i],
warning = isLow, modifier = Modifier.weight(1f),
) {
SessionPrefs.setStoresInstallTarget(ctx, t.root.absolutePath)
StoresState.install(ctx, item, t.root)
@@ -94,22 +99,24 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
}
@Composable
private fun TargetRow(label: String, free: String, removable: Boolean, focus: FocusRequester, warning: Boolean = false, onPick: () -> Unit) {
private fun TargetRow(label: String, free: String, removable: Boolean, folder: Boolean, focus: FocusRequester, modifier: Modifier, warning: Boolean = false, onPick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp),
modifier = Modifier.fillMaxWidth().focusRequester(focus).clip(Shape12)
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = modifier.height(IntrinsicSize.Min).focusRequester(focus).clip(Shape12)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface.copy(alpha = 0.6f))
.glideBorder(hot, Shape12, pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onPick)
.controllerConfirm(onClick = onPick)
.padding(horizontal = 14.dp, vertical = 10.dp),
.padding(horizontal = 12.dp, vertical = 10.dp),
) {
Icon(if (removable) Icons.Outlined.SdCard else Icons.Outlined.Smartphone, null, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(22.dp))
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
Text(free, fontSize = 12.sp, color = if (warning) colors.error else colors.onSurfaceVariant, maxLines = 1)
Icon(if (folder) Icons.Outlined.Folder else if (removable) Icons.Outlined.SdCard else Icons.Outlined.Smartphone, null, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.fillMaxHeight().aspectRatio(1f))
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(free, fontSize = 12.sp, color = if (warning) colors.error else colors.onSurfaceVariant, maxLines = 2)
}
}
}
@@ -12,6 +12,7 @@ import androidx.compose.animation.togetherWith
import androidx.compose.animation.core.Animatable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.icons.outlined.Folder
import androidx.compose.material.icons.outlined.SdCard
import androidx.compose.material.icons.outlined.Smartphone
import androidx.compose.runtime.CompositionLocalProvider
@@ -27,6 +28,7 @@ import androidx.compose.ui.layout.boundsInParent
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.positionInRoot
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.epic.EpicClient
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@@ -176,6 +178,16 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
val grids = remember { HashMap<PaneKey, LazyGridState>() }
val grid = grids.getOrPut(pane) { LazyGridState() }
LaunchedEffect(Unit) { StoresState.refresh(ctx) }
val lifecycle = androidx.compose.ui.platform.LocalLifecycleOwner.current.lifecycle
LaunchedEffect(chip) {
if (chip == Store.EPIC.id) {
EpicClient.ensure(ctx)
while (true) {
delay(5_000)
if (lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) EpicClient.refresh(ctx)
}
}
}
LaunchedEffect(chip, StoresState.accounts[store]) { if (store != null && StoresState.isSignedIn(store)) StoresState.open(ctx, store) }
val ff = LocalFrontFocus.current
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
@@ -425,7 +437,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
StepOut(
open = StoresMotion.stepOpen, pill = ask.anchor.translate(-hostAt), side = ask.side, accent = ask.accent,
onDismiss = { StoresMotion.fold() }, onClosed = { StoresMotion.closed(ask) },
pillCorner = ask.pillCorner, items = ask.items, handle = ask.handle, content = ask.content,
pillCorner = ask.pillCorner, maxWidth = ask.maxWidth, items = ask.items, handle = ask.handle, content = ask.content,
)
}
}
@@ -457,11 +469,12 @@ private fun InstallWhere(item: CatalogItem) {
val defaultIndex = targets.indexOfFirst { it.root.absolutePath == remembered }.coerceAtLeast(0)
StoresMotion.ask(StepAsk(
anchor = from, side = StepSide.Right, accent = pal.signal, pillCorner = 12.dp, items = 1 + targets.size,
maxWidth = (28 + 192 * targets.size - 8).dp,
onDismiss = { if (StoresState.pendingInstall === item) StoresState.pendingInstall = null },
handle = { Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1) },
) {
StepTitle(title)
StepList {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
targets.forEachIndexed { i, t ->
val needed = com.droiddeck.launcher.stores.StoreInstallRoot.estimatedBytesNeeded(item)
val freeBytes = t.freeBytes
@@ -473,12 +486,13 @@ private fun InstallWhere(item: CatalogItem) {
} else {
stringResource(R.string.stores_target_free, formatBytes(freeBytes))
}
StepChoice(
StepTile(
label = if (t.removable) t.label else internalLabel,
icon = if (t.removable) androidx.compose.material.icons.Icons.Outlined.SdCard else androidx.compose.material.icons.Icons.Outlined.Smartphone,
trailing = trailingText,
icon = if (t.folder) androidx.compose.material.icons.Icons.Outlined.Folder else if (t.removable) androidx.compose.material.icons.Icons.Outlined.SdCard else androidx.compose.material.icons.Icons.Outlined.Smartphone,
detail = trailingText,
warning = isLow,
enabled = open,
modifier = Modifier.fillMaxWidth().stepItem(1 + i).then(if (i == defaultIndex) Modifier.focusRequester(first) else Modifier),
modifier = Modifier.stepItem(1 + i).then(if (i == defaultIndex) Modifier.focusRequester(first) else Modifier),
) {
SessionPrefs.setStoresInstallTarget(ctx, t.root.absolutePath)
StoresMotion.markInstall(from, label)
@@ -889,6 +903,10 @@ private fun Storefront(
SortButton(s, a)
ViewButton(s, a)
}
if (store == Store.EPIC) SmallTextButton(stringResource(R.string.epic_client_title)) {
if (EpicClient.status.installed) a.onEpicLauncher()
else { EpicClient.install(ctx); StoresState.openDownloads = true }
}
SmallTextButton(stringResource(R.string.stores_refresh)) { StoresState.open(ctx, store, force = true) }
val name = StoresState.accounts[store] ?: ""
SignOutButton(store, name)