mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1d62f44a0 | ||
|
|
34c8025591 | ||
|
|
d7f43c26cd | ||
|
|
d5c83eae15 | ||
|
|
83dc5f37e9 | ||
|
|
d0022a35f9 | ||
|
|
acb2cba970 | ||
|
|
e58b463f54 |
No files matched your search
@@ -588,7 +588,7 @@ jobs:
|
||||
path: |
|
||||
~/.cache/droiddeck-pack-inputs
|
||||
~/.cache/droiddeck-build
|
||||
key: pack-inputs-v2-${{ hashFiles('tools/packs/build.sh', 'tools/packs/fetch-verified.sh', 'tools/packs/tracking/release.env', 'tools/powervr/release.json') }}
|
||||
key: pack-inputs-v2-${{ hashFiles('tools/packs/build.sh', 'tools/packs/fetch-verified.sh', 'tools/packs/tracking/release.env', 'tools/packs/zstd/release.env', 'tools/powervr/release.json') }}
|
||||
restore-keys: pack-inputs-v2-
|
||||
- name: Build the add-on packs
|
||||
run: |
|
||||
|
||||
@@ -302,15 +302,6 @@
|
||||
android:resizeableActivity="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
|
||||
|
||||
<activity
|
||||
android:name=".session.KeepTopActivity"
|
||||
android:exported="false"
|
||||
android:excludeFromRecents="true"
|
||||
android:noHistory="true"
|
||||
android:taskAffinity="${applicationId}.keeptop"
|
||||
android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"
|
||||
android:resizeableActivity="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
|
||||
<activity
|
||||
android:name=".ui.SessionTypingActivity"
|
||||
android:exported="false"
|
||||
|
||||
@@ -260,7 +260,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private var steamController: SteamControllerBle? = null
|
||||
private var onScreenControls: OnScreenControls? = null
|
||||
private var bottomInputControls: OnScreenControls? = null
|
||||
private var primaryInputLayout: com.droiddeck.launcher.input.SavedInputLayout? = null
|
||||
private var primaryInputLayout by mutableStateOf<com.droiddeck.launcher.input.SavedInputLayout?>(null)
|
||||
private var secondaryInputLayout by mutableStateOf<com.droiddeck.launcher.input.SavedInputLayout?>(null)
|
||||
private var steamTouchControls: com.droiddeck.launcher.input.SteamTouchControls? = null
|
||||
private var steamTouchAvailable by mutableStateOf(false)
|
||||
@@ -643,9 +643,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
|
||||
private var steamDownloadsInBackground by mutableStateOf(false)
|
||||
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
|
||||
private var oscRearButtons by mutableStateOf(false)
|
||||
private var oscTrackpads by mutableStateOf(false)
|
||||
private var onScreenButtonsVisible by mutableStateOf(false)
|
||||
private var layoutOptions by mutableStateOf<List<Pair<String, String>>>(emptyList())
|
||||
private var layoutOptions by mutableStateOf<List<com.droiddeck.launcher.input.ControlsChoice.Option>>(emptyList())
|
||||
private var layoutChoice by mutableStateOf("")
|
||||
private var layoutHint by mutableStateOf<String?>(null)
|
||||
private var layoutEditor by mutableStateOf<Triple<String, String, String>?>(null)
|
||||
private var layoutEditorScope: String? = null
|
||||
private var layoutEditorSplit: com.droiddeck.launcher.ui.InputEditorSplit? = null
|
||||
@@ -1744,7 +1747,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
layoutGame = controlsGameName(),
|
||||
layoutOptions = layoutOptions,
|
||||
layoutChoice = layoutChoice,
|
||||
layoutHint = layoutHint,
|
||||
onLayout = ::chooseLayout,
|
||||
onDeleteLayout = ::deleteLayout,
|
||||
oscRearButtons = oscRearButtons.takeIf {
|
||||
unfoldedPanel == null && !usesSteamTouchLayout() && com.droiddeck.launcher.input.PadKit.current(this).steam &&
|
||||
primaryInputLayout?.let(com.droiddeck.launcher.input.OnScreenLayout::hasBuiltInKit) == true
|
||||
},
|
||||
oscTrackpads = oscTrackpads,
|
||||
onOscRearButtons = { shown ->
|
||||
SessionPrefs.setOscRearButtons(this, shown)
|
||||
oscRearButtons = shown
|
||||
onScreenControls?.reload()
|
||||
bottomInputControls?.reload()
|
||||
},
|
||||
onOscTrackpads = { shown ->
|
||||
SessionPrefs.setOscTrackpads(this, shown)
|
||||
oscTrackpads = shown
|
||||
onScreenControls?.reload()
|
||||
bottomInputControls?.reload()
|
||||
},
|
||||
onEditLayout = when {
|
||||
layoutChoice == com.droiddeck.launcher.input.GameControls.STEAM -> steamTouchControls?.takeIf { steamTouchAvailable && onScreenButtonsVisible && it.visibility == View.VISIBLE }?.let { view -> {
|
||||
drawerOpen = false
|
||||
@@ -2556,6 +2578,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
|
||||
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
|
||||
oscMode = sessionOscMode()
|
||||
oscRearButtons = SessionPrefs.oscRearButtons(this)
|
||||
oscTrackpads = SessionPrefs.oscTrackpads(this)
|
||||
backHold = SessionPrefs.backHold(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
physicalShortcuts.bindings = PhysicalShortcuts.read(this)
|
||||
@@ -3230,8 +3254,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
private fun onSessionEnded(status: Int) {
|
||||
ended = true
|
||||
uiHandler.removeCallbacks(guardWhenRunning)
|
||||
com.droiddeck.launcher.session.KeepTopActivity.release()
|
||||
++steamVrRequestGeneration
|
||||
if (isInPictureInPictureMode) {
|
||||
runOnUiThread { finish() }
|
||||
@@ -4413,8 +4435,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private fun refreshLayoutOptions() {
|
||||
val steam = SessionState.mode == SessionService.MODE_STEAM
|
||||
val game = controlsGameId()
|
||||
layoutOptions = com.droiddeck.launcher.input.ControlsChoice.options(this, game, steam, controlsGameName())
|
||||
layoutChoice = com.droiddeck.launcher.input.ControlsChoice.current(this, game, steam, loadingMode() == SessionService.MODE_DESKTOP)
|
||||
val desktop = loadingMode() == SessionService.MODE_DESKTOP
|
||||
layoutOptions = com.droiddeck.launcher.input.ControlsChoice.options(this, game, steam, controlsGameName(), desktop)
|
||||
layoutChoice = com.droiddeck.launcher.input.ControlsChoice.current(this, game, steam, desktop)
|
||||
layoutHint = if (com.droiddeck.launcher.input.ControlsChoice.steamUnavailable(this, game, steam)) getString(R.string.osc_layout_steam_unavailable) else null
|
||||
}
|
||||
|
||||
private fun deleteLayout(id: String) {
|
||||
runCatching { com.droiddeck.launcher.input.ControlsChoice.delete(this, id) }.onFailure { Log.w(TAG, "could not delete layout $id", it) }
|
||||
refreshLayoutOptions()
|
||||
}
|
||||
|
||||
private fun chooseLayout(id: String) {
|
||||
@@ -5719,11 +5748,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
override fun onPictureInPictureModeChanged(inPip: Boolean, newConfig: android.content.res.Configuration) {
|
||||
super.onPictureInPictureModeChanged(inPip, newConfig)
|
||||
if (inPip) {
|
||||
uiHandler.removeCallbacks(guardWhenRunning)
|
||||
uiHandler.removeCallbacks(rearmAfterYield)
|
||||
com.droiddeck.launcher.session.KeepTopActivity.stepAside()
|
||||
}
|
||||
if (::pip.isInitialized) pip.changed(inPip)
|
||||
if (!inPip && surfaceW > 0) resizeOutputForWindow(surfaceW, surfaceH)
|
||||
applyUnfoldedControls()
|
||||
@@ -5732,8 +5756,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
|
||||
if (::pip.isInitialized && intent.component?.className != com.droiddeck.launcher.session.KeepTopActivity::class.java.name &&
|
||||
(requestCode >= 0 || intent.component?.packageName == packageName ||
|
||||
if (::pip.isInitialized && (requestCode >= 0 || intent.component?.packageName == packageName ||
|
||||
intent.action in setOf(Intent.ACTION_CHOOSER, Intent.ACTION_SEND, Intent.ACTION_OPEN_DOCUMENT,
|
||||
Intent.ACTION_GET_CONTENT, "android.settings.PICTURE_IN_PICTURE_SETTINGS"))) pip.background()
|
||||
super.startActivityForResult(intent, requestCode, options)
|
||||
@@ -5765,10 +5788,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
if (lightPause.stopped()) departureCleanup()
|
||||
uiHandler.removeCallbacks(guardWhenRunning)
|
||||
uiHandler.removeCallbacks(rearmAfterYield)
|
||||
com.droiddeck.launcher.session.KeepTopActivity.stepAside()
|
||||
if (runtimeRemovalBlocked) { super.onStop(); return }
|
||||
started = false
|
||||
if (::hud.isInitialized) hud.setBackgrounded(true)
|
||||
@@ -5813,13 +5832,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
com.droiddeck.launcher.session.KeepTopActivity.onYield = onGuardYield
|
||||
uiHandler.removeCallbacks(lightPauseCheck)
|
||||
when (lightPause.resumed(com.droiddeck.launcher.session.KeepTopActivity.bounces)) {
|
||||
com.droiddeck.launcher.session.LightPause.Resume.LIGHT -> return
|
||||
com.droiddeck.launcher.session.LightPause.Resume.CLEANUP_FIRST -> departureCleanup()
|
||||
com.droiddeck.launcher.session.LightPause.Resume.NORMAL -> Unit
|
||||
}
|
||||
drawerGameInventoryRevision++
|
||||
com.droiddeck.launcher.input.SystemKeyCapture.attach(this, { hasWindowFocus() && !appUiOwnsPointer() && CompositorHost.isStarted }) { event ->
|
||||
com.droiddeck.launcher.input.GuestKeys.send(event) { code, down -> sendGuestKey(code, down, 8) }
|
||||
@@ -5885,73 +5897,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(cardboardPrefListener)
|
||||
}
|
||||
|
||||
private var memoryPressureAt = 0L
|
||||
private var focusBounce = false
|
||||
private val lightPause = com.droiddeck.launcher.session.LightPause()
|
||||
private val lightPauseCheck = Runnable { if (lightPause.timedOut()) departureCleanup() }
|
||||
private var topResumed = false
|
||||
private val guardWhenRunning = object : Runnable {
|
||||
override fun run() {
|
||||
if (!topResumed || isFinishing) return
|
||||
if (SessionState.running) guardOtherDisplays() else uiHandler.postDelayed(this, 2_000)
|
||||
}
|
||||
}
|
||||
|
||||
// A touch that removed a guard while the session kept the top spot did not move focus to that
|
||||
// display, so the guard comes back unless the user carries on there.
|
||||
private val rearmAfterYield = Runnable {
|
||||
if (topResumed && !isFinishing) {
|
||||
com.droiddeck.launcher.session.KeepTopActivity.rearm()
|
||||
guardOtherDisplays()
|
||||
}
|
||||
}
|
||||
private val onGuardYield: () -> Unit = {
|
||||
uiHandler.removeCallbacks(rearmAfterYield)
|
||||
uiHandler.postDelayed(rearmAfterYield, com.droiddeck.launcher.session.KeepTopActivity.YIELD_GRACE_MS)
|
||||
}
|
||||
|
||||
// RUNNING_LOW and RUNNING_CRITICAL are not delivered from API 34, so the guard also goes up
|
||||
// as soon as a running session is on top.
|
||||
override fun onTrimMemory(level: Int) {
|
||||
super.onTrimMemory(level)
|
||||
if (!com.droiddeck.launcher.session.TopUnderPressure.isPressure(level)) return
|
||||
memoryPressureAt = android.os.SystemClock.elapsedRealtime()
|
||||
guardOtherDisplays()
|
||||
}
|
||||
|
||||
override fun onTopResumedActivityChanged(isTopResumedActivity: Boolean) {
|
||||
super.onTopResumedActivityChanged(isTopResumedActivity)
|
||||
topResumed = isTopResumedActivity
|
||||
uiHandler.removeCallbacks(guardWhenRunning)
|
||||
uiHandler.removeCallbacks(rearmAfterYield)
|
||||
if (isTopResumedActivity) {
|
||||
com.droiddeck.launcher.session.KeepTopActivity.rearm()
|
||||
uiHandler.post(guardWhenRunning)
|
||||
}
|
||||
else if (com.droiddeck.launcher.session.TopUnderPressure.shouldReclaim(
|
||||
android.os.SystemClock.elapsedRealtime(), memoryPressureAt, SessionState.running, isFinishing)) guardOtherDisplays()
|
||||
}
|
||||
|
||||
private fun guardOtherDisplays() {
|
||||
if (!SessionState.running || isFinishing || isInPictureInPictureMode) return
|
||||
val wasResumed = lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)
|
||||
val bounced = com.droiddeck.launcher.session.KeepTopActivity.guardOtherDisplays(this, display?.displayId ?: android.view.Display.DEFAULT_DISPLAY)
|
||||
if (com.droiddeck.launcher.session.KeepTopActivity.hasPendingStarts()) {
|
||||
uiHandler.removeCallbacks(guardWhenRunning)
|
||||
uiHandler.postDelayed(guardWhenRunning, com.droiddeck.launcher.session.KeepTopActivity.RETRY_MS)
|
||||
}
|
||||
if (!bounced) return
|
||||
if (!wasResumed) return
|
||||
focusBounce = true
|
||||
uiHandler.postDelayed({ focusBounce = false }, 500)
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
if (focusBounce) {
|
||||
focusBounce = false
|
||||
lightPause.paused(com.droiddeck.launcher.session.KeepTopActivity.bounces)
|
||||
uiHandler.postDelayed(lightPauseCheck, 200)
|
||||
} else departureCleanup()
|
||||
departureCleanup()
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
@@ -6614,10 +6561,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
uiHandler.removeCallbacks(guardWhenRunning)
|
||||
uiHandler.removeCallbacks(rearmAfterYield)
|
||||
if (com.droiddeck.launcher.session.KeepTopActivity.onYield === onGuardYield) com.droiddeck.launcher.session.KeepTopActivity.onYield = null
|
||||
com.droiddeck.launcher.session.KeepTopActivity.release()
|
||||
synchronized(frameGenGlobalLock) {
|
||||
frameGenActivityActive = false
|
||||
frameGenRequests.incrementAndGet()
|
||||
|
||||
@@ -24,14 +24,84 @@ object ControlsChoice {
|
||||
return if (chosen == null) library else library.selectPart(desktop, InputRole.PRIMARY, chosen)
|
||||
}
|
||||
|
||||
fun options(context: Context, game: Long?, steamMode: Boolean, gameName: String? = null): List<Pair<String, String>> {
|
||||
data class Option(val id: String, val name: String, val detail: String? = null, val deletable: Boolean = false)
|
||||
|
||||
/** Layouts made for one game, so they're listed only for that game. Layouts made before that was recorded are recognised by carrying the name of the game that draws them. */
|
||||
private fun owners(context: Context, library: InputLibrary): Map<String, Set<Long>> {
|
||||
val named = GameControls.games(context).mapNotNull { game ->
|
||||
val layout = own(library, GameControls.bindings(context, game))?.let { library.preset(it).layoutId } ?: return@mapNotNull null
|
||||
val name = GameControls.name(context, game) ?: return@mapNotNull null
|
||||
(layout to game).takeIf { library.layouts.any { it.id == layout && it.name == name } }
|
||||
}
|
||||
return (named + GameControls.madeFor(context).toList()).groupBy({ it.first }, { it.second }).mapValues { it.value.toSet() }
|
||||
}
|
||||
|
||||
private fun defaults(library: InputLibrary) =
|
||||
listOf(false, true).mapNotNull { library.activeLayout(it, InputRole.PRIMARY)?.id }.toSet()
|
||||
|
||||
private fun deletable(context: Context, library: InputLibrary, layout: SavedInputLayout): Boolean {
|
||||
if (!layout.editable || layout.id == InputLibraries.OVERLAY || layout.id in defaults(library)) return false
|
||||
if (GameControls.games(context).any { game -> own(library, GameControls.bindings(context, game))?.let { library.preset(it).layoutId } == layout.id }) return false
|
||||
return library.profiles.none { p -> p.parts.any { (role, part) -> part.layout == layout.id && drawn(library, p.id, role) } } &&
|
||||
library.bindings.none { it.layoutId == layout.id && library.selectedBindings(it.id) }
|
||||
}
|
||||
|
||||
/** Whether [profile]'s [role] part is what a mode shows, rather than one a choice made since covers. */
|
||||
private fun drawn(library: InputLibrary, profile: String, role: InputRole) =
|
||||
listOf(false, true).any { desktop -> library.activeId(desktop) == profile && library.selection(desktop).parts[role] == null }
|
||||
|
||||
private fun keeps(library: InputLibrary, profile: String) =
|
||||
profile == InputProfile.GAME || profile == InputProfile.DESKTOP || listOf(false, true).any { library.activeId(it) == profile }
|
||||
|
||||
fun options(context: Context, game: Long?, steamMode: Boolean, gameName: String? = null, desktop: Boolean = false): List<Option> {
|
||||
val library = InputLibraries.read(context)
|
||||
val own = game != null && game in GameControls.games(context)
|
||||
return (if (own) listOf(DEFAULT to context.getString(R.string.osc_default)) else emptyList()) +
|
||||
listOf(InputLibraries.OVERLAY to context.getString(R.string.osc_layout_gamepad)) +
|
||||
(if (steamMode) listOf(GameControls.STEAM to context.getString(R.string.osc_layout_steam)) else emptyList()) +
|
||||
library.layouts.filter { it.editable && it.supports(InputRole.PRIMARY) && it.id != InputLibraries.OVERLAY }.map { it.id to it.name } +
|
||||
(if (game != null && !gameName.isNullOrBlank()) listOf(NEW to context.getString(R.string.osc_layout_new_for, gameName)) else emptyList())
|
||||
val current = current(context, game, steamMode, desktop)
|
||||
val owners = owners(context, library)
|
||||
val defaults = defaults(library)
|
||||
val forGame = gameName?.takeIf { game != null && it.isNotBlank() }
|
||||
val saved = library.layouts.filter { it.editable && it.supports(InputRole.PRIMARY) && it.id != InputLibraries.OVERLAY }
|
||||
.filter { l -> l.id == current || l.id in defaults || owners[l.id].isNullOrEmpty() || game in owners[l.id].orEmpty() }
|
||||
.map { l ->
|
||||
val mine = game != null && game in owners[l.id].orEmpty() && l.id !in defaults
|
||||
Option(l.id, l.name, if (mine && forGame != null) context.getString(R.string.osc_layout_detail_game, forGame) else null,
|
||||
l.id != current && deletable(context, library, l))
|
||||
}
|
||||
return (if (own) listOf(Option(DEFAULT, context.getString(R.string.osc_default))) else emptyList()) +
|
||||
Option(InputLibraries.OVERLAY, context.getString(R.string.osc_layout_gamepad), context.getString(R.string.osc_layout_gamepad_detail)) +
|
||||
(if (steamMode) listOf(Option(GameControls.STEAM, context.getString(R.string.osc_layout_steam), context.getString(R.string.osc_layout_steam_detail))) else emptyList()) +
|
||||
saved +
|
||||
(if (forGame != null) listOf(Option(NEW, context.getString(R.string.osc_layout_new_for, forGame))) else emptyList())
|
||||
}
|
||||
|
||||
/** Whether [game] chose Steam's touch controls but runs where they can't be shown. */
|
||||
fun steamUnavailable(context: Context, game: Long?, steamMode: Boolean) = !steamMode && GameControls.steamLayout(context, game)
|
||||
|
||||
/** Deletes the saved layout [id] and its actions. A profile that can no longer be chosen goes with it; one that can falls back to the stock layout. */
|
||||
fun delete(context: Context, id: String) {
|
||||
val games = GameControls.games(context).mapNotNull { GameControls.bindings(context, it) }.toSet()
|
||||
InputLibraries.update(context) { library ->
|
||||
val layout = library.layouts.first { it.id == id }
|
||||
require(deletable(context, library, layout))
|
||||
val users = library.usersOfLayout(id)
|
||||
val orphans = users.filterNot { keeps(library, it.id) }
|
||||
var result = users.filter { keeps(library, it.id) }.fold(library) { acc, p ->
|
||||
p.parts.filterValues { it.layout == id }.keys.fold(acc) { lib, role ->
|
||||
lib.chooseLayout(p.id, role, when {
|
||||
role == InputRole.PRIMARY -> InputLibraries.OVERLAY
|
||||
p.base == InputProfile.DESKTOP -> InputLibraries.TRACKPAD
|
||||
else -> InputLibraries.DECK
|
||||
})
|
||||
}
|
||||
}
|
||||
result = orphans.fold(result) { acc, p -> acc.removeProfile(p.id) }
|
||||
val loose = orphans.flatMap { p -> p.parts.values.map { it.bindings } }.toSet()
|
||||
.filter { b -> b !in games && result.usersOfBindings(b).isEmpty() && !result.selectedBindings(b) && result.bindings.any { it.id == b } }
|
||||
.filterNot { b -> InputStockLayouts.presets(InputStockLayouts.layouts()).any { it.id == b } }
|
||||
result = loose.fold(result) { acc, b -> acc.removeBindings(b) }
|
||||
result.removeLayout(id)
|
||||
}
|
||||
GameControls.forgetLayout(context, id)
|
||||
}
|
||||
|
||||
fun current(context: Context, game: Long?, steamMode: Boolean, desktop: Boolean = false): String =
|
||||
@@ -61,6 +131,7 @@ object ControlsChoice {
|
||||
val layoutId = newInputId()
|
||||
val bindingsId = newInputId()
|
||||
InputLibraries.update(context) { latest -> copyForGame(context, latest, game, name, desktop, layoutId, bindingsId) }
|
||||
GameControls.markMadeFor(context, layoutId, game)
|
||||
GameControls.choose(context, game, bindingsId, steam = false, name = name)
|
||||
return layoutId to bindingsId
|
||||
}
|
||||
@@ -80,7 +151,10 @@ object ControlsChoice {
|
||||
}
|
||||
|
||||
/** Uses [bindingsId], made by [copyForGame], for [game] only. */
|
||||
fun useForGame(context: Context, game: Long, name: String, bindingsId: String) = GameControls.choose(context, game, bindingsId, steam = false, name = name)
|
||||
fun useForGame(context: Context, game: Long, name: String, bindingsId: String) {
|
||||
InputLibraries.read(context).bindings.firstOrNull { it.id == bindingsId }?.layoutId?.let { GameControls.markMadeFor(context, it, game) }
|
||||
GameControls.choose(context, game, bindingsId, steam = false, name = name)
|
||||
}
|
||||
|
||||
/** The profile, layout and actions the editor opens for [game], or null when its layout can't be edited here. */
|
||||
fun editTarget(context: Context, game: Long?, desktop: Boolean): Triple<String, String, String>? {
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.droiddeck.launcher.session.SessionPrefs
|
||||
/** Which on-screen layout each game uses. Games without a choice use the default profile's main-screen layout. */
|
||||
object GameControls {
|
||||
const val STEAM = "steam"
|
||||
private const val MADE_FOR = "layout-for."
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("game-controls", Context.MODE_PRIVATE)
|
||||
|
||||
@@ -28,6 +29,15 @@ object GameControls {
|
||||
.filter { it.endsWith(".steam") || it.endsWith(".bindings") }
|
||||
.mapNotNull { it.substringBeforeLast('.').toLongOrNull() }.distinct().sorted()
|
||||
|
||||
/** Layouts made for one game, by layout id. */
|
||||
fun madeFor(context: Context): Map<String, Long> = prefs(context).all.mapNotNull { (key, value) ->
|
||||
if (key.startsWith(MADE_FOR) && value is Long) key.removePrefix(MADE_FOR) to value else null
|
||||
}.toMap()
|
||||
|
||||
fun markMadeFor(context: Context, layout: String, game: Long) { prefs(context).edit().putLong(MADE_FOR + layout, game).apply() }
|
||||
|
||||
fun forgetLayout(context: Context, layout: String) { prefs(context).edit().remove(MADE_FOR + layout).apply() }
|
||||
|
||||
fun name(context: Context, game: Long): String? = prefs(context).getString("$game.name", null)
|
||||
|
||||
fun clear(context: Context, game: Long) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Rect
|
||||
import android.graphics.RectF
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
@@ -18,6 +19,12 @@ object KitLayout {
|
||||
/** Whether [id] names one of a kit's own controls rather than a key or control the player added. */
|
||||
fun isKit(id: String) = id.startsWith("legacy:") || id == DPAD_ID || id == KEYBOARD_ID
|
||||
|
||||
internal fun visibleOnOverlay(control: InputControl, rearButtons: Boolean, trackpads: Boolean): Boolean = when (control) {
|
||||
InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5 -> rearButtons
|
||||
InputControl.LEFT_PAD, InputControl.RIGHT_PAD -> trackpads
|
||||
else -> true
|
||||
}
|
||||
|
||||
/** The control a kit id stands for in a layout that keeps no kit positions, so bindings saved for it stay valid. */
|
||||
fun element(id: String): InputSurfaceElement? = when {
|
||||
id == DPAD_ID -> InputSurfaceElement(InputControl.LS, 0f, 0f, .1f, .1f, id, InputElementKind.DPAD)
|
||||
@@ -72,22 +79,24 @@ object KitLayout {
|
||||
dpad(220f, 345f, 150f)) + face(1375f, 345f, 58f, 96f) + listOf(
|
||||
Spec(InputControl.LS, 290f, 640f, 96f), Spec(InputControl.RS, 1310f, 640f, 96f),
|
||||
Spec(InputControl.LEFT_PAD, 470f, 360f, 88f, shape = InputButtonShape.ROUNDED), Spec(InputControl.RIGHT_PAD, 1130f, 360f, 88f, shape = InputButtonShape.ROUNDED),
|
||||
Spec(InputControl.SELECT, 660f, 150f, 46f, 26f, shape = InputButtonShape.PILL), Spec(InputControl.START, 940f, 150f, 46f, 26f, shape = InputButtonShape.PILL),
|
||||
Spec(InputControl.SELECT, 660f, 850f, 46f, 26f, shape = InputButtonShape.PILL), Spec(InputControl.START, 940f, 850f, 46f, 26f, shape = InputButtonShape.PILL),
|
||||
Spec(InputControl.GUIDE, 370f, 852f, 66f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.QAM, 1230f, 852f, 66f, 30f, shape = InputButtonShape.PILL),
|
||||
keyboard(136f))
|
||||
kit.playStation -> shoulders() + listOf(dpad(250f, 395f, 125f)) + face(1350f, 395f, 58f, 96f) + listOf(
|
||||
Spec(InputControl.LS, 565f, 690f, 100f), Spec(InputControl.RS, 1035f, 690f, 100f),
|
||||
Spec(InputControl.L3, 430f, 590f, 42f, ax = 565f, ay = 690f), Spec(InputControl.R3, 1170f, 590f, 42f, ax = 1035f, ay = 690f),
|
||||
Spec(InputControl.SELECT, 640f, 150f, 50f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.START, 960f, 150f, 50f, 30f, shape = InputButtonShape.PILL),
|
||||
Spec(InputControl.SELECT, 640f, 850f, 50f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.START, 960f, 850f, 50f, 30f, shape = InputButtonShape.PILL),
|
||||
Spec(InputControl.GUIDE, 800f, 250f, 46f), Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f))
|
||||
else -> shoulders() + listOf(Spec(InputControl.LS, 235f, 400f, 104f), dpad(470f, 675f, 118f)) + face(1375f, 400f, 58f, 94f) + listOf(
|
||||
Spec(InputControl.RS, 1130f, 690f, 104f), Spec(InputControl.L3, 385f, 290f, 42f, ax = 235f, ay = 400f), Spec(InputControl.R3, 1290f, 790f, 42f, ax = 1130f, ay = 690f),
|
||||
Spec(InputControl.SELECT, 690f, 162f, 38f), Spec(InputControl.GUIDE, 800f, 162f, 54f), Spec(InputControl.START, 910f, 162f, 38f),
|
||||
Spec(InputControl.SELECT, 690f, 850f, 38f), Spec(InputControl.GUIDE, 800f, 162f, 54f), Spec(InputControl.START, 910f, 850f, 38f),
|
||||
Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f))
|
||||
}
|
||||
|
||||
/** The default controls for [kit] on a [width] × [height] screen. */
|
||||
fun elements(context: Context, kit: PadKit, width: Int, height: Int, inset: Rect = Rect(), scale: Float = 1f): List<InputSurfaceElement> {
|
||||
fun elements(context: Context, kit: PadKit, width: Int, height: Int, inset: Rect = Rect(), scale: Float = 1f,
|
||||
cutouts: List<Rect> = emptyList(), rearButtons: Boolean = true, trackpads: Boolean = true,
|
||||
addedControls: List<InputSurfaceElement> = emptyList()): List<InputSurfaceElement> {
|
||||
if (width <= 0 || height <= 0) return emptyList()
|
||||
// Insets stay as reported unless what's left is too small to keep every control above the minimum element size.
|
||||
val smallestUnit = InputSurfaceElement.MIN_SIZE * max(width, height) / (2 * SMALLEST_HALF)
|
||||
@@ -100,6 +109,29 @@ object KitLayout {
|
||||
val (top, bottom) = fit(inset.top, inset.bottom, height, REF_H)
|
||||
val safe = Rect(left, top, right, bottom)
|
||||
if (height > width) return portrait(context, kit, width, height, safe, scale)
|
||||
.filter { visibleOnOverlay(it.control, rearButtons, trackpads) }
|
||||
val controls = specs(kit).filter { visibleOnOverlay(it.control, rearButtons, trackpads) }
|
||||
val leftCutouts = cutouts.filter { inset.left > 0 && it.right <= inset.left }
|
||||
val rightCutouts = cutouts.filter { inset.right > 0 && it.left >= width - inset.right }
|
||||
if ((leftCutouts.isNotEmpty() || rightCutouts.isNotEmpty()) &&
|
||||
(left == 0 || leftCutouts.isNotEmpty()) && (right == 0 || rightCutouts.isNotEmpty())) {
|
||||
val corner = cornerInset(safe, cutouts, height, context.resources.displayMetrics.density)
|
||||
val fullWidth = landscape(context, kit, width, height, Rect(0, top, 0, bottom), scale, corner, controls)
|
||||
avoidSideCutouts(fullWidth, leftCutouts, rightCutouts, width, height, addedControls)?.let { return it }
|
||||
}
|
||||
return landscape(context, kit, width, height, safe, scale, left, controls)
|
||||
}
|
||||
|
||||
internal fun cornerInset(inset: Rect, cutouts: List<Rect>, height: Int, density: Float): Int {
|
||||
val leftCutouts = cutouts.filter { inset.left > 0 && it.right <= inset.left }
|
||||
val floor = height - inset.bottom
|
||||
return if (height <= 0 || leftCutouts.isEmpty() ||
|
||||
leftCutouts.any { it.top < floor && it.bottom > floor - CORNER_DP * density && it.left < CORNER_DP * density })
|
||||
inset.left else 0
|
||||
}
|
||||
|
||||
private fun landscape(context: Context, kit: PadKit, width: Int, height: Int, safe: Rect, scale: Float,
|
||||
cornerInset: Int, controls: List<Spec>): List<InputSurfaceElement> {
|
||||
val w = width.toFloat(); val h = height.toFloat()
|
||||
val unit = (min(w / REF_W, h / REF_H) * cap(context, min(width, height)) * scale).coerceAtMost(min((w - safe.left - safe.right).coerceAtLeast(1f) / MIN_SPAN, (h - safe.top - safe.bottom).coerceAtLeast(1f) / REF_H))
|
||||
fun x(ref: Float) = when {
|
||||
@@ -113,22 +145,66 @@ object KitLayout {
|
||||
else -> (h / 2f + (ref - REF_H / 2f) * unit).between(safe.top + ref * unit, h - safe.bottom - (REF_H - ref) * unit)
|
||||
}
|
||||
val density = context.resources.displayMetrics.density
|
||||
var edge = safe.left + CORNER_DP * density
|
||||
val specs = specs(kit)
|
||||
val row = specs.filter { it.cy > REF_H * .88f && it.cx < REF_W / 3f }.sortedBy { it.cx }.associateWith { s ->
|
||||
var edge = cornerInset + CORNER_DP * density
|
||||
val row = controls.filter { it.cy > REF_H * .88f && it.cx < REF_W / 3f }.sortedBy { it.cx }.associateWith { s ->
|
||||
val hw = s.hw * unit
|
||||
max(x(s.cx), edge + hw).also { edge = it + hw + GAP_DP * density }
|
||||
}
|
||||
return specs.map { s ->
|
||||
val cx = row[s] ?: (x(s.ax) + (s.cx - s.ax) * unit); val cy = y(s.ay) + (s.cy - s.ay) * unit; val hw = s.hw * unit; val hh = s.hh * unit
|
||||
return controls.map { s ->
|
||||
val cx = when (s.control) {
|
||||
InputControl.START, InputControl.SELECT -> (w + safe.left - safe.right) / 2f + (s.cx - REF_W / 2f) * unit
|
||||
else -> row[s] ?: (x(s.ax) + (s.cx - s.ax) * unit)
|
||||
}
|
||||
val cy = y(s.ay) + (s.cy - s.ay) * unit; val hw = s.hw * unit; val hh = s.hh * unit
|
||||
InputSurfaceElement(s.control, (cx - hw) / w, (cy - hh) / h, 2 * hw / w, 2 * hh / h, s.id, s.kind, if (s.name == s.control.label) kit.name(s.control) else s.name,
|
||||
floating = s.kind == InputElementKind.STICK, buttonShape = s.shape, icon = s.icon).bounded()
|
||||
}
|
||||
}
|
||||
|
||||
private fun avoidSideCutouts(elements: List<InputSurfaceElement>, leftCutouts: List<Rect>, rightCutouts: List<Rect>,
|
||||
width: Int, height: Int, addedControls: List<InputSurfaceElement>): List<InputSurfaceElement>? {
|
||||
fun bounds(e: InputSurfaceElement) = RectF(e.x * width, e.y * height, (e.x + e.width) * width, (e.y + e.height) * height)
|
||||
val boxes = elements.map(::bounds)
|
||||
val addedBoxes = addedControls.map(::bounds)
|
||||
// Move a face-button cross or a stick and its click button together.
|
||||
val groups = elements.indices.groupBy { index ->
|
||||
val element = elements[index]
|
||||
when (element.control) {
|
||||
InputControl.A, InputControl.B, InputControl.X, InputControl.Y -> if (element.id == KEYBOARD_ID) element.id else "face"
|
||||
InputControl.L3 -> "legacy:ls"
|
||||
InputControl.R3 -> "legacy:rs"
|
||||
else -> element.id
|
||||
}
|
||||
}.values
|
||||
val shifts = FloatArray(elements.size)
|
||||
val left = leftCutouts.map(::RectF)
|
||||
val right = rightCutouts.map(::RectF)
|
||||
val obstacles = left + right
|
||||
for (group in groups) {
|
||||
val leftEdge = left.filter { cutout -> group.any { RectF.intersects(boxes[it], cutout) } }.maxOfOrNull { it.right }
|
||||
val rightEdge = right.filter { cutout -> group.any { RectF.intersects(boxes[it], cutout) } }.minOfOrNull { it.left }
|
||||
val shift = when {
|
||||
leftEdge != null && rightEdge != null -> return null
|
||||
leftEdge != null -> leftEdge - group.minOf { boxes[it].left } + 1f
|
||||
rightEdge != null -> rightEdge - group.maxOf { boxes[it].right } - 1f
|
||||
else -> continue
|
||||
}
|
||||
for (index in group) shifts[index] = shift
|
||||
}
|
||||
val moved = boxes.mapIndexed { index, box -> RectF(box).apply { offset(shifts[index], 0f) } }
|
||||
for (i in moved.indices) {
|
||||
if (moved[i].left < 0f || moved[i].right > width || obstacles.any { RectF.intersects(moved[i], it) }) return null
|
||||
if (shifts[i] != 0f && addedBoxes.any { RectF.intersects(moved[i], it) }) return null
|
||||
for (j in 0 until i) {
|
||||
if (shifts[i] != shifts[j] && RectF.intersects(moved[i], moved[j]) && !RectF.intersects(boxes[i], boxes[j])) return null
|
||||
}
|
||||
}
|
||||
return elements.mapIndexed { index, e -> e.copy(x = e.x + shifts[index] / width).bounded() }
|
||||
}
|
||||
|
||||
/**
|
||||
* A portrait surface gets the same pad as the panel under the game, in the lower part of the screen, with the keyboard,
|
||||
* Steam, Quick Access and stick-click buttons in a row along the bottom edge that starts after DroidDeck's corner button.
|
||||
* Steam, Quick Access, Start, Select and stick-click buttons in a row along the bottom edge.
|
||||
*/
|
||||
private fun portrait(context: Context, kit: PadKit, width: Int, height: Int, safe: Rect, scale: Float): List<InputSurfaceElement> {
|
||||
val w = width.toFloat(); val h = height.toFloat()
|
||||
@@ -137,15 +213,16 @@ object KitLayout {
|
||||
val inner = (w - safe.left - safe.right).coerceAtLeast(1f)
|
||||
val area = (min(h * .6f, inner * 1.15f) * scale).coerceAtMost(h - safe.top - safe.bottom - row).coerceAtLeast(1f)
|
||||
val top = h - safe.bottom - row - area
|
||||
val pad = dock(context, kit, inner.toInt(), area.toInt(), true, InputControl.LS, InputControl.RS, upright = true).map { e ->
|
||||
val pad = dock(context, kit, inner.toInt(), area.toInt(), true, InputControl.LS, InputControl.RS, upright = true)
|
||||
.filterNot { it.control == InputControl.SELECT || it.control == InputControl.START }.map { e ->
|
||||
e.copy(x = (safe.left + e.x * inner) / w, y = (top + e.y * area) / h, width = e.width * inner / w, height = e.height * area / h,
|
||||
floating = e.kind == InputElementKind.STICK)
|
||||
}
|
||||
val specs = specs(kit)
|
||||
fun spec(control: InputControl, id: String = "legacy:${control.id}") = specs.firstOrNull { it.control == control && it.id == id }
|
||||
val gap = GAP_DP * density
|
||||
val leftRow = listOfNotNull(spec(InputControl.A, KEYBOARD_ID), spec(InputControl.GUIDE).takeIf { kit.steam }, spec(InputControl.L3))
|
||||
val rightRow = listOfNotNull(spec(InputControl.QAM), spec(InputControl.GUIDE).takeIf { !kit.steam }, spec(InputControl.R3))
|
||||
val leftRow = listOfNotNull(spec(InputControl.A, KEYBOARD_ID), spec(InputControl.GUIDE).takeIf { kit.steam }, spec(InputControl.L3), spec(InputControl.SELECT))
|
||||
val rightRow = listOfNotNull(spec(InputControl.QAM), spec(InputControl.GUIDE).takeIf { !kit.steam }, spec(InputControl.R3), spec(InputControl.START))
|
||||
val start = safe.left + CORNER_DP * density
|
||||
val span = (w - safe.right - gap - start - gap * (leftRow.size + rightRow.size - 1)).coerceAtLeast(1f)
|
||||
val size = min(BUTTON_DP * density, span / (leftRow + rightRow).sumOf { (it.hw / it.hh).toDouble() }.toFloat())
|
||||
|
||||
@@ -15,6 +15,7 @@ import android.view.View
|
||||
import android.view.ViewConfiguration
|
||||
import android.view.WindowInsets
|
||||
import android.widget.FrameLayout
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.ui.InputSurfaceView
|
||||
import com.droiddeck.launcher.ui.PadArt
|
||||
|
||||
@@ -25,6 +26,7 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
|
||||
private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY, haptics = dock != null)
|
||||
private var layout: SavedInputLayout? = null
|
||||
private val safe = Rect()
|
||||
private var cutouts = emptyList<Rect>()
|
||||
private var viewWidth = 0
|
||||
private var viewHeight = 0
|
||||
private val corner = CornerButton(context)
|
||||
@@ -62,11 +64,22 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
|
||||
}
|
||||
|
||||
private fun render() {
|
||||
val placed = OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, dock)
|
||||
val placed = OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, dock, cutouts,
|
||||
rearButtons = SessionPrefs.oscRearButtons(context), trackpads = SessionPrefs.oscTrackpads(context))
|
||||
surface.updateCustomLayout(if (hidden != null) placed.filter { it.alwaysShown } else placed)
|
||||
surface.updateStyle(layout?.style ?: InputSurfaceStyle())
|
||||
corner.visibility = if (layout == null || dock != null) GONE else VISIBLE
|
||||
corner.alpha = (layout?.style?.opacity ?: 100) / 100f
|
||||
val density = resources.displayMetrics.density
|
||||
val margin = (CORNER_MARGIN_DP * density).toInt()
|
||||
val params = corner.layoutParams as LayoutParams
|
||||
val leftInset = if (dock == null && viewWidth >= viewHeight && layout?.let(OnScreenLayout::generated) == true)
|
||||
KitLayout.cornerInset(safe, cutouts, viewHeight, density) else safe.left
|
||||
if (params.leftMargin != leftInset + margin || params.bottomMargin != safe.bottom + margin) {
|
||||
params.leftMargin = leftInset + margin
|
||||
params.bottomMargin = safe.bottom + margin
|
||||
corner.layoutParams = params
|
||||
}
|
||||
corner.invalidate()
|
||||
}
|
||||
|
||||
@@ -91,18 +104,11 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
|
||||
|
||||
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
|
||||
val cutout = if (Build.VERSION.SDK_INT >= 28) insets.displayCutout else null
|
||||
val margin = (CORNER_MARGIN_DP * resources.displayMetrics.density).toInt()
|
||||
val params = corner.layoutParams as LayoutParams
|
||||
val left = (cutout?.safeInsetLeft ?: 0) + margin
|
||||
val bottom = (cutout?.safeInsetBottom ?: 0) + margin
|
||||
if (params.leftMargin != left || params.bottomMargin != bottom) {
|
||||
params.leftMargin = left
|
||||
params.bottomMargin = bottom
|
||||
corner.layoutParams = params
|
||||
}
|
||||
val fresh = Rect(cutout?.safeInsetLeft ?: 0, if (dock == null) cutout?.safeInsetTop ?: 0 else 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
|
||||
if (fresh != safe) {
|
||||
val bounds = cutout?.boundingRects.orEmpty()
|
||||
if (fresh != safe || bounds != cutouts) {
|
||||
safe.set(fresh)
|
||||
cutouts = bounds
|
||||
render()
|
||||
}
|
||||
return super.onApplyWindowInsets(insets)
|
||||
|
||||
@@ -23,19 +23,25 @@ object OnScreenLayout {
|
||||
* The built-in gamepad keeps no kit positions until its kit is edited; until then the kit follows the virtual controller and
|
||||
* the layout stores only the keys and controls the player added on top.
|
||||
*/
|
||||
fun generated(layout: SavedInputLayout) = (layout.id == InputLibraries.OVERLAY || layout.origin == InputLibraries.OVERLAY) &&
|
||||
!layout.kitless && layout.elements.none { KitLayout.isKit(it.id) }
|
||||
fun generated(layout: SavedInputLayout) = hasBuiltInKit(layout) && layout.elements.none { KitLayout.isKit(it.id) }
|
||||
|
||||
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect, dock: Dock? = null): List<InputSurfaceElement> {
|
||||
fun hasBuiltInKit(layout: SavedInputLayout) =
|
||||
!layout.kitless && (layout.id == InputLibraries.OVERLAY || layout.origin == InputLibraries.OVERLAY)
|
||||
|
||||
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect, dock: Dock? = null,
|
||||
cutouts: List<Rect> = emptyList(), rearButtons: Boolean = true, trackpads: Boolean = true): List<InputSurfaceElement> {
|
||||
layout ?: return emptyList()
|
||||
if (width <= 0 || height <= 0) return layout.elements
|
||||
if (generated(layout)) {
|
||||
val kit = PadKit.current(context)
|
||||
val extras = if (layout.elements.isEmpty()) emptyList() else fit(layout.elements, aspect(context, layout), 1f, width, height, safe)
|
||||
return (if (dock != null) KitLayout.dock(context, kit, width, height, dock.portrait, dock.left, dock.right)
|
||||
else KitLayout.elements(context, kit, width, height, safe, layout.scale)) + extras
|
||||
else KitLayout.elements(context, kit, width, height, safe, layout.scale, cutouts, rearButtons, trackpads, addedControls = extras)) + extras
|
||||
}
|
||||
return fit(layout.elements, aspect(context, layout), 1f, width, height, safe)
|
||||
val elements = if (dock == null && hasBuiltInKit(layout)) layout.elements.filter { element ->
|
||||
!KitLayout.isKit(element.id) || KitLayout.visibleOnOverlay(element.control, rearButtons, trackpads)
|
||||
} else layout.elements
|
||||
return fit(elements, aspect(context, layout), 1f, width, height, safe)
|
||||
}
|
||||
|
||||
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List<InputSurfaceElement> =
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.ActivityOptions
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import android.view.Display
|
||||
import android.view.MotionEvent
|
||||
import android.view.WindowManager
|
||||
|
||||
// While a session is on screen, sits invisibly on top of every other display, so that display's
|
||||
// home launcher is not its top activity. lmkd kills the launcher first; restarted as a top activity
|
||||
// it takes focus from the session, which then drops to adj 50 and is killed next.
|
||||
// Android gives a translucent activity alone in its task an input sink that eats every touch on the
|
||||
// display whatever its window flags say, so a touch makes the guard leave that display until the
|
||||
// session is back on top.
|
||||
class KeepTopActivity : Activity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
@Suppress("DEPRECATION") overridePendingTransition(0, 0)
|
||||
if (intent.getBooleanExtra(EXTRA_BOUNCE, false)) {
|
||||
bounces++
|
||||
finish()
|
||||
return
|
||||
}
|
||||
if (intent.getIntExtra(EXTRA_GENERATION, -1) != generation) {
|
||||
finishAndRemoveTask()
|
||||
return
|
||||
}
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
|
||||
val id = display?.displayId ?: Display.INVALID_DISPLAY
|
||||
starting.remove(id)
|
||||
if (id in yielded) {
|
||||
finishAndRemoveTask()
|
||||
return
|
||||
}
|
||||
guards[id]?.takeIf { it !== this && !it.isFinishing }?.finishAndRemoveTask()
|
||||
guards[id] = this
|
||||
}
|
||||
|
||||
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN && !isFinishing) {
|
||||
val id = display?.displayId ?: Display.INVALID_DISPLAY
|
||||
yielded.add(id)
|
||||
Log.i(TAG, "display $id touched, leaving it to the app below")
|
||||
finishAndRemoveTask()
|
||||
onYield?.invoke()
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
guards.values.remove(this)
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "KeepTop"
|
||||
private const val EXTRA_BOUNCE = "bounce"
|
||||
private const val EXTRA_GENERATION = "generation"
|
||||
private var generation = 0
|
||||
var bounces = 0
|
||||
private set
|
||||
private val guards = HashMap<Int, KeepTopActivity>()
|
||||
private const val START_TIMEOUT_MS = 2_000L
|
||||
private val starting = HashMap<Int, Long>()
|
||||
private val yielded = HashSet<Int>()
|
||||
const val YIELD_GRACE_MS = 5_000L
|
||||
var onYield: (() -> Unit)? = null
|
||||
|
||||
fun rearm() = yielded.clear()
|
||||
|
||||
fun guardOtherDisplays(context: Context, sessionDisplay: Int): Boolean {
|
||||
val displays = context.getSystemService(DisplayManager::class.java)?.displays ?: return false
|
||||
var started = false
|
||||
for (display in displays) {
|
||||
val id = display.displayId
|
||||
if (id == sessionDisplay || id in yielded || display.state != Display.STATE_ON || guards[id]?.isFinishing == false ||
|
||||
starting[id]?.let { SystemClock.elapsedRealtime() - it < START_TIMEOUT_MS } == true) continue
|
||||
runCatching {
|
||||
launch(context, id, bounce = false)
|
||||
starting[id] = SystemClock.elapsedRealtime()
|
||||
started = true
|
||||
Log.i(TAG, "guarding display $id from a home launcher restart")
|
||||
}.onFailure { Log.w(TAG, "could not guard display $id", it) }
|
||||
}
|
||||
if (!started) return false
|
||||
return runCatching { launch(context, sessionDisplay, bounce = true) }
|
||||
.onFailure { Log.w(TAG, "could not return focus to display $sessionDisplay", it) }.isSuccess
|
||||
}
|
||||
|
||||
fun hasPendingStarts() = starting.isNotEmpty()
|
||||
|
||||
const val RETRY_MS = START_TIMEOUT_MS + 250
|
||||
|
||||
fun stepAside() {
|
||||
generation++
|
||||
guards.values.toList().forEach { it.finishAndRemoveTask() }
|
||||
guards.clear()
|
||||
starting.clear()
|
||||
}
|
||||
|
||||
fun release() {
|
||||
stepAside()
|
||||
yielded.clear()
|
||||
}
|
||||
|
||||
private fun launch(context: Context, displayId: Int, bounce: Boolean) {
|
||||
val intent = Intent(context, KeepTopActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION)
|
||||
.putExtra(EXTRA_BOUNCE, bounce)
|
||||
.putExtra(EXTRA_GENERATION, generation)
|
||||
context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
// Tracks a pause that skipped the session's departure cleanup for the keep-top focus bounce.
|
||||
internal class LightPause {
|
||||
private var pending = false
|
||||
private var bouncesAtPause = 0
|
||||
|
||||
fun paused(bounces: Int) {
|
||||
pending = true
|
||||
bouncesAtPause = bounces
|
||||
}
|
||||
|
||||
// The bounce resumes the session within tens of milliseconds; still paused at the timeout means
|
||||
// something else holds the pause.
|
||||
fun timedOut(): Boolean = take()
|
||||
|
||||
fun stopped(): Boolean = take()
|
||||
|
||||
fun resumed(bounces: Int): Resume {
|
||||
if (!pending) return Resume.NORMAL
|
||||
pending = false
|
||||
return if (bounces != bouncesAtPause) Resume.LIGHT else Resume.CLEANUP_FIRST
|
||||
}
|
||||
|
||||
private fun take(): Boolean {
|
||||
val was = pending
|
||||
pending = false
|
||||
return was
|
||||
}
|
||||
|
||||
enum class Resume { NORMAL, LIGHT, CLEANUP_FIRST }
|
||||
}
|
||||
@@ -678,6 +678,18 @@ object SessionPrefs {
|
||||
editor.putString("osc", mode).apply()
|
||||
}
|
||||
|
||||
fun oscRearButtons(context: Context): Boolean = prefs(context).getBoolean("oscRearButtons", false)
|
||||
|
||||
fun setOscRearButtons(context: Context, shown: Boolean) {
|
||||
prefs(context).edit().putBoolean("oscRearButtons", shown).apply()
|
||||
}
|
||||
|
||||
fun oscTrackpads(context: Context): Boolean = prefs(context).getBoolean("oscTrackpads", false)
|
||||
|
||||
fun setOscTrackpads(context: Context, shown: Boolean) {
|
||||
prefs(context).edit().putBoolean("oscTrackpads", shown).apply()
|
||||
}
|
||||
|
||||
/** Draw Steam's touch layout for the game instead of DroidDeck's own. */
|
||||
fun steamTouchLayout(context: Context): Boolean =
|
||||
prefs(context).getBoolean("steamTouchLayout", prefs(context).getString("osc", null) == OSC_STEAM_TOUCH)
|
||||
|
||||
@@ -1613,6 +1613,11 @@ class SessionService : Service() {
|
||||
return
|
||||
}
|
||||
val accepted = gameId!!
|
||||
if (pendingSteamGameId == null && SteamGameProcess.alreadyRunning(accepted, SessionState.gameId)) {
|
||||
Log.i(TAG, "game $accepted is already running; resuming it instead of launching it again")
|
||||
if (SessionState.suspended || SessionState.suspending) resumeSession()
|
||||
return
|
||||
}
|
||||
if (!pendingSteamPreviousGamePending) {
|
||||
pendingSteamPreviousGameId = SessionState.gameId
|
||||
pendingSteamPreviousGamePending = true
|
||||
@@ -2394,8 +2399,7 @@ class SessionService : Service() {
|
||||
override fun onTaskRemoved(rootIntent: Intent?) {
|
||||
if (rootIntent?.component?.className in setOf(
|
||||
com.droiddeck.launcher.ui.DualScreenActivity::class.java.name,
|
||||
com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name,
|
||||
KeepTopActivity::class.java.name)) return
|
||||
com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name)) return
|
||||
if (pipTask || xrActivityVisible) {
|
||||
Log.i(TAG, "panel task dismissed - retaining the session under its active surface policy")
|
||||
activityVisible = false
|
||||
|
||||
@@ -61,4 +61,11 @@ object SteamGameProcess {
|
||||
runCatching { File(p, "cmdline").readBytes() }
|
||||
.getOrNull()?.let { matches(it, gameId) } == true
|
||||
} == true
|
||||
|
||||
// A front end that resumes a player by launching the same game again would otherwise have Steam
|
||||
// start it a second time, which Steam answers with "Game already running".
|
||||
fun alreadyRunning(requested: String, current: String?, proc: File = File("/proc")): Boolean {
|
||||
val appId = steamAppIdForGameId(requested) ?: return false
|
||||
return appId == steamAppIdForGameId(current.orEmpty()) && running(requested, proc)
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.ComponentCallbacks2
|
||||
|
||||
internal object TopUnderPressure {
|
||||
const val WINDOW_MS = 5_000L
|
||||
|
||||
fun isPressure(level: Int) =
|
||||
level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL || level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW
|
||||
|
||||
fun shouldReclaim(nowMs: Long, pressureAtMs: Long, sessionRunning: Boolean, finishing: Boolean) =
|
||||
sessionRunning && !finishing && pressureAtMs > 0 && nowMs - pressureAtMs in 0..WINDOW_MS
|
||||
}
|
||||
@@ -90,6 +90,8 @@ object StoreLaunchRequests {
|
||||
lastLaunched = Store.ROCKSTAR to request.optString("id")
|
||||
com.droiddeck.launcher.stores.rockstar.RockstarLaunch.prepare(app, request.optString("id"))
|
||||
}.getOrElse { JSONObject().put("ok", false).put("reason", "error-" + it.javaClass.simpleName) }
|
||||
"rockstar-sdk" -> runCatching { com.droiddeck.launcher.stores.rockstar.RockstarLaunch.sdkInstaller(app, request.optString("id")) }
|
||||
.getOrElse { JSONObject().put("ok", false).put("reason", "error-" + it.javaClass.simpleName) }
|
||||
"store-service" -> runCatching {
|
||||
val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app)
|
||||
if (com.droiddeck.launcher.session.SessionFiles.awaitStoreService(app, request.optString("store"), root)) JSONObject().put("ok", true)
|
||||
|
||||
@@ -99,6 +99,11 @@ internal object RockstarManifest {
|
||||
}
|
||||
|
||||
fun key(file: RockstarFile, chunk: RockstarChunk) = "${file.versionId}:${chunk.chunkId}"
|
||||
|
||||
fun sdkInstaller(build: RockstarBuild): RockstarFile? {
|
||||
val name = RockstarLaunch.SDK_INSTALLER.substringAfterLast('/')
|
||||
return build.files.filter { it.path.substringAfterLast('/').equals(name, ignoreCase = true) }.minByOrNull { it.path.length }
|
||||
}
|
||||
}
|
||||
|
||||
internal class RockstarInstaller(
|
||||
@@ -160,7 +165,7 @@ internal class RockstarInstaller(
|
||||
for (c in batch) {
|
||||
if (cancelled.get()) break
|
||||
val f = fileOf.getValue("${c.fileEntryId}:${c.chunkId}")
|
||||
fetch({ retry -> (if (retry) null else urls[c.chunkId]) ?: chunkUrls(ticket, branch.accessToken, listOf(c)).getValue(c.chunkId) }, RockstarManifest.inside(folder, f.path), c, progress) {
|
||||
fetch(cancelled::get, { retry -> (if (retry) null else urls[c.chunkId]) ?: chunkUrls(ticket, branch.accessToken, listOf(c)).getValue(c.chunkId) }, RockstarManifest.inside(folder, f.path), c, progress) {
|
||||
handle.progress(progress.get(), total, "Downloading (${build.files.size} files)")
|
||||
}
|
||||
synchronized(ledgerLock) { ledger.appendText(RockstarManifest.key(f, c) + "\n") }
|
||||
@@ -191,58 +196,6 @@ internal class RockstarInstaller(
|
||||
return folder.path
|
||||
}
|
||||
|
||||
private fun chunkUrls(ticket: String, branchToken: String, batch: List<RockstarChunk>): Map<String, String> {
|
||||
val csv = batch.joinToString(",") { "${it.fileEntryId}:${it.chunkId}" }
|
||||
val root = RockstarRos.result("app.asmx/RetrieveFileChunkMulti", listOf("ticket" to ticket, "branchAccessToken" to branchToken, "fileEntryAndChunkIdCsv" to csv))
|
||||
return RockstarRos.all(root, "Chunk").mapNotNull { c -> RockstarRos.text(c, "RedirectUrl")?.let { c.getAttribute("FileChunkId") to it } }.toMap()
|
||||
}
|
||||
|
||||
private fun fetch(url: (Boolean) -> String, target: File, chunk: RockstarChunk, progress: AtomicLong, report: () -> Unit) {
|
||||
var lastError: Exception? = null
|
||||
for (attempt in 0 until 3) {
|
||||
if (cancelled.get()) return
|
||||
val written = AtomicLong(0)
|
||||
try {
|
||||
val c = URL(url(attempt > 0)).openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 20_000
|
||||
c.readTimeout = 60_000
|
||||
try {
|
||||
if (c.responseCode != 200) throw java.io.IOException("chunk ${chunk.chunkId}: HTTP ${c.responseCode}")
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
RandomAccessFile(target, "rw").use { out ->
|
||||
out.seek(chunk.offset)
|
||||
c.inputStream.use { input ->
|
||||
val buf = ByteArray(256 * 1024)
|
||||
var last = 0L
|
||||
while (true) {
|
||||
if (cancelled.get()) { progress.addAndGet(-written.get()); return }
|
||||
val n = input.read(buf)
|
||||
if (n < 0) break
|
||||
if (written.get() + n > chunk.size) throw java.io.IOException("chunk ${chunk.chunkId} is longer than the manifest says")
|
||||
out.write(buf, 0, n)
|
||||
digest.update(buf, 0, n)
|
||||
written.addAndGet(n.toLong())
|
||||
progress.addAndGet(n.toLong())
|
||||
val now = System.currentTimeMillis()
|
||||
if (now - last > 400) { last = now; report() }
|
||||
}
|
||||
}
|
||||
}
|
||||
val hex = digest.digest().joinToString("") { "%02x".format(it) }
|
||||
if (written.get() != chunk.size || hex != chunk.sha256) throw java.io.IOException("chunk ${chunk.chunkId} failed its check")
|
||||
report()
|
||||
return
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
progress.addAndGet(-written.get())
|
||||
lastError = e
|
||||
}
|
||||
}
|
||||
throw lastError ?: java.io.IOException("chunk ${chunk.chunkId} failed")
|
||||
}
|
||||
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
if (deleteFiles) StoreInstalls.discard(app, folder, emptyList())
|
||||
@@ -252,6 +205,58 @@ internal class RockstarInstaller(
|
||||
const val LEDGER = ".droiddeck-rockstar-chunks"
|
||||
private const val WORKERS = 4
|
||||
|
||||
fun chunkUrls(ticket: String, branchToken: String, batch: List<RockstarChunk>): Map<String, String> {
|
||||
val csv = batch.joinToString(",") { "${it.fileEntryId}:${it.chunkId}" }
|
||||
val root = RockstarRos.result("app.asmx/RetrieveFileChunkMulti", listOf("ticket" to ticket, "branchAccessToken" to branchToken, "fileEntryAndChunkIdCsv" to csv))
|
||||
return RockstarRos.all(root, "Chunk").mapNotNull { c -> RockstarRos.text(c, "RedirectUrl")?.let { c.getAttribute("FileChunkId") to it } }.toMap()
|
||||
}
|
||||
|
||||
fun fetch(cancelled: () -> Boolean, url: (Boolean) -> String, target: File, chunk: RockstarChunk, progress: AtomicLong, report: () -> Unit) {
|
||||
var lastError: Exception? = null
|
||||
for (attempt in 0 until 3) {
|
||||
if (cancelled()) return
|
||||
val written = AtomicLong(0)
|
||||
try {
|
||||
val c = URL(url(attempt > 0)).openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 20_000
|
||||
c.readTimeout = 60_000
|
||||
try {
|
||||
if (c.responseCode != 200) throw java.io.IOException("chunk ${chunk.chunkId}: HTTP ${c.responseCode}")
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
RandomAccessFile(target, "rw").use { out ->
|
||||
out.seek(chunk.offset)
|
||||
c.inputStream.use { input ->
|
||||
val buf = ByteArray(256 * 1024)
|
||||
var last = 0L
|
||||
while (true) {
|
||||
if (cancelled()) { progress.addAndGet(-written.get()); return }
|
||||
val n = input.read(buf)
|
||||
if (n < 0) break
|
||||
if (written.get() + n > chunk.size) throw java.io.IOException("chunk ${chunk.chunkId} is longer than the manifest says")
|
||||
out.write(buf, 0, n)
|
||||
digest.update(buf, 0, n)
|
||||
written.addAndGet(n.toLong())
|
||||
progress.addAndGet(n.toLong())
|
||||
val now = System.currentTimeMillis()
|
||||
if (now - last > 400) { last = now; report() }
|
||||
}
|
||||
}
|
||||
}
|
||||
val hex = digest.digest().joinToString("") { "%02x".format(it) }
|
||||
if (written.get() != chunk.size || hex != chunk.sha256) throw java.io.IOException("chunk ${chunk.chunkId} failed its check")
|
||||
report()
|
||||
return
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
progress.addAndGet(-written.get())
|
||||
lastError = e
|
||||
}
|
||||
}
|
||||
throw lastError ?: java.io.IOException("chunk ${chunk.chunkId} failed")
|
||||
}
|
||||
|
||||
fun resolve(folder: File, configured: String): String? {
|
||||
var at = folder
|
||||
for (part in configured.replace('\\', '/').split('/').filter { it.isNotEmpty() }) {
|
||||
|
||||
@@ -10,6 +10,10 @@ import java.security.MessageDigest
|
||||
import java.util.Base64
|
||||
|
||||
object RockstarLaunch {
|
||||
internal const val SDK_INSTALLER = "Redistributables/Social-Club-Setup.exe"
|
||||
private const val LAUNCHER_APP = "launcher"
|
||||
private val sdkLock = Any()
|
||||
|
||||
internal val pipes = mapOf("gta3" to "GTA3_Pipe", "gtavc" to "GTA-VC_Pipe", "gtasa" to "GTA_SA_Pipe", "gta4" to "GTAIV_Pipe", "lanoire" to "LANOIRE_Pipe")
|
||||
|
||||
fun usesClassicLauncher(id: String) = id in pipes
|
||||
@@ -22,10 +26,47 @@ object RockstarLaunch {
|
||||
}
|
||||
}
|
||||
|
||||
private fun installedFolder(app: Context, id: String) = StoreInstallRoot.gameFolders(app).firstOrNull { folder ->
|
||||
StoreGameSidecar.read(folder)?.let { it.store == Store.ROCKSTAR && it.id == id && it.isInstalled } == true
|
||||
}
|
||||
|
||||
fun sdkInstaller(app: Context, id: String): JSONObject = synchronized(sdkLock) { downloadSdkInstaller(app, id) }
|
||||
|
||||
private fun downloadSdkInstaller(app: Context, id: String): JSONObject {
|
||||
val folder = installedFolder(app, id) ?: return failure("not-installed")
|
||||
val target = RockstarManifest.inside(folder, SDK_INSTALLER)
|
||||
if (target.isFile) return JSONObject().put("ok", true)
|
||||
val ticket = RockstarAuth.ticket(app) ?: RockstarAuth.ticket(app, fresh = true) ?: return failure("signed-out")
|
||||
val branch = RockstarApps.fetch(ticket.ticket) {}.apps.firstOrNull { it.name == LAUNCHER_APP }?.let(RockstarApps::branch)
|
||||
?: return failure("no-launcher-build")
|
||||
val build = RockstarManifest.parse(RockstarRos.result("app.asmx/GetBuildManifestFull",
|
||||
listOf("ticket" to ticket.ticket, "branchAccessToken" to branch.accessToken)))
|
||||
val file = RockstarManifest.sdkInstaller(build) ?: return failure("no-sdk-installer")
|
||||
if (file.chunks.sumOf { it.size } != file.size) return failure("invalid-sdk-installer")
|
||||
val part = RockstarManifest.inside(folder, "$SDK_INSTALLER.part")
|
||||
part.parentFile?.mkdirs()
|
||||
try {
|
||||
java.io.RandomAccessFile(part, "rw").use { it.setLength(file.size) }
|
||||
for (batch in RockstarManifest.batches(file.chunks)) {
|
||||
val urls = RockstarInstaller.chunkUrls(ticket.ticket, branch.accessToken, batch)
|
||||
for (chunk in batch) {
|
||||
RockstarInstaller.fetch({ false }, { retry ->
|
||||
(if (retry) null else urls[chunk.chunkId]) ?: RockstarInstaller.chunkUrls(ticket.ticket, branch.accessToken, listOf(chunk)).getValue(chunk.chunkId)
|
||||
}, part, chunk, java.util.concurrent.atomic.AtomicLong()) {}
|
||||
}
|
||||
}
|
||||
if (file.sha256.isNotEmpty() && !RockstarManifest.verified(part, RockstarChunk(file.entryId, "", file.sha256, 0, file.size))) {
|
||||
return failure("invalid-sdk-installer")
|
||||
}
|
||||
if (!part.renameTo(target)) return failure("sdk-installer-unwritable")
|
||||
} finally {
|
||||
part.delete()
|
||||
}
|
||||
return JSONObject().put("ok", true)
|
||||
}
|
||||
|
||||
fun prepare(app: Context, id: String): JSONObject {
|
||||
val folder = StoreInstallRoot.gameFolders(app).firstOrNull { folder ->
|
||||
StoreGameSidecar.read(folder)?.let { it.store == Store.ROCKSTAR && it.id == id && it.isInstalled } == true
|
||||
} ?: return failure("not-installed")
|
||||
val folder = installedFolder(app, id) ?: return failure("not-installed")
|
||||
val installed = StoreGameSidecar.read(folder) ?: return failure("not-installed")
|
||||
val exe = installed.exeFile(folder).canonicalFile
|
||||
if (!exe.path.startsWith(folder.canonicalPath + java.io.File.separator) || !exe.isFile) return failure("missing-game-files")
|
||||
|
||||
@@ -199,9 +199,9 @@ private fun DefaultControlsGroup(host: MenuHost, revision: Int, onEdit: (Triple<
|
||||
var touch by remember { mutableStateOf(SessionPrefs.touchMode(context)) }
|
||||
var below by remember { mutableStateOf(SessionPrefs.unfoldedControls(context)) }
|
||||
SettingsGroup(stringResource(R.string.osc_group_for, stringResource(R.string.osc_default))) {
|
||||
ChoiceRow(host, "osc-layout", stringResource(R.string.osc_layout), null, options, choice) { id ->
|
||||
LayoutChoiceRow(host, "osc-layout", options, choice, onPick = { id ->
|
||||
runCatching { ControlsChoice.choose(context, null, id, desktop = false) }.onSuccess { onChanged() }.onFailure(onFailure)
|
||||
}
|
||||
}, onDelete = { id -> runCatching { ControlsChoice.delete(context, id) }.onSuccess { onChanged() }.onFailure(onFailure) })
|
||||
if (choice != GameControls.STEAM) ActionRow(stringResource(R.string.osc_edit_layout), null, stringResource(R.string.ctrl_edit), {
|
||||
host.open = null
|
||||
ControlsChoice.editTarget(context, null, desktop = false)?.let(onEdit)
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsFocusedAsState
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.ControlsChoice
|
||||
|
||||
/** The on-screen controls layout menu: each option with what it is, and a delete button on saved layouts nothing uses. */
|
||||
@Composable
|
||||
fun LayoutChoiceRow(
|
||||
host: MenuHost, key: String, options: List<ControlsChoice.Option>, selected: String, hint: String? = null,
|
||||
chipModifier: Modifier = Modifier, onPick: (String) -> Unit, onDelete: (String) -> Unit,
|
||||
) {
|
||||
val label = stringResource(R.string.osc_layout)
|
||||
val open = host.open == key
|
||||
var deleting by remember { mutableStateOf<ControlsChoice.Option?>(null) }
|
||||
SettingsRow(label, hint, highlighted = open) {
|
||||
Box {
|
||||
ValueChip(options.firstOrNull { it.id == selected }?.name ?: "-", open,
|
||||
modifier = chipModifier.testTag("setting-$key")) { host.open = if (open) null else key }
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label) { firstItemFocus ->
|
||||
options.forEachIndexed { index, option ->
|
||||
MenuItem(option.name, checked = option.id == selected, detail = option.detail,
|
||||
focusRequester = if (index == 0) firstItemFocus else null,
|
||||
trailing = if (option.deletable) ({ DeleteButton(option.id, option.name) { host.open = null; deleting = option } }) else null) {
|
||||
onPick(option.id)
|
||||
host.open = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
deleting?.let { option ->
|
||||
AlertDialog(onDismissRequest = { deleting = null },
|
||||
title = { Text(stringResource(R.string.osc_delete_layout)) },
|
||||
text = { Text(stringResource(R.string.input_delete_layout_detail, option.name)) },
|
||||
confirmButton = { PadTextButton(onClick = { deleting = null; onDelete(option.id) }, modifier = Modifier.testTag("osc-delete-confirm")) {
|
||||
Text(stringResource(R.string.common_delete))
|
||||
} },
|
||||
dismissButton = { PadTextButton(onClick = { deleting = null }) { Text(stringResource(R.string.common_cancel)) } })
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DeleteButton(id: String, name: String, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(36.dp).clip(RoundedCornerShape(8.dp))
|
||||
.background(if (hot) colors.error.copy(alpha = 0.16f) else Color.Transparent)
|
||||
.glideBorder(hot, RoundedCornerShape(8.dp), colors.error)
|
||||
.hoverable(source).clickable(role = Role.Button, interactionSource = source, indication = null, onClick = onClick)
|
||||
.controllerConfirm(onClick = onClick)
|
||||
.testTag("osc-delete-$id"),
|
||||
) {
|
||||
Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, name),
|
||||
tint = if (hot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp))
|
||||
}
|
||||
}
|
||||
@@ -291,10 +291,16 @@ class DrawerActions(
|
||||
val achievementsProgress: Pair<Int, Int>? = null,
|
||||
val onOsc: (String) -> Unit,
|
||||
val layoutGame: String? = null,
|
||||
val layoutOptions: List<Pair<String, String>> = emptyList(),
|
||||
val layoutOptions: List<com.droiddeck.launcher.input.ControlsChoice.Option> = emptyList(),
|
||||
val layoutChoice: String = "",
|
||||
val layoutHint: String? = null,
|
||||
val onLayout: (String) -> Unit = {},
|
||||
val onDeleteLayout: (String) -> Unit = {},
|
||||
val onEditLayout: (() -> Unit)? = null,
|
||||
val oscRearButtons: Boolean? = null,
|
||||
val oscTrackpads: Boolean = false,
|
||||
val onOscRearButtons: (Boolean) -> Unit = {},
|
||||
val onOscTrackpads: (Boolean) -> Unit = {},
|
||||
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
|
||||
val onRumble: (Boolean) -> Unit = {},
|
||||
val onSuspendPolicy: (String) -> Unit,
|
||||
@@ -665,8 +671,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
}
|
||||
SessionDrawerPage.CONTROLLER -> {
|
||||
SettingsGroup(a.layoutGame?.let { stringResource(R.string.osc_group_for, it) } ?: stringResource(R.string.mode_osc)) {
|
||||
if (a.layoutOptions.isNotEmpty()) ChoiceRow(host, "osc-layout", stringResource(R.string.osc_layout), null,
|
||||
a.layoutOptions, a.layoutChoice, chipModifier = focus.track(page, "osc-layout"), onPick = a.onLayout)
|
||||
if (a.layoutOptions.isNotEmpty()) LayoutChoiceRow(host, "osc-layout", a.layoutOptions, a.layoutChoice, a.layoutHint,
|
||||
chipModifier = focus.track(page, "osc-layout"), onPick = a.onLayout, onDelete = a.onDeleteLayout)
|
||||
a.onEditLayout?.let { edit ->
|
||||
ActionRow(stringResource(R.string.osc_edit_layout), null, stringResource(R.string.ctrl_edit), { host.open = null; edit() },
|
||||
modifier = focus.track(page, "osc-edit"))
|
||||
@@ -676,6 +682,12 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)), a.oscMode,
|
||||
tabModifier = { focus.track(page, "osc-$it") }, onPick = a.onOsc)
|
||||
}
|
||||
a.oscRearButtons?.let { rearButtons ->
|
||||
ToggleRow(host, "osc-rear-buttons", stringResource(R.string.osc_rear_buttons), null, rearButtons,
|
||||
chipModifier = focus.track(page, "osc-rear-buttons"), onChange = a.onOscRearButtons)
|
||||
ToggleRow(host, "osc-trackpads", stringResource(R.string.osc_trackpads), null, a.oscTrackpads,
|
||||
chipModifier = focus.track(page, "osc-trackpads"), onChange = a.onOscTrackpads)
|
||||
}
|
||||
ChoiceRow(host, "touch", stringResource(R.string.input_touches), null,
|
||||
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_mouse),
|
||||
SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures),
|
||||
|
||||
@@ -326,10 +326,17 @@
|
||||
<string name="mode_osc_note">Auto shows the controls when no controller is connected.</string>
|
||||
<string name="osc_group_for">On-screen controls · %1$s</string>
|
||||
<string name="osc_layout">Layout</string>
|
||||
<string name="osc_layout_gamepad">Gamepad</string>
|
||||
<string name="osc_layout_steam">Steam layout</string>
|
||||
<string name="osc_layout_gamepad">DroidDeck controls</string>
|
||||
<string name="osc_layout_gamepad_detail">Works in every game. Edit them here.</string>
|
||||
<string name="osc_layout_steam">Steam touch controls</string>
|
||||
<string name="osc_layout_steam_detail">Each game\'s touch controls from Steam. Steam games only; edit them in Steam.</string>
|
||||
<string name="osc_layout_steam_unavailable">Steam touch controls only work in games launched through Steam, so these are shown instead.</string>
|
||||
<string name="osc_layout_detail_game">Just for %1$s</string>
|
||||
<string name="osc_delete_layout">Delete layout</string>
|
||||
<string name="osc_edit_layout">Edit layout</string>
|
||||
<string name="osc_show">Show</string>
|
||||
<string name="osc_rear_buttons">Rear buttons</string>
|
||||
<string name="osc_trackpads">Trackpads</string>
|
||||
<string name="osc_more">More controller settings</string>
|
||||
<string name="osc_more_detail">Shortcuts, latency and the PC keyboard</string>
|
||||
<string name="input_touches">Touches elsewhere</string>
|
||||
|
||||
@@ -89,10 +89,10 @@ class ControlsChoiceTest {
|
||||
}
|
||||
|
||||
@Test fun newIsOfferedOnlyForAGame() {
|
||||
assertTrue(ControlsChoice.options(context, null, steamMode = true).none { it.first == ControlsChoice.NEW })
|
||||
assertEquals(ControlsChoice.NEW to context.getString(R.string.osc_layout_new_for, "Castle Crashers"),
|
||||
ControlsChoice.options(context, 7, steamMode = true, gameName = "Castle Crashers").last())
|
||||
assertEquals(listOf(InputLibraries.OVERLAY, GameControls.STEAM), ControlsChoice.options(context, null, steamMode = true).map { it.first }.take(2))
|
||||
assertTrue(ControlsChoice.options(context, null, steamMode = true).none { it.id == ControlsChoice.NEW })
|
||||
val last = ControlsChoice.options(context, 7, steamMode = true, gameName = "Castle Crashers").last()
|
||||
assertEquals(ControlsChoice.NEW to context.getString(R.string.osc_layout_new_for, "Castle Crashers"), last.id to last.name)
|
||||
assertEquals(listOf(InputLibraries.OVERLAY, GameControls.STEAM), ControlsChoice.options(context, null, steamMode = true).map { it.id })
|
||||
}
|
||||
|
||||
@Test fun newForTheGameInTheControllerPageCopiesTheLayoutAndOpensTheEditorOnIt() {
|
||||
@@ -101,8 +101,8 @@ class ControlsChoiceTest {
|
||||
ReflectionHelpers.getField<MutableState<Long?>>(activity, "frameGenActiveGameId\$delegate").value = 77L
|
||||
ReflectionHelpers.getField<MutableState<String?>>(activity, "frameGenActiveGameName\$delegate").value = "Castle Crashers"
|
||||
ReflectionHelpers.callInstanceMethod<Any?>(activity, "refreshInputProfile")
|
||||
val options = ReflectionHelpers.getField<MutableState<List<Pair<String, String>>>>(activity, "layoutOptions\$delegate").value
|
||||
assertEquals(ControlsChoice.NEW to "+ New for Castle Crashers", options.last())
|
||||
val options = ReflectionHelpers.getField<MutableState<List<ControlsChoice.Option>>>(activity, "layoutOptions\$delegate").value
|
||||
assertEquals(ControlsChoice.NEW to "+ New for Castle Crashers", options.last().let { it.id to it.name })
|
||||
ReflectionHelpers.callInstanceMethod<Any?>(activity, "chooseLayout", ReflectionHelpers.ClassParameter.from(String::class.java, ControlsChoice.NEW))
|
||||
val editor = ReflectionHelpers.getField<MutableState<Triple<String, String, String>?>>(activity, "layoutEditor\$delegate").value!!
|
||||
assertEquals(GameControls.bindings(activity, 77), editor.third)
|
||||
@@ -115,11 +115,87 @@ class ControlsChoiceTest {
|
||||
}
|
||||
|
||||
@Test fun aGameWithItsOwnLayoutCanGoBackToTheDefault() {
|
||||
assertTrue(ControlsChoice.options(context, 42L, steamMode = true, gameName = "Game").none { it.first == ControlsChoice.DEFAULT })
|
||||
assertTrue(ControlsChoice.options(context, 42L, steamMode = true, gameName = "Game").none { it.id == ControlsChoice.DEFAULT })
|
||||
ControlsChoice.newForGame(context, 42L, "Game", desktop = false)
|
||||
assertTrue(ControlsChoice.options(context, 42L, steamMode = true, gameName = "Game").first().first == ControlsChoice.DEFAULT)
|
||||
assertTrue(ControlsChoice.options(context, 42L, steamMode = true, gameName = "Game").first().id == ControlsChoice.DEFAULT)
|
||||
ControlsChoice.choose(context, 42L, ControlsChoice.DEFAULT, desktop = false)
|
||||
assertFalse(ControlsChoice.hasOwn(context, 42L))
|
||||
assertTrue(ControlsChoice.options(context, 42L, steamMode = true, gameName = "Game").none { it.first == ControlsChoice.DEFAULT })
|
||||
assertTrue(ControlsChoice.options(context, 42L, steamMode = true, gameName = "Game").none { it.id == ControlsChoice.DEFAULT })
|
||||
}
|
||||
|
||||
@Test fun aLayoutMadeForOneGameIsListedOnlyForThatGame() {
|
||||
val (layoutId, _) = ControlsChoice.newForGame(context, 7, "Castle Crashers", desktop = false)
|
||||
val mine = ControlsChoice.options(context, 7, steamMode = true, gameName = "Castle Crashers").first { it.id == layoutId }
|
||||
assertEquals(context.getString(R.string.osc_layout_detail_game, "Castle Crashers"), mine.detail)
|
||||
assertFalse(mine.deletable)
|
||||
assertTrue(ControlsChoice.options(context, 8, steamMode = true, gameName = "Portal").none { it.id == layoutId })
|
||||
assertTrue(ControlsChoice.options(context, null, steamMode = true).none { it.id == layoutId })
|
||||
ControlsChoice.useDefault(context, 7)
|
||||
assertTrue(ControlsChoice.options(context, 8, steamMode = true, gameName = "Portal").none { it.id == layoutId })
|
||||
assertTrue(ControlsChoice.options(context, 7, steamMode = true, gameName = "Castle Crashers").first { it.id == layoutId }.deletable)
|
||||
}
|
||||
|
||||
@Test fun anUnusedLayoutCanBeDeletedButNotOneInUse() {
|
||||
val source = bigSticks()
|
||||
assertTrue(ControlsChoice.options(context, null, steamMode = true).first { it.id == source }.deletable)
|
||||
ControlsChoice.choose(context, null, source, desktop = false)
|
||||
assertFalse(ControlsChoice.options(context, null, steamMode = true).first { it.id == source }.deletable)
|
||||
ControlsChoice.choose(context, null, InputLibraries.OVERLAY, desktop = false)
|
||||
ControlsChoice.choose(context, 7, source, desktop = false, gameName = "Castle Crashers")
|
||||
assertFalse(ControlsChoice.options(context, null, steamMode = true).first { it.id == source }.deletable)
|
||||
assertNull(ControlsChoice.options(context, 8, steamMode = true, gameName = "Portal").first { it.id == source }.detail)
|
||||
ControlsChoice.useDefault(context, 7)
|
||||
ControlsChoice.delete(context, source)
|
||||
val library = InputLibraries.read(context)
|
||||
assertTrue(library.layouts.none { it.id == source })
|
||||
assertTrue(library.bindings.none { it.layoutId == source })
|
||||
assertTrue(ControlsChoice.options(context, null, steamMode = true).none { it.id == source })
|
||||
}
|
||||
|
||||
@Test fun deletingALayoutAlsoRemovesAProfileThatCanNoLongerBeChosen() {
|
||||
InputLibraries.update(context) { it.duplicateProfile(InputProfile.GAME, "Game2") }
|
||||
val profile = InputLibraries.read(context).profiles.first { it.name == "Game2" }
|
||||
val layout = InputLibraries.read(context).layout(profile.id, InputRole.PRIMARY)!!
|
||||
assertEquals("Game2 / primary", layout.name)
|
||||
assertTrue(ControlsChoice.options(context, null, steamMode = true).first { it.id == layout.id }.deletable)
|
||||
ControlsChoice.delete(context, layout.id)
|
||||
val library = InputLibraries.read(context)
|
||||
assertTrue(library.profiles.none { it.id == profile.id })
|
||||
assertTrue(library.layouts.none { it.id == layout.id })
|
||||
assertTrue(profile.parts.values.none { part -> library.bindings.any { it.id == part.bindings } })
|
||||
assertEquals(InputLibraries.OVERLAY, ControlsChoice.current(context, null, steamMode = true))
|
||||
}
|
||||
|
||||
@Test fun steamTouchSavedForAGameFallsBackOutsideSteamWithANote() {
|
||||
ControlsChoice.choose(context, 7, GameControls.STEAM, desktop = false, gameName = "Portal")
|
||||
assertEquals(GameControls.STEAM, ControlsChoice.current(context, 7, steamMode = true))
|
||||
assertFalse(ControlsChoice.steamUnavailable(context, 7, steamMode = true))
|
||||
assertEquals(InputLibraries.OVERLAY, ControlsChoice.current(context, 7, steamMode = false))
|
||||
assertTrue(ControlsChoice.steamUnavailable(context, 7, steamMode = false))
|
||||
assertFalse(ControlsChoice.steamUnavailable(context, 8, steamMode = false))
|
||||
assertTrue(ControlsChoice.options(context, 7, steamMode = false, gameName = "Portal").none { it.id == GameControls.STEAM })
|
||||
}
|
||||
|
||||
@Test fun aLayoutNamedAfterTheGameThatDrawsItCountsAsThatGamesOwn() {
|
||||
val source = bigSticks()
|
||||
InputLibraries.update(context) { it.withLayout(it.layouts.first { l -> l.id == source }.copy(name = "ARMSX1")) }
|
||||
ControlsChoice.choose(context, 7, source, desktop = false, gameName = "ARMSX1")
|
||||
assertTrue(ControlsChoice.options(context, 8, steamMode = true, gameName = "Portal").none { it.id == source })
|
||||
assertEquals(context.getString(R.string.osc_layout_detail_game, "ARMSX1"),
|
||||
ControlsChoice.options(context, 7, steamMode = true, gameName = "ARMSX1").first { it.id == source }.detail)
|
||||
}
|
||||
|
||||
@Test fun aLayoutTheGameProfileStillListsCanBeDeletedOnceAnotherIsChosen() {
|
||||
val source = bigSticks()
|
||||
InputLibraries.update(context) { it.chooseLayout(InputProfile.GAME, InputRole.PRIMARY, source) }
|
||||
assertEquals(source, ControlsChoice.current(context, null, steamMode = true))
|
||||
assertFalse(ControlsChoice.options(context, null, steamMode = true).first { it.id == source }.deletable)
|
||||
ControlsChoice.choose(context, null, InputLibraries.OVERLAY, desktop = false)
|
||||
assertTrue(ControlsChoice.options(context, null, steamMode = true).first { it.id == source }.deletable)
|
||||
ControlsChoice.delete(context, source)
|
||||
val library = InputLibraries.read(context)
|
||||
assertTrue(library.layouts.none { it.id == source })
|
||||
assertEquals(InputLibraries.OVERLAY, library.profile(InputProfile.GAME).parts.getValue(InputRole.PRIMARY).layout)
|
||||
assertEquals(InputLibraries.OVERLAY, ControlsChoice.current(context, null, steamMode = true))
|
||||
}
|
||||
}
|
||||
@@ -113,6 +113,56 @@ class KitLayoutTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aSideCutoutOnlyMovesTheOverlappingCluster() {
|
||||
val w = 2400
|
||||
val h = 1080
|
||||
val plain = KitLayout.elements(context, PadKit.STEAM_DECK, w, h, rearButtons = false, trackpads = false)
|
||||
val left = Rect(10, 380, 120, 480)
|
||||
val right = Rect(w - 120, 380, w, 480)
|
||||
val adjusted = KitLayout.elements(context, PadKit.STEAM_DECK, w, h, Rect(120, 0, 120, 0),
|
||||
cutouts = listOf(left, right), rearButtons = false, trackpads = false)
|
||||
val face = setOf("legacy:a", "legacy:b", "legacy:x", "legacy:y")
|
||||
val xOffsets = plain.zip(adjusted).associate { (before, after) ->
|
||||
assertEquals(before.id, after.id)
|
||||
assertEquals(before.y, after.y, .00001f)
|
||||
assertEquals(before.width, after.width, .00001f)
|
||||
assertEquals(before.height, after.height, .00001f)
|
||||
assertTrue(after.x * w >= left.right || (after.x + after.width) * w <= left.left ||
|
||||
after.y * h >= left.bottom || (after.y + after.height) * h <= left.top)
|
||||
assertTrue(after.x * w >= right.right || (after.x + after.width) * w <= right.left ||
|
||||
after.y * h >= right.bottom || (after.y + after.height) * h <= right.top)
|
||||
before.id to (after.x - before.x) * w
|
||||
}
|
||||
assertTrue(xOffsets.getValue(KitLayout.DPAD_ID) in 1f..100f)
|
||||
assertTrue(xOffsets.getValue("legacy:b") in -100f..-1f)
|
||||
for ((id, offset) in xOffsets) if (id in face) assertEquals(xOffsets.getValue("legacy:b"), offset, .01f)
|
||||
else if (id != KitLayout.DPAD_ID) assertEquals(id, 0f, offset, .01f)
|
||||
assertTrue(overlapping(adjusted, w, h).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aCutoutShiftDoesNotCoverAnAddedControl() {
|
||||
val w = 2400
|
||||
val h = 1080
|
||||
val safe = Rect(120, 0, 0, 0)
|
||||
val extra = InputSurfaceElement(InputControl.B, .05f, .4f, .025f, .06f, id = "added")
|
||||
val layout = SavedInputLayout(InputLibraries.OVERLAY, "Gamepad", listOf(extra), aspect = w.toFloat() / h)
|
||||
val fallback = OnScreenLayout.elements(context, layout, w, h, safe, rearButtons = false, trackpads = false)
|
||||
val placed = OnScreenLayout.elements(context, layout, w, h, safe, cutouts = listOf(Rect(0, 380, 120, 480)),
|
||||
rearButtons = false, trackpads = false)
|
||||
assertEquals(fallback, placed)
|
||||
assertTrue(overlapping(placed, w, h).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun startAndSelectAreOnTheFloatingOverlayBottomRow() {
|
||||
for (kit in PadKit.entries) for ((w, h) in sizes) {
|
||||
val buttons = KitLayout.elements(context, kit, w, h)
|
||||
val keyboard = buttons.single { it.id == KitLayout.KEYBOARD_ID }
|
||||
for (button in buttons.filter { it.control == InputControl.SELECT || it.control == InputControl.START }) {
|
||||
assertTrue("$kit $w x $h ${button.id}", button.y + button.height / 2 in keyboard.y..(keyboard.y + keyboard.height))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun widerScreensSpreadTheControlsInsteadOfStretchingThem() {
|
||||
for (kit in PadKit.entries) {
|
||||
val narrow = KitLayout.elements(context, kit, 1920, 1080).associateBy { it.id }
|
||||
|
||||
@@ -32,6 +32,36 @@ class ShowLayoutTest {
|
||||
view.releaseInputs()
|
||||
}
|
||||
|
||||
@Test fun overlayExtrasAreIndependentAndKeepTheirPreferencesWhenRecreated() {
|
||||
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
|
||||
val kit = SavedInputLayout(InputLibraries.OVERLAY, "Gamepad")
|
||||
val grips = setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5)
|
||||
val trackpads = setOf(InputControl.LEFT_PAD, InputControl.RIGHT_PAD)
|
||||
fun controls(dock: OnScreenLayout.Dock? = null, layout: SavedInputLayout = kit): OnScreenControls =
|
||||
OnScreenControls(context, null, dock).also { it.updateLayout(layout); sized(it, 1920, 1080) }
|
||||
fun shown(view: OnScreenControls) = view.inputSurface.shownElements.map { it.control }.toSet()
|
||||
val overlay = controls()
|
||||
assertTrue(shown(overlay).intersect(grips + trackpads).isEmpty())
|
||||
SessionPrefs.setOscRearButtons(context, true)
|
||||
overlay.reload()
|
||||
assertTrue(shown(overlay).containsAll(grips))
|
||||
assertTrue(shown(overlay).intersect(trackpads).isEmpty())
|
||||
SessionPrefs.setOscTrackpads(context, true)
|
||||
SessionPrefs.setOscRearButtons(context, false)
|
||||
assertTrue(shown(controls()).containsAll(trackpads))
|
||||
assertTrue(shown(controls()).intersect(grips).isEmpty())
|
||||
|
||||
SessionPrefs.setOscTrackpads(context, false)
|
||||
val customPad = InputSurfaceElement(InputControl.LEFT_PAD, .4f, .4f, .15f, .15f, id = "custom-pad")
|
||||
val edited = kit.copy(elements = listOf(customPad,
|
||||
InputSurfaceElement(InputControl.RIGHT_PAD, .6f, .4f, .15f, .15f, id = "legacy:right-pad")))
|
||||
assertEquals(listOf(customPad.id), controls(layout = edited).inputSurface.shownElements.map { it.id })
|
||||
|
||||
val dock = OnScreenLayout.Dock(portrait = true, grips = true)
|
||||
val panel = OnScreenControls(context, null, dock).also { it.updateLayout(kit); sized(it, 1080, 1300) }
|
||||
assertTrue(shown(panel).containsAll(grips + trackpads))
|
||||
}
|
||||
|
||||
@Test fun aSavedLayoutIsDrawnAsSaved() {
|
||||
val saved = listOf(InputSurfaceElement(InputControl.A, .4f, .4f, .1f, .1f))
|
||||
val view = InputSurfaceView(context)
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class LightPauseTest {
|
||||
@Test
|
||||
fun theBounceAloneResumesLight() {
|
||||
val pause = LightPause()
|
||||
pause.paused(bounces = 3)
|
||||
assertEquals(LightPause.Resume.LIGHT, pause.resumed(bounces = 4))
|
||||
assertFalse(pause.timedOut())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anUnrelatedPauseWithoutABounceCleansUpAtTheTimeout() {
|
||||
val pause = LightPause()
|
||||
pause.paused(bounces = 3)
|
||||
assertTrue(pause.timedOut())
|
||||
assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 3))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aBounceWhileAnotherActivityHoldsThePauseStillCleansUpAtTheTimeout() {
|
||||
val pause = LightPause()
|
||||
pause.paused(bounces = 3)
|
||||
assertTrue(pause.timedOut())
|
||||
assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 4))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aResumeBeforeTheTimeoutWithoutABounceCleansUpFirst() {
|
||||
val pause = LightPause()
|
||||
pause.paused(bounces = 3)
|
||||
assertEquals(LightPause.Resume.CLEANUP_FIRST, pause.resumed(bounces = 3))
|
||||
assertFalse(pause.timedOut())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aStopAfterALightPauseCleansUpOnce() {
|
||||
val pause = LightPause()
|
||||
pause.paused(bounces = 3)
|
||||
assertTrue(pause.stopped())
|
||||
assertFalse(pause.timedOut())
|
||||
assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 4))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aNormalPauseIsUntouched() {
|
||||
val pause = LightPause()
|
||||
assertFalse(pause.stopped())
|
||||
assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 0))
|
||||
}
|
||||
}
|
||||
@@ -88,4 +88,17 @@ class SteamGameProcessTest {
|
||||
process("301", "reaper", "SteamLaunch", "AppId=351710", "--", "proton", "waitforexitandrun", "game.exe")
|
||||
assertTrue(SteamGameProcess.running("351710", proc))
|
||||
}
|
||||
|
||||
@Test fun onlyTheRunningCurrentGameCountsAsAlreadyRunning() {
|
||||
val proc = tmp.newFolder("proc-relaunch")
|
||||
File(proc, "200").apply { mkdirs() }.resolve("cmdline")
|
||||
.writeBytes(cmdline("reaper", "SteamLaunch", "AppId=584400", "--", "proton", "waitforexitandrun", "SonicMania.exe"))
|
||||
assertTrue(SteamGameProcess.alreadyRunning("584400", "584400", proc))
|
||||
assertFalse(SteamGameProcess.alreadyRunning("584400", "311340", proc))
|
||||
assertFalse(SteamGameProcess.alreadyRunning("311340", "311340", proc))
|
||||
assertFalse(SteamGameProcess.alreadyRunning("584400", null, proc))
|
||||
val shortcutId = ((584400uL shl 32) or 0x02000000uL).toString()
|
||||
assertTrue(SteamGameProcess.alreadyRunning(shortcutId, "584400", proc))
|
||||
assertTrue(SteamGameProcess.alreadyRunning("584400", shortcutId, proc))
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.ComponentCallbacks2
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class TopUnderPressureTest {
|
||||
@Test
|
||||
fun onlyRunningLevelsCountAsPressure() {
|
||||
assertTrue(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL))
|
||||
assertTrue(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW))
|
||||
assertFalse(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE))
|
||||
assertFalse(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reclaimsOnlyDuringASessionShortlyAfterPressure() {
|
||||
assertTrue(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = true, finishing = false))
|
||||
assertFalse(TopUnderPressure.shouldReclaim(20_000, 9_500, sessionRunning = true, finishing = false))
|
||||
assertFalse(TopUnderPressure.shouldReclaim(10_000, 0, sessionRunning = true, finishing = false))
|
||||
assertFalse(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = false, finishing = false))
|
||||
assertFalse(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = true, finishing = true))
|
||||
}
|
||||
}
|
||||
@@ -315,6 +315,15 @@ class RockstarTest {
|
||||
assertEquals("ThirdParty/Steam/steam_api64.dll", build.files[1].path)
|
||||
}
|
||||
|
||||
@Test fun theSocialClubInstallerIsTakenFromTheLauncherBuild() {
|
||||
fun file(path: String) = RockstarFile("1", "1", path, 1, "", emptyList())
|
||||
val launcher = RockstarBuild("1", "1", false, listOf(file("Launcher.exe"),
|
||||
file("Redistributables/SocialClub/old/social-club-setup.exe"), file("Redistributables/SocialClub/Social-Club-Setup.exe")))
|
||||
assertEquals("Redistributables/SocialClub/Social-Club-Setup.exe", RockstarManifest.sdkInstaller(launcher)?.path)
|
||||
assertNull(RockstarManifest.sdkInstaller(RockstarBuild("1", "1", false, listOf(file("Launcher.exe"), file("Social-Club-Setup.exe.sig")))))
|
||||
assertEquals("Redistributables/Social-Club-Setup.exe", RockstarLaunch.SDK_INSTALLER)
|
||||
}
|
||||
|
||||
@Test fun pathsThatLeaveTheInstallAreRefused() {
|
||||
assertNull(RockstarManifest.safePath("..\\..\\Windows\\x.dll"))
|
||||
assertNull(RockstarManifest.safePath("C:\\x.dll"))
|
||||
|
||||
@@ -156,6 +156,20 @@ class InputSettingsTest {
|
||||
compose.runOnIdle { assertEquals(SessionPrefs.OSC_NEVER, SessionPrefs.oscMode(context)) }
|
||||
}
|
||||
|
||||
@Test fun theLayoutMenuDescribesEachChoiceAndDeletesAnUnusedLayout() {
|
||||
InputLibraries.update(context) { it.copyLayout(InputLibraries.OVERLAY, "Big sticks", "big-sticks") }
|
||||
compose.setContent { DroidDeckTheme { InputSettingsPage({}) } }
|
||||
compose.onNodeWithTag("setting-osc-layout").performScrollTo().performClick()
|
||||
compose.onNodeWithText(context.getString(R.string.osc_layout_gamepad_detail)).assertExists()
|
||||
compose.onNodeWithText(context.getString(R.string.osc_layout_steam_detail)).assertExists()
|
||||
compose.onNodeWithTag("osc-delete-${InputLibraries.OVERLAY}").assertDoesNotExist()
|
||||
compose.onNodeWithTag("osc-delete-big-sticks").performClick()
|
||||
compose.onNodeWithTag("osc-delete-confirm").performClick()
|
||||
compose.runOnIdle { assertTrue(InputLibraries.read(context).layouts.none { it.id == "big-sticks" }) }
|
||||
compose.onNodeWithTag("setting-osc-layout").performScrollTo().performClick()
|
||||
compose.onNodeWithText("Big sticks").assertDoesNotExist()
|
||||
}
|
||||
|
||||
@Test fun choosingTheDefaultLayoutAppliesToGamesWithoutTheirOwn() {
|
||||
InputLibraries.update(context) { it.copyLayout(InputLibraries.OVERLAY, "Big sticks", "big-sticks") }
|
||||
ControlsChoice.newForGame(context, 7, "Castle Crashers", desktop = false)
|
||||
|
||||
@@ -1,20 +1,24 @@
|
||||
# Keep-top guard A/B on dual screens
|
||||
|
||||
`KeepTopActivity` (#2763) covers every other display while a session is on top, so that
|
||||
display's home is not its top activity. On the Thor, lmkd kills the bottom home under memory
|
||||
pressure, Android relaunches it to the front (`wm_task_to_front`), the session loses the top
|
||||
spot, drops to adj 50 and is killed in lmkd's next pass.
|
||||
`KeepTopActivity` (#2763, removed in the change that added this section) covered every other
|
||||
display while a session was on top, so that display's home was not its top activity. The
|
||||
reasoning: on the Thor, lmkd kills the bottom home under memory pressure, Android relaunches it
|
||||
to the front, the session loses the top spot, drops to adj 50 and is killed next.
|
||||
|
||||
Android gives a translucent activity that is alone in its task an `ActivityRecordInputSink`
|
||||
that consumes every touch inside the task bounds, whatever the window's flags say
|
||||
(`ENABLE_TOUCH_OPAQUE_ACTIVITIES`, on for DroidDeck's target SDK; see
|
||||
`services/core/java/com/android/server/wm/ActivityRecordInputSink.java`). The guard's
|
||||
`FLAG_NOT_TOUCHABLE` therefore did nothing: with the dual-screen panel closed, the bottom
|
||||
screen took no touch until the session ended, and the guard also stayed over it after Home.
|
||||
It had three side effects:
|
||||
|
||||
The guard now takes touches itself. A touch removes it from that display. It comes back when
|
||||
the session is top-resumed again, or after 5 s if the session kept the top spot (one touch on
|
||||
the bottom screen, then back to the game). Stopping or entering PiP removes the guards.
|
||||
- Android gives a translucent activity alone in its task an `ActivityRecordInputSink` that
|
||||
consumes every touch in the task bounds whatever the window's flags say
|
||||
(`ENABLE_TOUCH_OPAQUE_ACTIVITIES`), so the bottom screen took no touch (#2910 worked around it).
|
||||
- Cocoon tracks the top activity of each display; with a DroidDeck activity on the bottom it
|
||||
could not suspend or resume DroidDeck properly.
|
||||
- The Thor's `com.odin.gameassistant` gives every app with an activity on top of the bottom
|
||||
display that display's volume (`secondary_screen_volume_level`). With the guard up, all of
|
||||
DroidDeck's audio played at the bottom screen's volume (AudioFlinger track gain -37, -13 and
|
||||
-2.6 dB at levels 3, 8 and 13; -7.4 dB, the top level, once the guard was removed).
|
||||
|
||||
The A/B below found no case on either device where the guard kept the session alive, so it was
|
||||
removed.
|
||||
|
||||
## Tool
|
||||
|
||||
@@ -25,6 +29,7 @@ build that has the debugging tools:
|
||||
python3 tools/memory_guard_ab.py --label main --apk main.apk states
|
||||
python3 tools/memory_guard_ab.py --label fix --apk fix.apk states
|
||||
python3 tools/memory_guard_ab.py --label fix pressure --stop-mb 650 --hold 30 --runs 3
|
||||
python3 tools/memory_guard_ab.py --label fix pressure --burst --stop-mb 1500 --hold 20 --runs 3
|
||||
python3 tools/memory_guard_ab.py --label fix summarize ~/.cache/droiddeck-memory-guard-ab/fix-stop650-1-events.txt
|
||||
```
|
||||
|
||||
@@ -39,6 +44,13 @@ event log of every probe.
|
||||
`--stop-mb`, holds it, and releases it. zram cannot compress that data and no app owns it,
|
||||
so lmkd keeps killing by adj. It records lmkd's `killinfo`, process deaths, focus loss and
|
||||
whether DroidDeck survived.
|
||||
- `pressure --burst` takes everything above `--stop-mb` at once instead: it copies a 256 MiB
|
||||
random file into the tmpfs with all copies running in parallel (about 5 GiB in 2 to 3 s on a
|
||||
Thor), the way a game's GPU allocation burst lands on lmkd.
|
||||
- `oom_score_adj` is read without `su`. Under pressure lmkd keeps killing the root manager app,
|
||||
and a `su` call can then open its request screen on top of the game.
|
||||
- If the bottom display has no home (a killed home is not always restarted), the visible app on
|
||||
top of it stands in.
|
||||
- `--bottom-tap` must point at an inert spot of the bottom home; `--panel-close` at the
|
||||
panel's close button. Both are fractions of the bottom display.
|
||||
- `am start` of `SessionActivity` needs `--display 0`; without it, it creates a second
|
||||
@@ -88,3 +100,24 @@ moves it to the front, even with no guard. The Thor's focus steal does not happe
|
||||
Duo shows that the guard covers the same states as before, not that it saves the session. That
|
||||
needs a Thor: run `states` and `pressure --stop-mb` near its adj-50 level on `main` and on the
|
||||
fix, and look for `task_to_front` and `session_top_lost` before `droiddeck_died_at_adj` 50.
|
||||
|
||||
## Results: AYN Thor (12 GB), Android 13
|
||||
|
||||
Builds: `main` (56986b5, guard with the #2910 touch yield) and `no-guard` (`main` with
|
||||
`guardOtherDisplays` returning at once). The game was focused on the top screen in every run.
|
||||
|
||||
| Pressure | Bottom app | no-guard | main |
|
||||
| --- | --- | --- | --- |
|
||||
| Fill to 650 MB free, hold 30 s | stock launcher | survived 1/1 usable run (launcher not reached) | survived 3/3 (launcher killed 80, 25, 0 times) |
|
||||
| Fill to 550 MB free, hold 30 s | Cocoon as home | survived 3/3, Cocoon killed 387, 400, 84 times | survived 3/3, Cocoon killed 384, 127, 338 times |
|
||||
| Burst to 400 MB free (about 5 GB in 2.5 to 3.4 s) | stock launcher | killed at adj 0 in 3/3 | killed at adj 0 in 3/3 |
|
||||
| Burst to 1500 MB free (2.0 to 2.4 s) | stock launcher | survived 1/2, killed at adj 0 in 1/2 | killed at adj 0 in 2/2 |
|
||||
|
||||
No run on either build lost the top spot (`wm_on_top_resumed_lost_called` for
|
||||
`SessionActivity`), moved a task to the front, or killed DroidDeck at adj 50. A killed bottom
|
||||
home is either restarted in place or its task disappears and the next app shows on the bottom
|
||||
screen, without taking focus. A burst big enough to matter makes lmkd kill the foreground
|
||||
session at adj 0, which no activity on another display can prevent.
|
||||
|
||||
`kill -9` of the bottom app (`states`) is noisy on a Thor with many recent apps: each kill
|
||||
surfaces the next app on the bottom screen, and every tap the tool sends there moves focus.
|
||||
@@ -364,6 +364,12 @@ def rockstar_launcher_log(compat_data, limit=65536):
|
||||
return [line.strip() for line in data.decode("utf-8", "replace").splitlines() if line.strip()]
|
||||
|
||||
|
||||
def ships_sdk(root, exe):
|
||||
return any(directory.is_dir() and any(p.is_file() and not p.is_symlink() and p.name.lower() in ("socialclub.dll", "socialclub64.dll")
|
||||
for p in directory.iterdir())
|
||||
for directory in {root, exe.parent})
|
||||
|
||||
|
||||
def rockstar_sdk(folder, sidecar):
|
||||
if str(sidecar.get("id")) in ("gta4", "lanoire"):
|
||||
return True
|
||||
@@ -371,10 +377,8 @@ def rockstar_sdk(folder, sidecar):
|
||||
exe = (folder / str(sidecar.get("exe") or "").replace("\\", "/")).resolve()
|
||||
if not exe.is_relative_to(root):
|
||||
return False
|
||||
for directory in {root, exe.parent}:
|
||||
if directory.is_dir() and any(p.is_file() and not p.is_symlink() and p.name.lower() in ("socialclub.dll", "socialclub64.dll")
|
||||
for p in directory.iterdir()):
|
||||
return True
|
||||
if ships_sdk(root, exe):
|
||||
return True
|
||||
if str(sidecar.get("id")) in ROCKSTAR_TITLES:
|
||||
return False
|
||||
level = [root]
|
||||
@@ -543,7 +547,15 @@ def prepare_rockstar(folder, sidecar, compat_data, launch_dir, proton="", ask_ap
|
||||
return "prefix-" + made
|
||||
arch = "x86" if signature[4:] == b"\x4c\x01" else "x64"
|
||||
if sdk:
|
||||
log("rockstar runtime: " + rockstar_runtime(folder, exe, compat_data, arch))
|
||||
runtime = rockstar_runtime(folder, exe, compat_data, arch)
|
||||
if runtime == "game-runtime" and not ships_sdk(root, exe):
|
||||
answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "rockstar-sdk", "store": "rockstar", "id": str(sidecar.get("id"))},
|
||||
timeout=SERVICE_WAIT)
|
||||
if isinstance(answer, dict) and answer.get("ok"):
|
||||
runtime = rockstar_runtime(folder, exe, compat_data, arch)
|
||||
else:
|
||||
runtime = "sdk-" + (str(answer.get("reason") or "refused") if isinstance(answer, dict) else "timeout")
|
||||
log("rockstar runtime: " + runtime)
|
||||
if not rockstar_registry(folder, title, compat_data, proton, sdk_arch=arch if sdk else None):
|
||||
return "registry-unavailable"
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -111,6 +111,9 @@ typedef int (*accept4_fn)(int, struct sockaddr *, socklen_t *, int);
|
||||
static unsigned guarded_port(void);
|
||||
|
||||
__attribute__((visibility("hidden"))) int dd_udevmon_stand_in(int fd);
|
||||
__attribute__((visibility("hidden"))) int dd_udevmon_bind(int fd, const struct sockaddr *addr, socklen_t len,
|
||||
int (*real_bind)(int, const struct sockaddr *, socklen_t),
|
||||
int *rc);
|
||||
__attribute__((visibility("hidden"))) int dd_nl_bind(int fd, const struct sockaddr *addr,
|
||||
socklen_t len, int *rc);
|
||||
__attribute__((visibility("hidden"))) int dd_nl_connect(int fd, const struct sockaddr *addr,
|
||||
@@ -121,6 +124,7 @@ int bind(int fd, const struct sockaddr *addr, socklen_t len) {
|
||||
int nl_rc;
|
||||
if (!real) real = (bind_fn)dlsym(RTLD_NEXT, "bind");
|
||||
if (dd_nl_bind(fd, addr, len, &nl_rc)) return nl_rc;
|
||||
if (dd_udevmon_bind(fd, addr, len, real, &nl_rc)) return nl_rc;
|
||||
if (dd_udevmon_stand_in(fd)) {
|
||||
if (addr == NULL || len < sizeof(struct sockaddr_nl) || addr->sa_family != AF_NETLINK) {
|
||||
errno = EINVAL;
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#include <sys/stat.h>
|
||||
#include <endian.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
|
||||
struct stand_in {
|
||||
@@ -146,6 +147,61 @@ __attribute__((visibility("hidden"))) int dd_udevmon_stand_in(int fd) {
|
||||
return is_stand_in(fd);
|
||||
}
|
||||
|
||||
static int subscribed(int fd) {
|
||||
#ifdef UDEVMON_TEST
|
||||
if (getenv("DD_UDEVMON_REFUSE") != NULL) return 0;
|
||||
#endif
|
||||
struct sockaddr_nl nl;
|
||||
socklen_t len = sizeof(nl);
|
||||
memset(&nl, 0, sizeof(nl));
|
||||
return getsockname(fd, (struct sockaddr *)&nl, &len) == 0 && nl.nl_groups != 0;
|
||||
}
|
||||
|
||||
/* Android lets an app open a uevent socket but not join its multicast groups, and libudev joins none
|
||||
when no udev daemon runs, so a monitor bound there hears nothing. Such a socket is replaced, under
|
||||
the same descriptor, by a stand-in. */
|
||||
__attribute__((visibility("hidden"))) int dd_udevmon_bind(int fd, const struct sockaddr *addr, socklen_t len,
|
||||
int (*real_bind)(int, const struct sockaddr *, socklen_t),
|
||||
int *rc) {
|
||||
int protocol = -1;
|
||||
socklen_t protocol_len = sizeof(protocol);
|
||||
if (addr == NULL || len < sizeof(struct sockaddr_nl) || addr->sa_family != AF_NETLINK) return 0;
|
||||
if (is_stand_in(fd) || is_wine_process()) return 0;
|
||||
if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &protocol, &protocol_len) != 0 || protocol != NETLINK_KOBJECT_UEVENT)
|
||||
return 0;
|
||||
*rc = real_bind(fd, addr, len);
|
||||
int refused = errno;
|
||||
if (*rc == 0 && subscribed(fd)) return 1;
|
||||
int status = fcntl(fd, F_GETFL);
|
||||
int descriptor = fcntl(fd, F_GETFD);
|
||||
int sv[2];
|
||||
if (status < 0 || descriptor < 0 || socketpair(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0, sv) != 0) {
|
||||
errno = refused;
|
||||
return 1;
|
||||
}
|
||||
pthread_mutex_lock(&lock);
|
||||
size_t slot = sizeof(stand_ins) / sizeof(stand_ins[0]);
|
||||
for (size_t i = 0; i < sizeof(stand_ins) / sizeof(stand_ins[0]); i++) {
|
||||
if (stand_ins[i].fd == -1) { slot = i; break; }
|
||||
}
|
||||
if (slot == sizeof(stand_ins) / sizeof(stand_ins[0]) ||
|
||||
dup3(sv[0], fd, (descriptor & FD_CLOEXEC) ? O_CLOEXEC : 0) < 0) {
|
||||
pthread_mutex_unlock(&lock);
|
||||
close(sv[0]);
|
||||
close(sv[1]);
|
||||
errno = refused;
|
||||
return 1;
|
||||
}
|
||||
close(sv[0]);
|
||||
if (status & O_NONBLOCK) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
|
||||
stand_ins[slot].fd = fd;
|
||||
stand_ins[slot].peer = sv[1];
|
||||
stand_ins[slot].inode = socket_inode(fd);
|
||||
pthread_mutex_unlock(&lock);
|
||||
*rc = 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int getsockname(int fd, struct sockaddr *addr, socklen_t *len) {
|
||||
static int (*real_getsockname)(int, struct sockaddr *, socklen_t *);
|
||||
struct sockaddr_nl nl;
|
||||
|
||||
+72
-20
@@ -26,30 +26,52 @@ PACKAGE = "com.droiddeck.launcher"
|
||||
SESSION = f"{PACKAGE}/.SessionActivity"
|
||||
HOG_PATH = "/data/local/tmp/dd-memory-hog.sh"
|
||||
HOG_MOUNT = "/dev/dd-memory-hog"
|
||||
SEED_PATH = "/data/local/tmp/dd-memory-burst.bin"
|
||||
|
||||
# oom_score_adj is read without su: under pressure lmkd kills the root manager app, and each su call
|
||||
# can then open its request screen on top of the game.
|
||||
# Incompressible data in a private tmpfs: zram cannot shrink it and no app owns it, so lmkd keeps
|
||||
# killing by oom_score_adj while it is held.
|
||||
HOG = f"""#!/system/bin/sh
|
||||
stop_mb=$1; hold=$2
|
||||
cleanup() {{ rm -f {HOG_MOUNT}/f*; umount {HOG_MOUNT} 2>/dev/null; }}
|
||||
stop_mb=$1; hold=$2; mode=$3
|
||||
cleanup() {{ kill $(jobs -p) 2>/dev/null; rm -f {HOG_MOUNT}/f*; umount {HOG_MOUNT} 2>/dev/null; }}
|
||||
trap 'cleanup; exit 1' HUP INT TERM
|
||||
mkdir -p {HOG_MOUNT}
|
||||
grep -q ' {HOG_MOUNT} ' /proc/mounts || mount -t tmpfs -o size=16g tmpfs {HOG_MOUNT}
|
||||
i=0
|
||||
i=0; failed=0
|
||||
if [ "$mode" = burst ]; then
|
||||
[ "$(stat -c %s {SEED_PATH} 2>/dev/null)" = 268435456 ] ||
|
||||
{{ head -c 268435456 /dev/urandom > {SEED_PATH}.tmp && mv {SEED_PATH}.tmp {SEED_PATH}; }} ||
|
||||
{{ rm -f {SEED_PATH}.tmp; cleanup; exit 1; }}
|
||||
cat {SEED_PATH} > /dev/null
|
||||
avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo)
|
||||
echo "avail=$avail"
|
||||
take=$((avail - stop_mb))
|
||||
[ "$take" -gt 0 ] || {{ echo "nothing to take"; cleanup; exit 2; }}
|
||||
n=$((take / 256)); rest=$((take % 256)); pids=""
|
||||
echo "burst_mb=$take start=$(date +%s%N)"
|
||||
while [ $i -lt $n ]; do cat {SEED_PATH} > {HOG_MOUNT}/f$i & pids="$pids $!"; i=$((i+1)); done
|
||||
[ "$rest" -gt 0 ] && {{ head -c $((rest * 1048576)) {SEED_PATH} > {HOG_MOUNT}/f$i & pids="$pids $!"; }}
|
||||
for pid in $pids; do wait "$pid" || failed=1; done
|
||||
echo "burst_done=$(date +%s%N)"
|
||||
echo "avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo)"
|
||||
i=512
|
||||
fi
|
||||
while [ $i -lt 512 ]; do
|
||||
avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo)
|
||||
echo "avail=$avail"
|
||||
[ "$avail" -le "$stop_mb" ] && break
|
||||
head -c 33554432 /dev/urandom > {HOG_MOUNT}/f$i || break
|
||||
head -c 33554432 /dev/urandom > {HOG_MOUNT}/f$i || {{ failed=1; break; }}
|
||||
i=$((i+1))
|
||||
done
|
||||
[ "$failed" = 0 ] || {{ echo "write failed"; cleanup; exit 1; }}
|
||||
sleep "$hold"
|
||||
cleanup
|
||||
echo released
|
||||
"""
|
||||
# Stops a writer left by an interrupted run before its files go, so the unmount does not fail. The
|
||||
# bracketed patterns keep pkill from matching the shell that runs this line.
|
||||
HOG_CLEANUP = (f"pkill -f '[d]d-memory-hog.sh'; pkill -f '[h]ead -c 33554432'; sleep 1; rm -f {HOG_MOUNT}/f*; "
|
||||
HOG_CLEANUP = (f"pkill -f '[d]d-memory-hog.sh'; pkill -f '[h]ead -c 33554432'; pkill -f '[d]d-memory-burst.bin'; sleep 1; rm -f {HOG_MOUNT}/f*; "
|
||||
f"umount {HOG_MOUNT} 2>/dev/null; true")
|
||||
|
||||
def focused_display(input_dump: str) -> int | None:
|
||||
@@ -58,7 +80,7 @@ def focused_display(input_dump: str) -> int | None:
|
||||
|
||||
|
||||
def activity_count(activities_dump: str, activity: str) -> int:
|
||||
return len(re.findall(r"Hist\s+#\d+: ActivityRecord\{\S+ u\d+ " + re.escape(activity) + r" ", activities_dump))
|
||||
return len(re.findall(r"Hist\s+#\d+: ActivityRecord\{\S+ u\d+ " + re.escape(activity) + r"[ }]", activities_dump))
|
||||
|
||||
|
||||
def guard_count(activities_dump: str) -> int:
|
||||
@@ -85,7 +107,8 @@ def panel_windows(windows_dump: str, display: int) -> int:
|
||||
|
||||
|
||||
def bottom_home(activities_dump: str, session_display: int) -> tuple[int, str] | None:
|
||||
display = None
|
||||
"""The visible home on another display, else the visible app on top of it."""
|
||||
display, top = None, None
|
||||
for line in activities_dump.splitlines():
|
||||
section = re.match(r"Display #(\d+) \(activities", line)
|
||||
if section:
|
||||
@@ -96,7 +119,10 @@ def bottom_home(activities_dump: str, session_display: int) -> tuple[int, str] |
|
||||
home = re.search(r"type=home A=\d+:(\S+) .*visible=true", line)
|
||||
if home:
|
||||
return display, home.group(1)
|
||||
return None
|
||||
app = re.search(r"type=standard A=\d+:([\w.]+) .*visible=true", line)
|
||||
if app and top is None and not app.group(1).startswith(PACKAGE):
|
||||
top = display, app.group(1)
|
||||
return top
|
||||
|
||||
|
||||
def logical_size(displays_dump: str, display: int) -> tuple[int, int] | None:
|
||||
@@ -151,8 +177,11 @@ class Device:
|
||||
return self.sh(f"su -c {shlex.quote(command)}", timeout=timeout)
|
||||
|
||||
def ctl(self, *args: str, timeout: int = 300) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run([str(TOOLS / "droiddeckctl"), "--adb", self.adb, "--serial", self.serial, *args],
|
||||
capture_output=True, text=True, timeout=timeout)
|
||||
command = [str(TOOLS / "droiddeckctl"), "--adb", self.adb, "--serial", self.serial, *args]
|
||||
try:
|
||||
return subprocess.run(command, capture_output=True, text=True, timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
return subprocess.CompletedProcess(command, -1, "", f"timed out after {timeout} s")
|
||||
|
||||
def phase(self) -> str | None:
|
||||
match = re.search(r'"phase":\s*"(\w+)"', self.ctl("state").stdout)
|
||||
@@ -208,7 +237,8 @@ class Bench:
|
||||
|
||||
def prepare(self, apk: str | None):
|
||||
self.d.sh("input keyevent KEYCODE_WAKEUP")
|
||||
self.d.ctl("stop")
|
||||
if self.d.ctl("stop", timeout=120).returncode != 0:
|
||||
self.d.sh(f"am force-stop {PACKAGE}")
|
||||
if apk:
|
||||
env = dict(os.environ, ADB_SERIAL=self.d.serial)
|
||||
subprocess.run([str(TOOLS / "deploy_local.sh"), apk], env=env, check=True, capture_output=True)
|
||||
@@ -234,7 +264,7 @@ class Bench:
|
||||
"guards": guard_count(activities),
|
||||
"sessions": session_count(activities),
|
||||
"panel": panel_windows(self.d.sh("dumpsys window windows"), display),
|
||||
"adj": int(self.d.su(f"cat /proc/{pid}/oom_score_adj").strip() or -9999),
|
||||
"adj": int(self.d.sh(f"cat /proc/{pid}/oom_score_adj").strip() or -9999),
|
||||
"pid": pid,
|
||||
}
|
||||
|
||||
@@ -251,7 +281,8 @@ class Bench:
|
||||
before = self.snapshot()
|
||||
_, home = self.bottom()
|
||||
self.d.run("logcat", "-b", "events", "-c")
|
||||
samples = self.d.su(f"kill -9 $(pidof {home}); for i in $(seq 50); do cat /proc/{before['pid']}/oom_score_adj"
|
||||
self.d.su(f"kill -9 $(pidof {home})")
|
||||
samples = self.d.sh(f"for i in $(seq 50); do cat /proc/{before['pid']}/oom_score_adj"
|
||||
" 2>/dev/null || echo DEAD; sleep 0.1; done").split()
|
||||
events = self.d.run("logcat", "-b", "events", "-d")
|
||||
(self.out / f"{self.label}-{state}-events.txt").write_text(events)
|
||||
@@ -297,7 +328,7 @@ class Bench:
|
||||
self.probe("using_bottom_now")
|
||||
self.game_front()
|
||||
|
||||
def pressure(self, run: str, stop_mb: int, hold: int):
|
||||
def pressure(self, run: str, stop_mb: int, hold: int, burst: bool = False) -> bool:
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".sh", delete=False) as script:
|
||||
script.write(HOG)
|
||||
try:
|
||||
@@ -305,16 +336,18 @@ class Bench:
|
||||
finally:
|
||||
os.unlink(script.name)
|
||||
self.d.sh(f"chmod 755 {HOG_PATH}")
|
||||
self.game_front()
|
||||
self.close_panel()
|
||||
self.game_front()
|
||||
self.tap(self.session_display, (0.36, 0.11))
|
||||
time.sleep(2)
|
||||
before = self.snapshot()
|
||||
self.d.run("logcat", "-b", "events", "-c")
|
||||
hog = subprocess.Popen([self.d.adb, "-s", self.d.serial, "shell", f"su -c '{HOG_PATH} {int(stop_mb)} {int(hold)}'"],
|
||||
hog = subprocess.Popen([self.d.adb, "-s", self.d.serial, "shell", f"su -c '{HOG_PATH} {int(stop_mb)} {int(hold)} {'burst' if burst else 'fill'}'"],
|
||||
stdout=subprocess.PIPE, text=True)
|
||||
samples = []
|
||||
try:
|
||||
while hog.poll() is None:
|
||||
samples.append(self.d.su(f"cat /proc/{before['pid']}/oom_score_adj 2>/dev/null || echo DEAD").strip())
|
||||
samples.append(self.d.sh(f"cat /proc/{before['pid']}/oom_score_adj 2>/dev/null || echo DEAD").strip())
|
||||
time.sleep(0.5)
|
||||
output = hog.stdout.read() if hog.stdout else ""
|
||||
finally:
|
||||
@@ -324,12 +357,19 @@ class Bench:
|
||||
time.sleep(3)
|
||||
events = self.d.run("logcat", "-b", "events", "-d")
|
||||
(self.out / f"{self.label}-{run}-events.txt").write_text(events)
|
||||
workload_ok = hog.returncode == 0 and "released" in output.splitlines()
|
||||
if not workload_ok:
|
||||
print(f"memory-guard-ab: {run}: the memory hog failed (exit {hog.returncode}): "
|
||||
f"{output.strip().splitlines()[-1] if output.strip() else 'no output'}", file=sys.stderr)
|
||||
available = [int(value) for value in re.findall(r"avail=(\d+)", output)]
|
||||
took = re.search(r"start=(\d+).*?burst_done=(\d+)", output, re.S)
|
||||
self.write("pressure", {
|
||||
"run": run, "stop_mb": stop_mb, "hold_s": hold, **{k: v for k, v in before.items() if k != "pid"},
|
||||
"run": run, "workload_ok": workload_ok, "mode": "burst" if burst else "fill", "stop_mb": stop_mb, "hold_s": hold,
|
||||
"burst_ms": (int(took.group(2)) - int(took.group(1))) // 1_000_000 if took else None, **{k: v for k, v in before.items() if k != "pid"},
|
||||
"min_available_mb": min(available) if available else None, "adj_max": max_adj(samples),
|
||||
"droiddeck_alive": self.d.pid() == before["pid"], "phase": self.d.phase(), **summarize_events(events),
|
||||
})
|
||||
return workload_ok
|
||||
|
||||
|
||||
def fraction_pair(text: str) -> tuple[float, float]:
|
||||
@@ -355,6 +395,8 @@ def main() -> int:
|
||||
pressure.add_argument("--stop-mb", type=int, default=650, help="stop filling at this MemAvailable")
|
||||
pressure.add_argument("--hold", type=int, default=30)
|
||||
pressure.add_argument("--runs", type=int, default=1)
|
||||
pressure.add_argument("--burst", action="store_true",
|
||||
help="take everything above --stop-mb at once instead of filling 32 MiB at a time")
|
||||
summarize = commands.add_parser("summarize", help="summarize a saved events log")
|
||||
summarize.add_argument("events", type=Path)
|
||||
args = parser.parse_args()
|
||||
@@ -376,9 +418,19 @@ def main() -> int:
|
||||
bench.prepare(args.apk)
|
||||
bench.states()
|
||||
else:
|
||||
completed = 0
|
||||
for run in range(args.runs):
|
||||
bench.prepare(args.apk if run == 0 else None)
|
||||
bench.pressure(f"stop{args.stop_mb}-{run + 1}", args.stop_mb, args.hold)
|
||||
try:
|
||||
bench.prepare(args.apk if run == 0 else None)
|
||||
except RuntimeError as exc:
|
||||
print(f"memory-guard-ab: run {run + 1} skipped: {exc}", file=sys.stderr)
|
||||
continue
|
||||
if bench.pressure(f"{'burst' if args.burst else 'stop'}{args.stop_mb}-{run + 1}", args.stop_mb,
|
||||
args.hold, args.burst):
|
||||
completed += 1
|
||||
if completed == 0:
|
||||
print("memory-guard-ab: no pressure run completed", file=sys.stderr)
|
||||
return 1
|
||||
except RuntimeError as exc:
|
||||
print(f"memory-guard-ab: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
+19
-1
@@ -11,6 +11,8 @@ linuxfs="$repo/app/src/main/assets/linuxfs/usr/local/lib"
|
||||
source "$here/tracking/release.env"
|
||||
# shellcheck source=butler/release.env
|
||||
source "$here/butler/release.env"
|
||||
# shellcheck source=zstd/release.env
|
||||
source "$here/zstd/release.env"
|
||||
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
@@ -21,6 +23,22 @@ fetch() {
|
||||
bash "$here/fetch-verified.sh" "$@"
|
||||
}
|
||||
|
||||
zstd_version() { "$1" -V 2>/dev/null | sed -n 's/.* v\([0-9][0-9.]*\),.*/\1/p'; }
|
||||
zstd=$(command -v zstd || true)
|
||||
if [ -z "$zstd" ] || [ "$(zstd_version "$zstd")" != "$ZSTD_VERSION" ]; then
|
||||
zstd="${DROIDDECK_PACK_CACHE:-"$HOME/.cache/droiddeck-pack-inputs"}/zstd-$ZSTD_VERSION/zstd"
|
||||
if [ ! -x "$zstd" ] || [ "$(zstd_version "$zstd")" != "$ZSTD_VERSION" ]; then
|
||||
fetch "https://github.com/facebook/zstd/releases/download/v$ZSTD_VERSION/zstd-$ZSTD_VERSION.tar.gz" \
|
||||
"$ZSTD_SHA256" "$work/zstd.tar.gz"
|
||||
tar -xzf "$work/zstd.tar.gz" -C "$work"
|
||||
make -s -C "$work/zstd-$ZSTD_VERSION" -j"$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 2)" zstd-release >/dev/null
|
||||
mkdir -p "$(dirname "$zstd")"
|
||||
install -m755 "$work/zstd-$ZSTD_VERSION/programs/zstd" "$zstd.part.$$"
|
||||
mv -f "$zstd.part.$$" "$zstd"
|
||||
fi
|
||||
fi
|
||||
[ "$(zstd_version "$zstd")" = "$ZSTD_VERSION" ] || { echo "packs need zstd $ZSTD_VERSION, $zstd is not it" >&2; exit 1; }
|
||||
|
||||
pack() {
|
||||
local name=$1 src=$2
|
||||
shift 2
|
||||
@@ -47,7 +65,7 @@ with tarfile.open(dest, "w", format=tarfile.USTAR_FORMAT) as tar:
|
||||
with open(path, "rb") as f:
|
||||
tar.addfile(info, f)
|
||||
EOF
|
||||
zstd -q -19 -f "$work/$name.tar" -o "$out/$name.tar.zst"
|
||||
"$zstd" -q -19 -f "$work/$name.tar" -o "$out/$name.tar.zst"
|
||||
echo "$name $(sha256 "$out/$name.tar.zst") $(wc -c < "$out/$name.tar.zst" | tr -d ' ')"
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
ZSTD_VERSION=1.5.5
|
||||
ZSTD_SHA256=9c4396cc829cfae319a6e2615202e82aad41372073482fce286fac78646d3ee4
|
||||
@@ -6,7 +6,7 @@ The handoff is mode 0600, expires after 90 seconds and is deleted before startin
|
||||
|
||||
GTA III, Vice City and San Andreas use body-length MTLX replies. GTA IV and L.A. Noire use total-length, terminated replies. Titles with installed Social Club metadata or SDK binaries use the SDK IPC adapter, including user-info, login, ticket, initialization and authorized title-state synchronization. The title metadata supplies the ROS identity and principal executable; it is checked against Rockstar's catalog before title authorization. Other titles retain Play and Steam shortcuts and attempt the normal executable launch path.
|
||||
|
||||
The SDK runtime is extracted from the game's own Social-Club-Setup.exe when present. Architecture-specific payloads are staged into the prefix, archive paths and sizes are checked, interrupted copies are retried, and both registry views are registered. The helper discovers launcher identity pipe names in the game executable and the executables beside it, because protected game executables resolve that name only at run time, and answers bounded INIT challenges from the launched process. No vendor executables or runtime files are bundled with this tool. SDK initialization has a 90-second deadline. SDK wire tests and fixture clients do not establish gameplay compatibility for every title; per-title ROS ticket exchange and secondary SDK channels remain unverified.
|
||||
The SDK runtime is extracted from the game's own Social-Club-Setup.exe when present. A title that ships neither the installer nor `socialclub.dll` gets the installer from the account's Rockstar Games Launcher build, downloaded by the app into the game's `Redistributables` folder with each chunk's hash checked. Architecture-specific payloads are staged into the prefix, archive paths and sizes are checked, interrupted copies are retried, and both registry views are registered. The helper discovers launcher identity pipe names in the game executable and the executables beside it, because protected game executables resolve that name only at run time, and answers bounded INIT challenges from the launched process. No vendor executables or runtime files are bundled with this tool. SDK initialization has a 90-second deadline. SDK wire tests and fixture clients do not establish gameplay compatibility for every title; per-title ROS ticket exchange and secondary SDK channels remain unverified.
|
||||
|
||||
GTA III defaults to full x87 precision for FEX before Wine starts, because reduced precision crashed new-game initialization on the test device. San Andreas defaults to WineD3D, because DXVK intermittently corrupted its textures; full precision and conservative memory ordering did not prevent that corruption. These defaults use DroidDeck's per-game settings and preserve explicit per-game overrides.
|
||||
|
||||
|
||||
@@ -19,7 +19,8 @@ class CdpGuardTest(unittest.TestCase):
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", str(SOURCE), str(SOURCE.parent / "binfmt.c"), str(SOURCE.parent / "webhelper.c"),
|
||||
str(Path(__file__).with_name("netlink_stubs.c")), "-x", "c", "-", "-ldl",
|
||||
"-o", str(cls.library)],
|
||||
input=b"int dd_udevmon_stand_in(int fd) { return 0; }", check=True, capture_output=True)
|
||||
input=b"int dd_udevmon_stand_in(int fd) { return 0; }\n"
|
||||
b"int dd_udevmon_bind(int fd, const void *addr, unsigned len, void *real, int *rc) { return 0; }", check=True, capture_output=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
|
||||
@@ -66,6 +66,15 @@ class DumpParsingTest(unittest.TestCase):
|
||||
def test_the_bottom_home_is_the_visible_home_on_another_display(self):
|
||||
self.assertEqual((2, "rip.moth.cocoonshell"), ab.bottom_home(ACTIVITIES, 0))
|
||||
|
||||
def test_android_13_activity_records_are_counted(self):
|
||||
self.assertEqual(1, ab.session_count(
|
||||
" * Hist #1: ActivityRecord{e1ec207 u0 com.droiddeck.launcher/.SessionActivity} t14519}\n"))
|
||||
|
||||
def test_the_visible_app_stands_in_when_no_home_is_on_the_other_display(self):
|
||||
dump = ("Display #4 (activities from top to bottom):\n"
|
||||
" * Task{21f60d6 #14493 type=standard A=10113:com.discord U=0 visible=true visibleRequested=true mode=fullscreen}\n")
|
||||
self.assertEqual((4, "com.discord"), ab.bottom_home(dump, 0))
|
||||
|
||||
def test_no_bottom_home_without_another_display(self):
|
||||
self.assertIsNone(ab.bottom_home(ACTIVITIES.split("\n\n")[1], 0))
|
||||
|
||||
@@ -80,6 +89,25 @@ class DumpParsingTest(unittest.TestCase):
|
||||
self.assertIsNone(ab.logical_size(DISPLAYS, 5))
|
||||
|
||||
|
||||
class HogScriptTest(unittest.TestCase):
|
||||
def test_both_modes_start_the_fill_counter(self):
|
||||
script = ab.HOG.splitlines()
|
||||
counter = next(n for n, line in enumerate(script) if line.startswith("i=0"))
|
||||
self.assertLess(counter, script.index('if [ "$mode" = burst ]; then'))
|
||||
self.assertLess(counter, next(n for n, line in enumerate(script) if line.startswith("while [ $i -lt 512 ]")))
|
||||
|
||||
|
||||
def test_a_failed_write_never_reports_released(self):
|
||||
script = ab.HOG.splitlines()
|
||||
check = script.index('[ "$failed" = 0 ] || { echo "write failed"; cleanup; exit 1; }')
|
||||
self.assertLess(check, script.index("echo released"))
|
||||
self.assertIn("failed=1", ab.HOG.split("echo released")[0])
|
||||
|
||||
def test_a_burst_takes_the_remainder_below_one_chunk(self):
|
||||
self.assertIn("rest=$((take % 256))", ab.HOG)
|
||||
self.assertIn('echo "nothing to take"', ab.HOG)
|
||||
|
||||
|
||||
class SummaryTest(unittest.TestCase):
|
||||
def test_max_adj_skips_samples_after_death(self):
|
||||
self.assertEqual(50, ab.max_adj(["0", "50", "DEAD", ""]))
|
||||
|
||||
@@ -234,6 +234,66 @@ class RockstarLaunch(unittest.TestCase):
|
||||
self.assertEqual('ready', result)
|
||||
self.assertEqual([False], stale)
|
||||
|
||||
def sdk_launch(self, root, runtimes, sdk_answer=None, ships_runtime=False, ident='gta5'):
|
||||
folder, sidecar, prefix, service, answer = self.setup_game(root)
|
||||
sidecar['id'] = ident
|
||||
(folder / 'title.rgl').write_bytes(b'RGLM' + bytes(108))
|
||||
if ships_runtime:
|
||||
(folder / 'socialclub.dll').write_bytes(b'game-runtime')
|
||||
answer['session'] = {'accountId': '123', 'identity': 'player@example.invalid', 'ticket': 'game-session'}
|
||||
requests, lines, states = [], [], list(runtimes)
|
||||
|
||||
def ask(channel, request, timeout):
|
||||
requests.append(request['op'])
|
||||
return sdk_answer if request['op'] == 'rockstar-sdk' else answer
|
||||
|
||||
with patch.object(store, 'ROCKSTAR_SERVICE', service), patch.object(store, 'rockstar_registry', return_value=True), \
|
||||
patch.object(store, 'rockstar_runtime', side_effect=lambda *args: states.pop(0)), \
|
||||
patch.object(store, 'log', lines.append):
|
||||
result = store.prepare_rockstar(folder, sidecar, str(prefix), str(Path(root) / 'channel'), ask_app=ask)
|
||||
return result, requests, lines, states
|
||||
|
||||
def test_a_title_without_a_social_club_installer_gets_one_from_the_app_before_its_session(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
result, requests, lines, states = self.sdk_launch(root, ['game-runtime', 'installed'], {'ok': True})
|
||||
self.assertEqual('ready', result)
|
||||
self.assertEqual(['rockstar-sdk', 'rockstar-launch'], requests)
|
||||
self.assertIn('rockstar runtime: installed', lines)
|
||||
self.assertEqual([], states)
|
||||
|
||||
def test_classic_sdk_titles_without_a_social_club_installer_also_get_one_from_the_app(self):
|
||||
for ident in ('gta4', 'lanoire'):
|
||||
with self.subTest(ident=ident), tempfile.TemporaryDirectory() as root:
|
||||
result, requests, lines, states = self.sdk_launch(root, ['game-runtime', 'installed'], {'ok': True}, ident=ident)
|
||||
self.assertEqual('ready', result)
|
||||
self.assertEqual(['rockstar-sdk', 'rockstar-launch'], requests)
|
||||
self.assertIn('rockstar runtime: installed', lines)
|
||||
self.assertEqual([], states)
|
||||
|
||||
def test_an_unavailable_social_club_installer_is_logged_and_the_launch_continues(self):
|
||||
for sdk_answer, reason in (({'ok': False, 'reason': 'no-launcher-build'}, 'sdk-no-launcher-build'), (None, 'sdk-timeout')):
|
||||
with self.subTest(reason=reason), tempfile.TemporaryDirectory() as root:
|
||||
result, requests, lines, _ = self.sdk_launch(root, ['game-runtime'], sdk_answer)
|
||||
self.assertEqual('ready', result)
|
||||
self.assertEqual(['rockstar-sdk', 'rockstar-launch'], requests)
|
||||
self.assertIn('rockstar runtime: ' + reason, lines)
|
||||
|
||||
def test_an_installed_or_bundled_social_club_does_not_ask_the_app(self):
|
||||
for runtimes, ships in ((['present'], False), (['installed'], False), (['game-runtime'], True)):
|
||||
with self.subTest(runtimes=runtimes, ships=ships), tempfile.TemporaryDirectory() as root:
|
||||
result, requests, lines, _ = self.sdk_launch(root, runtimes, ships_runtime=ships)
|
||||
self.assertEqual('ready', result)
|
||||
self.assertEqual(['rockstar-launch'], requests)
|
||||
self.assertIn('rockstar runtime: ' + runtimes[0], lines)
|
||||
|
||||
def test_classic_titles_without_the_sdk_never_ask_for_the_social_club_installer(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
with patch.object(store, 'rockstar_runtime') as runtime:
|
||||
result, _, requests = self.prepare(root)
|
||||
self.assertEqual('ready', result)
|
||||
self.assertEqual(['rockstar-launch'], [request['op'] for request in requests])
|
||||
runtime.assert_not_called()
|
||||
|
||||
def exit_game(self, root, store_id, log_text=None, link=None):
|
||||
folder = game(root, store_id=store_id, ident='gta5')
|
||||
prefix = Path(root) / 'prefix'
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/netlink.h>
|
||||
#include <poll.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
unsigned groups = argc > 1 ? (unsigned)atoi(argv[1]) : 2;
|
||||
int fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC | SOCK_NONBLOCK, NETLINK_KOBJECT_UEVENT);
|
||||
if (fd < 0) { printf("socket failed\n"); return 2; }
|
||||
struct sockaddr_nl nl = {.nl_family = AF_NETLINK, .nl_groups = groups};
|
||||
printf("bind %d\n", bind(fd, (struct sockaddr *)&nl, sizeof(nl)));
|
||||
printf("cloexec %d nonblock %d\n", (fcntl(fd, F_GETFD) & FD_CLOEXEC) != 0, (fcntl(fd, F_GETFL) & O_NONBLOCK) != 0);
|
||||
int (*inject)(const char *, const char *, const char *, const char *, unsigned, unsigned) =
|
||||
(int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned))dlsym(RTLD_DEFAULT, "dd_udevmon_inject");
|
||||
int sent = inject("add", "/devices/droiddeck/usb4/4-1:1.3/0003:054C:09CC.0005/hidraw/hidraw20", "hidraw",
|
||||
"/dev/hidraw20", 245, 20);
|
||||
printf("sent %d\n", sent);
|
||||
struct pollfd p = {.fd = fd, .events = POLLIN};
|
||||
if (sent > 0 && poll(&p, 1, 1000) == 1) {
|
||||
char buf[2048];
|
||||
struct sockaddr_nl from;
|
||||
struct iovec iov = {.iov_base = buf, .iov_len = sizeof(buf)};
|
||||
struct msghdr msg = {.msg_name = &from, .msg_namelen = sizeof(from), .msg_iov = &iov, .msg_iovlen = 1};
|
||||
ssize_t n = recvmsg(fd, &msg, 0);
|
||||
int found = 0;
|
||||
for (ssize_t i = 0; n > 0 && i < n; i += (ssize_t)strlen(buf + i) + 1)
|
||||
if (!strcmp(buf + i, "ACTION=add") || !strcmp(buf + i, "DEVNAME=/dev/hidraw20")) found++;
|
||||
printf("received %s fields %d\n", n > 0 && !memcmp(buf, "libudev", 8) ? "libudev" : "nothing", found);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("gcc") and os.uname().machine == "x86_64", "needs gcc on an x86-64 host")
|
||||
class UdevMonitorPreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = Path(tempfile.mkdtemp())
|
||||
cls.library = cls.tmp / "libudevmon.so"
|
||||
subprocess.run(["gcc", "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror", "-DUDEVMON_TEST", "-DBINFMT_TEST",
|
||||
'-DBINFMT_HANDLER="/bin/false"', "-o", str(cls.library), "-pthread"]
|
||||
+ [str(PRELOAD / name) for name in ("binfmt.c", "net.c", "udevmon.c", "pathcache.c", "perms.c", "webhelper.c")]
|
||||
+ [str(Path(__file__).with_name("netlink_stubs.c")), "-ldl"], check=True)
|
||||
source = cls.tmp / "program.c"
|
||||
source.write_text(PROGRAM.replace("#include <unistd.h>", "#include <unistd.h>\n#include <stdlib.h>"))
|
||||
cls.program = cls.tmp / "program"
|
||||
subprocess.run(["gcc", "-O2", "-o", str(cls.program), str(source), "-ldl"], check=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(cls.tmp, True)
|
||||
|
||||
def run_program(self, *args, refuse=False):
|
||||
env = dict(os.environ, LD_PRELOAD=str(self.library))
|
||||
env.pop("DD_UDEVMON_REFUSE", None)
|
||||
if refuse:
|
||||
env["DD_UDEVMON_REFUSE"] = "1"
|
||||
return subprocess.run([str(self.program), *args], env=env, capture_output=True, text=True, check=True).stdout.splitlines()
|
||||
|
||||
def test_a_monitor_the_system_will_not_subscribe_hears_the_sessions_events(self):
|
||||
out = self.run_program(refuse=True)
|
||||
self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 1", "received libudev fields 2"], out)
|
||||
|
||||
def test_a_monitor_the_system_subscribes_stays_on_the_real_socket(self):
|
||||
self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 0"], self.run_program())
|
||||
|
||||
def test_a_monitor_bound_without_groups_hears_the_sessions_events(self):
|
||||
out = self.run_program("0")
|
||||
self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 1", "received libudev fields 2"], out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user