mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
666943f628 | ||
|
|
d7d0583c5a | ||
|
|
7909af74d6 | ||
|
|
28cf995d7b | ||
|
|
b2b2e38e67 | ||
|
|
fa95df37d0 | ||
|
|
b88b5f6b1d | ||
|
|
c31f19a9f0 | ||
|
|
812e492302 | ||
|
|
f84e9d5191 | ||
|
|
2ff890f0ec | ||
|
|
913cb85c92 | ||
|
|
7852098e63 | ||
|
|
0794f361ad | ||
|
|
8c8cae85cf | ||
|
|
8e49dfe190 | ||
|
|
1951bbc92a | ||
|
|
d7c03ba3ec | ||
|
|
cdb8fa6f53 | ||
|
|
663a7003bc | ||
|
|
2be0ba58c7 | ||
|
|
637f4b21ee | ||
|
|
51ec4a3029 | ||
|
|
b1a7d9b2d0 |
No files matched your search
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
@@ -70,7 +70,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
|
||||
|
||||
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
|
||||
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
|
||||
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT). FEX's code disk cache was checked in its source.
|
||||
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source.
|
||||
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
|
||||
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
|
||||
- `WriteProcessMemory` hooks fall back to `/proc/<pid>/mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11.
|
||||
@@ -97,6 +97,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
|
||||
- Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`.
|
||||
- The EA store follows the EA app's protocols as documented by [ArmchairDevelopers](https://github.com/ArmchairDevelopers)' [Maxima](https://github.com/ArmchairDevelopers/Maxima) (GPL-3.0): sign-in, the GraphQL queries (included verbatim, since EA matches them by hash), build archives, online activation licences and the LSX game endpoint. The code is DroidDeck's own.
|
||||
- Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader.
|
||||
- The Rockstar launcher service looks for launcher pipe names in the executables beside the game, since [CitizenFX](https://github.com/citizenfx/fivem)'s `ros-patches-five` shows GTA V opening `GTAVLauncher_Pipe` and [@pingod](https://github.com/pingod)'s [rdr2-linux-launcher](https://github.com/pingod/rdr2-linux-launcher) notes that Rockstar's protected executables resolve such strings only at run time. Read without taking code.
|
||||
- World of Warcraft addon imports replace an addon's folder from a temporary copy, as [WowUp](https://github.com/WowUp/WowUp) does, and read flavour folders the way [WoWDeck](https://github.com/sigboe/wowdeck) does. No code from either is used.
|
||||
- The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. [CurseForge](https://www.curseforge.com/wow) opens in the user's browser, with no API and no key.
|
||||
- The Xbox store runs [@domsvoboda](https://github.com/domsvoboda)'s [nexus-backend](https://github.com/domsvoboda/nexus-backend) 0.2.15 (GPL-3.0, a fork of [Xodus](https://github.com/xodus-gaming/xodus)), and Xbox games load the Windows modules of his [nexus-runtime](https://github.com/domsvoboda/nexus-runtime) (LGPL-2.1-or-later), including the C++ [nexus-xgameruntime](https://github.com/domsvoboda/nexus-xgameruntime) and `wintypes.dll`. Content licensing sends delegation-compact device tickets in the licensing wire form, as nexus-backend's Store license path (commit `27c335e`) does. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT).
|
||||
|
||||
@@ -298,6 +298,15 @@
|
||||
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"
|
||||
|
||||
@@ -43,6 +43,7 @@ class App : Application() {
|
||||
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic" ||
|
||||
process == "$packageName:shortcuts_sync" || process == "$packageName:bottom_desktop") return
|
||||
CrashHandler.install(this)
|
||||
com.droiddeck.launcher.input.ShortcutsRelay.Holder.install(this)
|
||||
com.droiddeck.launcher.agent.AgentHost.refresh(this)
|
||||
com.droiddeck.launcher.agent.AgentTab.load(this)
|
||||
com.droiddeck.launcher.ui.NavTabs.load(this)
|
||||
|
||||
@@ -191,6 +191,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private var unfoldedPanel by mutableStateOf<OnScreenControls?>(null)
|
||||
private var unfoldedColumn: android.widget.LinearLayout? = null
|
||||
private var unfoldedDeckSurface: com.droiddeck.launcher.ui.InputSurfaceView? = null
|
||||
private var swappedInputSurface: com.droiddeck.launcher.ui.InputSurfaceView? = null
|
||||
private var unfoldedDeckPanel by mutableStateOf<com.droiddeck.launcher.input.DeckPanel?>(null)
|
||||
private var deckPanelLayouts: Map<com.droiddeck.launcher.input.DeckPanel, com.droiddeck.launcher.input.SavedInputLayout?> = emptyMap()
|
||||
private lateinit var sessionRoot: FrameLayout
|
||||
@@ -200,6 +201,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
@Volatile private var inputUsesLocalActions = false
|
||||
private var inputUsesPointer = false
|
||||
private var inputProfile = InputProfile.defaults(InputProfile.GAME)
|
||||
private var stockInputProfile = InputProfile.defaults(InputProfile.GAME)
|
||||
private val inputMotion = InputMotion { inputRouter }
|
||||
private val heldKeys = HeldInput { code, down -> WaylandCompositor.nativeSendKey(code, if (down) 1 else 0) }
|
||||
private val heldButtons = HeldInput(::sendSceneButton)
|
||||
@@ -539,6 +541,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private var lastMouseY = Float.NaN
|
||||
private var padType by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
|
||||
private var pcKeyboardOpen by mutableStateOf(false)
|
||||
private var fieldKeyboardOnPrimary = false
|
||||
private var pendingFieldKeyboard = false
|
||||
private var fieldKeyboardImeShown = false
|
||||
private var achievementsInFront by mutableStateOf<AchievementsInFront?>(null)
|
||||
private var achievementsOpen by mutableStateOf(false)
|
||||
private var hudOn by mutableStateOf(true)
|
||||
@@ -656,11 +661,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
override fun onDisplayAdded(displayId: Int) {
|
||||
notifyActivityDisplayStateChanged(displayId)
|
||||
refreshSecondScreenDisplays()
|
||||
updateBottomGame()
|
||||
}
|
||||
override fun onDisplayRemoved(displayId: Int) {
|
||||
if (refreshActivityDisplayId() && started) {
|
||||
SessionService.setActivityDisplay(this@SessionActivity, sessionActivityDisplayId)
|
||||
}
|
||||
updateBottomGame()
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
override fun onDisplayChanged(displayId: Int) {
|
||||
@@ -872,10 +879,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
root.addView(controls)
|
||||
}
|
||||
keyboard = KeyboardHost(this).also { host ->
|
||||
host.onImeChanged = { updateDesktopKeyboardButton() }
|
||||
host.onImeChanged = ::onPrimaryImeChanged
|
||||
root.addView(host)
|
||||
}
|
||||
desktopKeyboardButton = com.droiddeck.launcher.input.DesktopKeyboardButton(this) { keyboard?.show() }
|
||||
desktopKeyboardButton = com.droiddeck.launcher.input.DesktopKeyboardButton(this) { showPrimaryKeyboard() }
|
||||
.also { root.addView(it) }
|
||||
touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener)
|
||||
directTouchHold = DirectTouchHold(PointerGestures.slop(this), pointerListener, directTouchSink)
|
||||
@@ -893,6 +900,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
drawnRect()?.let { forwardTouch(event, it) }
|
||||
}
|
||||
override fun rightClick(x: Float, y: Float) {
|
||||
if (!screenTapsClick) return
|
||||
pointerListener.onLongPress()
|
||||
pointerListener.onButton(PointerGestures.BTN_RIGHT, true, x, y)
|
||||
surfaceView.postDelayed({ pointerListener.onButton(PointerGestures.BTN_RIGHT, false, x, y) }, 50L)
|
||||
@@ -1090,6 +1098,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (AgentGuest.keyboardDismissals != keyboardDismissalsSeen[0]) {
|
||||
keyboardDismissalsSeen[0] = AgentGuest.keyboardDismissals
|
||||
secondScreenPresentation?.closeFieldKeyboard()
|
||||
dismissFieldKeyboard()
|
||||
}
|
||||
}
|
||||
androidx.compose.runtime.LaunchedEffect(picturePosition, integerScaling, SessionState.running, pipUi, cardboard.enabled) { applyGameAlignment() }
|
||||
@@ -1312,7 +1321,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
if (pcKeyboardOpen) com.droiddeck.launcher.ui.PcKeyboard(
|
||||
sendKey = { code, down -> if (CompositorHost.isStarted) sendGuestKey(code, down, 32) },
|
||||
onAndroidKeyboard = { pcKeyboardOpen = false; keyboard?.toggle() },
|
||||
onAndroidKeyboard = { pcKeyboardOpen = false; togglePrimaryKeyboard() },
|
||||
onClose = { pcKeyboardOpen = false },
|
||||
)
|
||||
if (!drawerDocked) SessionMenu(
|
||||
@@ -1436,6 +1445,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
secondScreenNone = !bottomOutputActive && !dockDrawer(),
|
||||
gameOnBottom = bottomOutputActive,
|
||||
gameSwapAvailable = bottomSwapAvailable,
|
||||
gameSwapBuiltIn = !::displayManager.isInitialized || displayManager.getDisplay(selectedSecondScreenDisplay)
|
||||
?.let(com.droiddeck.launcher.input.DualScreen::builtIn) ?: true,
|
||||
onGameOnBottom = { on -> drawerOpen = false; putGameOnBottom(on) },
|
||||
dashboardAvailable = bottomPages().isNotEmpty(),
|
||||
desktopAvailable = com.droiddeck.launcher.session.BottomDesktop.available(),
|
||||
@@ -1629,7 +1640,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
pickLossless.launch(InAppFilePicker.buildIntent(
|
||||
this@SessionActivity, listOf("dll"), getString(R.string.lsfg_pick_title)))
|
||||
},
|
||||
onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; keyboard?.toggle() },
|
||||
onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; togglePrimaryKeyboard() },
|
||||
onHardwareKeyboard = ::togglePcKeyboard,
|
||||
wowChatShown = com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram),
|
||||
wowChat = wowChat.remembered,
|
||||
@@ -1860,7 +1871,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
val all = com.droiddeck.launcher.input.VrControllers.Emulate.entries
|
||||
com.droiddeck.launcher.input.VrControllers.setEmulate(this, all[(pads.emulate.ordinal + 1) % all.size])
|
||||
}) else null,
|
||||
onKeyboard = { keyboard?.toggle() },
|
||||
onKeyboard = { togglePrimaryKeyboard() },
|
||||
onSessionMenu = { drawerOpen = true },
|
||||
onStopSteamVr = if (vr) ({ steamVrAction("stop") }) else null,
|
||||
brightness = glasses.brightness,
|
||||
@@ -1901,12 +1912,44 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
private fun togglePcKeyboard() {
|
||||
drawerOpen = false
|
||||
keyboard?.hide()
|
||||
hidePrimaryKeyboard()
|
||||
onScreenControls?.releaseAll()
|
||||
bottomInputControls?.releaseAll()
|
||||
pcKeyboardOpen = !pcKeyboardOpen
|
||||
}
|
||||
|
||||
private fun showPrimaryKeyboard() {
|
||||
pendingFieldKeyboard = false
|
||||
fieldKeyboardOnPrimary = false
|
||||
keyboard?.show()
|
||||
}
|
||||
|
||||
private fun togglePrimaryKeyboard() {
|
||||
pendingFieldKeyboard = false
|
||||
fieldKeyboardOnPrimary = false
|
||||
keyboard?.toggle()
|
||||
}
|
||||
|
||||
private fun hidePrimaryKeyboard() {
|
||||
pendingFieldKeyboard = false
|
||||
fieldKeyboardOnPrimary = false
|
||||
keyboard?.hide()
|
||||
}
|
||||
|
||||
private fun onPrimaryImeChanged(visible: Boolean) {
|
||||
if (visible) fieldKeyboardImeShown = true
|
||||
else if (fieldKeyboardImeShown) {
|
||||
fieldKeyboardImeShown = false
|
||||
fieldKeyboardOnPrimary = false
|
||||
}
|
||||
updateDesktopKeyboardButton()
|
||||
}
|
||||
|
||||
private fun dismissFieldKeyboard() {
|
||||
pendingFieldKeyboard = false
|
||||
if (fieldKeyboardOnPrimary) hidePrimaryKeyboard()
|
||||
}
|
||||
|
||||
private fun updateControllerPrefs(change: () -> Unit) {
|
||||
change()
|
||||
controllerSettings = ControllerPrefs.read(this)
|
||||
@@ -3139,6 +3182,8 @@ 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() }
|
||||
@@ -3657,7 +3702,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
val target = com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId) ?: return false
|
||||
return try {
|
||||
val presentation = secondScreenPresentation ?: secondScreenPresentation(target).also {
|
||||
selectedSecondScreenDisplay = target.displayId
|
||||
secondScreenPresentation = it
|
||||
}
|
||||
if (!presentation.isShowing) presentation.show()
|
||||
@@ -4016,16 +4060,23 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
val candidates = SecondScreenDisplays.available(displayManager, primaryId)
|
||||
.filter { glassesScreen == null || it.id != glasses.displayId }
|
||||
val oldIds = secondScreenDisplays.map { it.id }.toSet()
|
||||
val oldSelectedDisplay = selectedSecondScreenDisplay
|
||||
secondScreenDisplays = candidates
|
||||
reconcileDock(primaryId)
|
||||
bottomSwapAvailable = bottomGame != null || bottomGameDisplay() != null
|
||||
val newIds = candidates.map { it.id }.toSet()
|
||||
if (secondScreenMode != SecondScreenMode.NONE && oldIds.isNotEmpty() && selectedSecondScreenDisplay !in newIds) {
|
||||
bottomSwapAvailable = bottomGame != null
|
||||
closeSecondScreen(reset = true)
|
||||
SessionState.secondScreenAutoOpened = false
|
||||
return
|
||||
}
|
||||
if (selectedSecondScreenDisplay !in newIds) selectedSecondScreenDisplay = candidates.firstOrNull()?.id ?: -1
|
||||
selectedSecondScreenDisplay = SecondScreenDisplays.selection(selectedSecondScreenDisplay, candidates.map { it.id }, gameOnBottom) {
|
||||
SessionState.secondScreenDisplay = it
|
||||
}
|
||||
if (selectedSecondScreenDisplay != oldSelectedDisplay) {
|
||||
updateBottomGame()
|
||||
}
|
||||
bottomSwapAvailable = bottomGame != null || bottomGameDisplay() != null
|
||||
if (secondScreenMode != SecondScreenMode.NONE && candidates.isEmpty()) {
|
||||
closeSecondScreen(reset = true)
|
||||
SessionState.secondScreenAutoOpened = false
|
||||
@@ -4047,12 +4098,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
private fun openDualScreenControls() {
|
||||
if (SessionState.secondScreenAutoOpened || secondScreenMode != SecondScreenMode.NONE || pipUi) return
|
||||
if (gameOnBottom && selectedSecondScreenDisplay >= 0 && secondScreenDisplays.none { it.id == selectedSecondScreenDisplay }) return
|
||||
if (!SessionPrefs.dualScreenSessionControls(this)) return
|
||||
val target = com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId) ?: return
|
||||
if (secondScreenDisplays.none { it.id == target.displayId }) return
|
||||
val gameDisplay = bottomGame?.display?.displayId
|
||||
?: if (SessionState.gameOnBottom) bottomGameDisplay()?.displayId else null
|
||||
SessionState.secondScreenAutoOpened = true
|
||||
selectedSecondScreenDisplay = target.displayId
|
||||
selectSecondScreenMode(openingPanel())
|
||||
if (gameDisplay != null && gameDisplay != target.displayId && secondScreenDisplays.any { it.id == gameDisplay }) {
|
||||
panelMode(openingPanel())
|
||||
} else {
|
||||
val selectionChanged = selectedSecondScreenDisplay != target.displayId
|
||||
selectedSecondScreenDisplay = target.displayId
|
||||
SessionState.secondScreenDisplay = target.displayId
|
||||
if (selectionChanged) updateBottomGame()
|
||||
selectSecondScreenMode(openingPanel())
|
||||
}
|
||||
automaticPanel = secondScreenMode != SecondScreenMode.NONE
|
||||
dualControlsProvisional = ::loading.isInitialized && loading.visible
|
||||
}
|
||||
@@ -4078,6 +4139,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (secondScreenDisplays.none { it.id == displayId }) return
|
||||
selectedSecondScreenDisplay = displayId
|
||||
SessionState.secondScreenDisplay = displayId
|
||||
updateBottomGame()
|
||||
if (secondScreenMode != SecondScreenMode.NONE) showSecondScreen(secondScreenMode)
|
||||
}
|
||||
|
||||
@@ -4096,6 +4158,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
return
|
||||
}
|
||||
if (selectedSecondScreenDisplay !in secondScreenDisplays.map { it.id }) {
|
||||
if (gameOnBottom && selectedSecondScreenDisplay >= 0) {
|
||||
panelMode(mode)
|
||||
return
|
||||
}
|
||||
selectedSecondScreenDisplay = secondScreenDisplays.first().id
|
||||
}
|
||||
showSecondScreen(mode)
|
||||
@@ -4174,7 +4240,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
)
|
||||
}
|
||||
},
|
||||
onSwap = if (bottomSwapAvailable && com.droiddeck.launcher.input.DualScreen.builtIn(target)) ({ putGameOnBottom(true) }) else null,
|
||||
onSwap = if (bottomSwapAvailable) ({ putGameOnBottom(true) }) else null,
|
||||
onDeckPanel = ::selectDeckPanel,
|
||||
dashboard = if (bottomPages().isEmpty()) null else ({
|
||||
DroidDeckTheme {
|
||||
@@ -4278,6 +4344,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
val library = com.droiddeck.launcher.input.InputLibraries.read(this)
|
||||
val desktop = loadingMode() == SessionService.MODE_DESKTOP
|
||||
inputProfile = library.compileActive(desktop, secondScreenMode.panel(this))
|
||||
stockInputProfile = library.compileStock(desktop, secondScreenMode.panel(this))
|
||||
primaryInputLayout = library.activeLayout(desktop, InputRole.PRIMARY)
|
||||
adaptiveSticks = primaryInputLayout?.adaptiveSticks
|
||||
quickButtons = primaryInputLayout?.takeIf { it.editable }?.let { l -> l.quickButtons.associateWith { it !in l.style.hidden } }.orEmpty()
|
||||
@@ -4417,6 +4484,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (!started) return null
|
||||
if (secondScreenPresentation?.showsKeyboard != true && dockDrawer()) {
|
||||
val target = com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId) ?: return null
|
||||
if (gameOnBottom && selectedSecondScreenDisplay != target.displayId) return null
|
||||
if (drawerOpen || drawerPinned) drawerOpen = false
|
||||
typingReturnMode = secondScreenMode
|
||||
selectedSecondScreenDisplay = target.displayId
|
||||
@@ -4426,16 +4494,37 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
private fun openBottomKeyboard() {
|
||||
val presentation = bottomKeyboardPresentation() ?: return
|
||||
val presentation = bottomKeyboardPresentation()
|
||||
if (presentation == null) {
|
||||
if (keyboardBelongsOnPrimary()) {
|
||||
pendingFieldKeyboard = true
|
||||
retryFieldKeyboard(hasWindowFocus())
|
||||
}
|
||||
return
|
||||
}
|
||||
pendingFieldKeyboard = false
|
||||
if (fieldKeyboardOnPrimary) hidePrimaryKeyboard()
|
||||
presentation.requestKeyboard(forField = true)
|
||||
com.droiddeck.launcher.ui.SessionTyping.focusDisplay(this, presentation.display.displayId)
|
||||
}
|
||||
|
||||
private fun keyboardBelongsOnPrimary() = SecondScreenDisplays.keyboardOnPrimary(gameOnBottom, selectedSecondScreenDisplay,
|
||||
secondScreenDisplays.map { it.id }, taken = com.droiddeck.launcher.input.DualScreen::taken)
|
||||
|
||||
private fun retryFieldKeyboard(hasFocus: Boolean) {
|
||||
if (!pendingFieldKeyboard || !hasFocus || !resumed || pipUi) return
|
||||
pendingFieldKeyboard = false
|
||||
if (!keyboardBelongsOnPrimary()) return
|
||||
fieldKeyboardOnPrimary = true
|
||||
fieldKeyboardImeShown = keyboard?.hideMeansDismissal == true
|
||||
keyboard?.show()
|
||||
}
|
||||
|
||||
private fun onGameTextField(focused: Boolean) {
|
||||
if (!focused || !com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram)) wowChat.chatClosed()
|
||||
else if (resumed && !pipUi && !pcKeyboardOpen &&
|
||||
resources.configuration.hardKeyboardHidden != android.content.res.Configuration.HARDKEYBOARDHIDDEN_NO) {
|
||||
keyboard?.takeIf { it.shown }?.hide()
|
||||
hidePrimaryKeyboard()
|
||||
wowChat.chatOpened()
|
||||
}
|
||||
}
|
||||
@@ -4522,9 +4611,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
private fun updateKeyboardRoute() {
|
||||
AgentGuest.routeKeyboard(this, SessionState.mode == SessionService.MODE_STEAM &&
|
||||
(secondScreenPresentation?.showsKeyboard == true || dockDrawer()) &&
|
||||
SessionPrefs.androidTextFieldKeyboard(this))
|
||||
AgentGuest.routeKeyboard(this, SecondScreenDisplays.routeKeyboard(
|
||||
SessionState.mode == SessionService.MODE_STEAM,
|
||||
SessionPrefs.androidTextFieldKeyboard(this),
|
||||
secondScreenPresentation?.showsKeyboard == true,
|
||||
dockDrawer(),
|
||||
SecondScreenDisplays.keyboardOnPrimary(gameOnBottom, selectedSecondScreenDisplay,
|
||||
secondScreenDisplays.map { it.id }, resumed && !pipUi, com.droiddeck.launcher.input.DualScreen::taken)))
|
||||
}
|
||||
|
||||
private fun dropDockedDrawer() {
|
||||
@@ -4735,6 +4828,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private var lockedSwipeY = 0f
|
||||
private var dismissTouch = false
|
||||
private var sessionTouchDown = false
|
||||
private var screenTapsClick = true
|
||||
|
||||
private fun onScreenMouseButtonShown(): Boolean = listOfNotNull(
|
||||
onScreenControls?.inputSurface, bottomInputControls?.inputSurface, unfoldedPanel?.inputSurface, unfoldedDeckSurface,
|
||||
secondScreenPresentation?.controlsView, swappedInputSurface,
|
||||
).any { it.isShown && inputProfile.showsMouseButton(it.inputRole, it.shownElements, stockInputProfile) }
|
||||
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
val pen = PenStream.penIndex(event)
|
||||
@@ -4767,6 +4866,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
val snapshot = fingerTouchSnapshot(uiBlocking)
|
||||
val route = com.droiddeck.launcher.input.TouchRouter.decide(snapshot)
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
|
||||
screenTapsClick = !onScreenMouseButtonShown()
|
||||
if (::touchpad.isInitialized) touchpad.clicks = screenTapsClick
|
||||
if (::scrollTouch.isInitialized) scrollTouch.clicks = screenTapsClick
|
||||
}
|
||||
if (route != touchRoute) {
|
||||
Log.i(TAG, "touch route $touchRoute -> $route (mode=$routedTouchMode steamUi=${SessionState.steamUi} scrollLayer=$scrollTouchGesture)")
|
||||
touchRoute = route
|
||||
@@ -4916,6 +5020,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) ignoreGameTouch = false
|
||||
return true
|
||||
}
|
||||
// With an on-screen mouse button the press comes from the button, so the pointer has to be there before
|
||||
// the two-finger gesture buffer holds the touch-down.
|
||||
if (SessionState.mode == SessionService.MODE_DESKTOP && !screenTapsClick && !pointerLocked &&
|
||||
event.actionMasked == MotionEvent.ACTION_DOWN) movePointer(event.x, event.y)
|
||||
if (SessionState.mode == SessionService.MODE_DESKTOP && twoFingerGestures.onTouch(event)) return true
|
||||
return forwardTouch(event, rect)
|
||||
}
|
||||
@@ -4950,7 +5058,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
}
|
||||
}
|
||||
directTouchHold.onTouch(event)
|
||||
if (screenTapsClick) directTouchHold.onTouch(event)
|
||||
else if (!pointerLocked && (event.actionMasked == MotionEvent.ACTION_DOWN || event.actionMasked == MotionEvent.ACTION_MOVE))
|
||||
movePointer(event.x, event.y)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -5406,6 +5516,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
private fun showPipUi(show: Boolean) {
|
||||
pipUi = show
|
||||
updateKeyboardRoute()
|
||||
if (!show) retryFieldKeyboard(hasWindowFocus())
|
||||
if (show) {
|
||||
if (::hud.isInitialized) hud.setHidden(true)
|
||||
drawerOpen = false
|
||||
@@ -5425,7 +5537,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
guestKeysDown.toList().forEach { sendGuestKey(it, false) }
|
||||
heldKeys.clear()
|
||||
heldButtons.clear()
|
||||
keyboard?.hide()
|
||||
hidePrimaryKeyboard()
|
||||
sessionClipboard.stop()
|
||||
padMotion?.stop()
|
||||
cursorVisible = false
|
||||
@@ -5466,7 +5578,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
|
||||
if (::pip.isInitialized && (requestCode >= 0 || intent.component?.packageName == packageName ||
|
||||
if (::pip.isInitialized && intent.component?.className != com.droiddeck.launcher.session.KeepTopActivity::class.java.name &&
|
||||
(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)
|
||||
@@ -5498,6 +5611,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
if (lightPause.stopped()) departureCleanup()
|
||||
if (runtimeRemovalBlocked) { super.onStop(); return }
|
||||
started = false
|
||||
if (::hud.isInitialized) hud.setBackgrounded(true)
|
||||
@@ -5541,6 +5655,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
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) }
|
||||
@@ -5568,6 +5688,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
onScreenControls?.reload()
|
||||
controllerSettings = ControllerPrefs.read(this)
|
||||
resumed = true
|
||||
updateKeyboardRoute()
|
||||
retryFieldKeyboard(hasWindowFocus())
|
||||
updateDesktopKeyboardButton()
|
||||
com.droiddeck.launcher.input.HomeButtonShortcuts.attach(this,
|
||||
enabled = {
|
||||
@@ -5604,10 +5726,63 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
if (isTopResumedActivity) 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) 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()
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
private fun departureCleanup() {
|
||||
com.droiddeck.launcher.input.SystemKeyCapture.detach(this)
|
||||
com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this)
|
||||
if (runtimeRemovalBlocked) { super.onPause(); return }
|
||||
if (runtimeRemovalBlocked) return
|
||||
physicalShortcuts.clear()
|
||||
backQamInput.cancel()
|
||||
mouseBackInput.cancel()
|
||||
@@ -5641,14 +5816,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (::scrollTouch.isInitialized) scrollTouch.cancel()
|
||||
if (::padMouse.isInitialized) padMouse.reset()
|
||||
resumed = false
|
||||
updateKeyboardRoute()
|
||||
updatePointerCapture()
|
||||
updatePadMotion()
|
||||
keyboard?.takeIf { it.shown }?.hide()
|
||||
val pendingKeyboard = pendingFieldKeyboard
|
||||
hidePrimaryKeyboard()
|
||||
pendingFieldKeyboard = pendingKeyboard
|
||||
SessionPrefs.sessionPrefs(this).unregisterOnSharedPreferenceChangeListener(cardboardPrefListener)
|
||||
SessionPrefs.sessionPrefs(this).unregisterOnSharedPreferenceChangeListener(screenEffectsProfilePrefListener)
|
||||
ControllerPrefs.prefs(this).unregisterOnSharedPreferenceChangeListener(shortcutPrefListener)
|
||||
updateHeadTracker()
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
private fun steamVrAction(action: String) {
|
||||
@@ -5889,9 +6066,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
private fun bottomGameDisplay(): Display? {
|
||||
if (!::displayManager.isInitialized) return null
|
||||
return com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId)
|
||||
?.takeIf { it.isValid && com.droiddeck.launcher.input.DualScreen.builtIn(it) }
|
||||
if (!::displayManager.isInitialized || SessionPrefs.dualScreenSessionMode(this) == com.droiddeck.launcher.input.DualScreen.MODE_OFF) return null
|
||||
return com.droiddeck.launcher.input.DualScreen.selectedSessionDisplay(
|
||||
this, displayManager, shownOnDisplayId, selectedSecondScreenDisplay,
|
||||
)
|
||||
}
|
||||
|
||||
private fun putGameOnBottom(on: Boolean) {
|
||||
@@ -6017,7 +6195,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
tabs = tabs,
|
||||
)
|
||||
val keyboardExtra = com.droiddeck.launcher.ui.BarExtra(getString(R.string.second_show_keyboard), icon = R.drawable.ic_bottom_keyboard) {
|
||||
keyboard?.toggle()
|
||||
togglePrimaryKeyboard()
|
||||
}
|
||||
val profileLayout = secondaryInputLayout
|
||||
androidx.compose.foundation.layout.Box(
|
||||
@@ -6045,8 +6223,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
androidx.compose.runtime.key(profileLayout) {
|
||||
androidx.compose.ui.viewinterop.AndroidView(
|
||||
factory = { context -> com.droiddeck.launcher.ui.InputSurfaceView(context, padBridge, profileLayout?.elements.orEmpty(),
|
||||
surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()) },
|
||||
surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()).also { swappedInputSurface = it } },
|
||||
modifier = Modifier.fillMaxWidth().weight(1f),
|
||||
onRelease = { if (swappedInputSurface === it) swappedInputSurface = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -6213,6 +6392,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
releaseHeldGuestInput()
|
||||
}
|
||||
if (hasFocus && !pipUi) {
|
||||
retryFieldKeyboard(true)
|
||||
goFullscreen()
|
||||
refreshClipboard()
|
||||
}
|
||||
@@ -6257,6 +6437,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
uiHandler.removeCallbacks(guardWhenRunning)
|
||||
com.droiddeck.launcher.session.KeepTopActivity.release()
|
||||
synchronized(frameGenGlobalLock) {
|
||||
frameGenActivityActive = false
|
||||
frameGenRequests.incrementAndGet()
|
||||
|
||||
@@ -37,7 +37,7 @@ object SteamIntegration {
|
||||
locationOn = WifiDiscovery.locationEnabled(context),
|
||||
brightness = Settings.System.canWrite(context),
|
||||
home = HomeApp.isDefault(context),
|
||||
shortcuts = shortcutsEnabled(context),
|
||||
shortcuts = shortcutsEnabled(context) && shortcutsCurrent(context),
|
||||
shortcutsRestricted = restrictedSettings(context),
|
||||
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
|
||||
)
|
||||
@@ -61,6 +61,10 @@ object SteamIntegration {
|
||||
return enabled.split(':').any { ComponentName.unflattenFromString(it.trim()) == shortcutsComponent }
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
fun shortcutsCurrent(context: Context): Boolean =
|
||||
runCatching { context.packageManager.getPackageInfo(Relay.PACKAGE, 0).versionCode }.getOrDefault(0) >= Relay.VERSION
|
||||
|
||||
fun shortcutsListed(context: Context): Boolean =
|
||||
context.getSystemService(android.view.accessibility.AccessibilityManager::class.java)
|
||||
?.installedAccessibilityServiceList.orEmpty()
|
||||
|
||||
@@ -82,6 +82,12 @@ object DualScreen {
|
||||
fun sessionDisplay(context: Context, displayManager: DisplayManager, primaryDisplayId: Int): Display? =
|
||||
display(context, displayManager, primaryDisplayId, SessionPrefs.dualScreenSessionMode(context))
|
||||
|
||||
fun selectedSessionDisplay(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, selectedDisplayId: Int): Display? =
|
||||
displayManager.getDisplay(selectedDisplayId)?.takeIf {
|
||||
SessionPrefs.dualScreenSessionMode(context) != MODE_OFF && it.isValid && it.displayId != primaryDisplayId &&
|
||||
(it.flags and Display.FLAG_PRESENTATION) != 0 && !taken(it.displayId)
|
||||
}
|
||||
|
||||
fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, mode: String = SessionPrefs.dualScreenMode(context)): Display? =
|
||||
when (mode) {
|
||||
MODE_OFF -> null
|
||||
|
||||
@@ -97,6 +97,16 @@ data class InputLibrary(
|
||||
fun compileActive(isDesktop: Boolean, panel: String? = null): InputProfile = compileParts(activeId(isDesktop), InputRole.entries.associateWith {
|
||||
preset(if (it == InputRole.SECONDARY) panelPart(isDesktop, panel).bindings else activePart(isDesktop, it).bindings)
|
||||
})
|
||||
fun compileStock(isDesktop: Boolean, panel: String? = null): InputProfile {
|
||||
val defaults = InputProfile.defaults(profile(activeId(isDesktop)).base)
|
||||
val stock = InputStockLayouts.presets(InputStockLayouts.layouts())
|
||||
return compileParts(defaults.id, InputRole.entries.associateWith { role ->
|
||||
val part = if (role == InputRole.SECONDARY) panelPart(isDesktop, panel) else activePart(isDesktop, role)
|
||||
val origin = layouts.firstOrNull { it.id == part.layout }?.origin ?: part.layout
|
||||
stock.firstOrNull { it.id == part.bindings || (origin != null && it.layoutId == origin) }
|
||||
?: SavedInputBindings(part.bindings, "", role == InputRole.PHYSICAL, part.layout, defaults.bindings[role].orEmpty())
|
||||
})
|
||||
}
|
||||
|
||||
fun saveSelection(isDesktop: Boolean, name: String, id: String = newInputId()): InputLibrary {
|
||||
val current = profile(activeId(isDesktop))
|
||||
|
||||
@@ -53,6 +53,16 @@ data class InputProfile(
|
||||
fun elementClickAction(role: InputRole, element: InputSurfaceElement): InputAction = clicks[role]?.get(element.id)
|
||||
?: defaultElementClick(element, elementAction(role, element.id, element.control)) { action(role, it) }
|
||||
|
||||
fun showsMouseButton(role: InputRole, shown: List<InputSurfaceElement>, stock: InputProfile): Boolean = shown.any { element ->
|
||||
val action = elementAction(role, element.id, element.control).takeIf {
|
||||
elements[role]?.get(element.id) != stock.elements[role]?.get(element.id) || it != stock.elementAction(role, element.id, element.control)
|
||||
}
|
||||
val click = elementClickAction(role, element).takeIf {
|
||||
clicks[role]?.get(element.id) != stock.clicks[role]?.get(element.id) || it != stock.elementClickAction(role, element)
|
||||
}
|
||||
listOfNotNull(action, click).any { it is InputAction.MouseButton && it.validFor(element.control) }
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val GAME = "game"
|
||||
const val DESKTOP = "desktop"
|
||||
|
||||
@@ -26,6 +26,8 @@ class KeyboardHost(
|
||||
var imeShowing = false
|
||||
private set
|
||||
var onImeChanged: ((Boolean) -> Unit)? = null
|
||||
val hideMeansDismissal: Boolean
|
||||
get() = Build.VERSION.SDK_INT < Build.VERSION_CODES.R || (shown && imeShowing)
|
||||
|
||||
init {
|
||||
isFocusable = false
|
||||
|
||||
@@ -176,7 +176,7 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
|
||||
}
|
||||
|
||||
|
||||
fun elements(): List<InputSurfaceElement> {
|
||||
fun elements(previousStickGeometry: Boolean = false): List<InputSurfaceElement> {
|
||||
fit = fitScale()
|
||||
controls.forEach { it.radius = scaled(it.radiusDp) }
|
||||
placeAuto(width.toFloat(), height.toFloat())
|
||||
@@ -189,7 +189,7 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
|
||||
}.map { c ->
|
||||
InputSurfaceElement(requireNotNull(InputControl.fromId(c.id)), (c.cx - c.halfW) / width, (c.cy - c.halfH) / height,
|
||||
2 * c.halfW / width, 2 * c.halfH / height, floating = settings.adaptiveSticks, hideWhenIdle = c.stick >= 0 && settings.adaptiveSticks,
|
||||
buttonShape = if (c.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE).let(::widenStick).bounded()
|
||||
buttonShape = if (c.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE).let { if (previousStickGeometry) widenStickPreviously(it) else widenStick(it) }.bounded()
|
||||
}.toMutableList()
|
||||
if (settings.keyboardButton) result += keyboard()
|
||||
return result
|
||||
@@ -315,7 +315,7 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
|
||||
return e.copy(x = (cx - radius) / width, y = (cy - radius) / height, width = 2 * radius / width, height = 2 * radius / height)
|
||||
}
|
||||
|
||||
private fun widenStick(e: InputSurfaceElement): InputSurfaceElement {
|
||||
private fun widenStickPreviously(e: InputSurfaceElement): InputSurfaceElement {
|
||||
val extra = e.width * (STICK_REACH - 1f)
|
||||
return when (e.control) {
|
||||
InputControl.LS -> (e.x - extra).coerceAtLeast(0f).let { x -> e.copy(x = x, width = e.x + e.width - x) }
|
||||
@@ -323,6 +323,16 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
|
||||
else -> e
|
||||
}
|
||||
}
|
||||
|
||||
private fun widenStick(e: InputSurfaceElement): InputSurfaceElement {
|
||||
val extra = e.width * (STICK_REACH - 1f)
|
||||
val width = e.width + extra
|
||||
return when (e.control) {
|
||||
InputControl.LS -> e.copy(x = (e.x - extra).coerceIn(0f, (1f - width).coerceAtLeast(0f)), width = width)
|
||||
InputControl.RS -> e.copy(x = e.x.coerceIn(0f, (1f - width).coerceAtLeast(0f)), width = width)
|
||||
else -> e
|
||||
}
|
||||
}
|
||||
private companion object {
|
||||
const val MIN_FACE_MM = 9.5f
|
||||
const val FULL_SIZE_HEIGHT_MM = 85f
|
||||
|
||||
@@ -32,6 +32,7 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
|
||||
var isPinnedOnly = false
|
||||
private set
|
||||
val hasPinned get() = layout?.elements?.any { it.alwaysShown } == true
|
||||
val inputSurface: com.droiddeck.launcher.ui.InputSurfaceView get() = surface
|
||||
var onTouchMiss: ((MotionEvent) -> Unit)?
|
||||
get() = surface.onTouchMiss
|
||||
set(value) { surface.onTouchMiss = value }
|
||||
|
||||
@@ -5,6 +5,7 @@ import android.graphics.Rect
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
object OnScreenLayout {
|
||||
data class Dock(val portrait: Boolean, val grips: Boolean, val left: InputControl = InputControl.LS, val right: InputControl = InputControl.RS) {
|
||||
@@ -41,6 +42,14 @@ object OnScreenLayout {
|
||||
return stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } }
|
||||
}
|
||||
|
||||
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List<InputSurfaceElement> =
|
||||
elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, Rect())
|
||||
|
||||
fun editorFrame(layout: SavedInputLayout, displayed: List<InputSurfaceElement>): List<InputSurfaceElement> {
|
||||
val byId = displayed.associateBy { it.id }
|
||||
return layout.elements.map { byId[it.id] ?: it }
|
||||
}
|
||||
|
||||
fun fit(elements: List<InputSurfaceElement>, referenceWidth: Float, referenceHeight: Float, width: Int, height: Int, safe: Rect): List<InputSurfaceElement> {
|
||||
val w = width.toFloat()
|
||||
val h = height.toFloat()
|
||||
@@ -77,8 +86,11 @@ object OnScreenLayout {
|
||||
if (gamepad.any { it.id.startsWith("legacy:") }) {
|
||||
val named = layout.id.removePrefix("migrated.layout.").takeIf { it != layout.id }?.split('x')?.mapNotNull { it.toIntOrNull() }
|
||||
?.takeIf { it.size == 2 && it.all { size -> size > 0 } }?.let { it[0] to it[1] }
|
||||
for ((w, h) in listOfNotNull(named, width to height, long to short, short to long).distinct()) {
|
||||
if (matches(gamepad, LegacyGamepadLayout(display, w, h, scale = layout.scale).elements())) return (w.toFloat() to h.toFloat()) to true
|
||||
val aspectSize = layout.aspect.takeIf { layout.id == InputLibraries.OVERLAY && it > 0f }
|
||||
?.let { (it * height).roundToInt().coerceAtLeast(1) to height }
|
||||
for ((w, h) in listOfNotNull(named, width to height, aspectSize, long to short, short to long).distinct()) {
|
||||
val generator = LegacyGamepadLayout(display, w, h, scale = layout.scale)
|
||||
if (matches(gamepad, generator.elements()) || matches(gamepad, generator.elements(previousStickGeometry = true))) return (w.toFloat() to h.toFloat()) to true
|
||||
}
|
||||
}
|
||||
val aspect = layout.aspect.takeIf { it > 0f } ?: (long.toFloat() / short)
|
||||
|
||||
@@ -12,6 +12,8 @@ import com.droiddeck.launcher.session.SessionState;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicIntegerArray;
|
||||
|
||||
public final class PadBridge {
|
||||
@@ -56,6 +58,7 @@ public final class PadBridge {
|
||||
private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS];
|
||||
private final PadState[] playerStates = new PadState[SLOTS];
|
||||
private final float[][] rawSticks = new float[SLOTS][4];
|
||||
private final Map<Integer, Boolean> rightStickLayouts = new HashMap<>();
|
||||
private final boolean[][] keyTriggers = new boolean[SLOTS][2];
|
||||
private final int[] retainedSticks = new int[SLOTS];
|
||||
private final PadState effectiveState = new PadState();
|
||||
@@ -240,6 +243,7 @@ public final class PadBridge {
|
||||
clearBackQamWrites();
|
||||
releaseBackPaddles();
|
||||
activeControllerId = NO_CONTROLLER;
|
||||
rightStickLayouts.clear();
|
||||
for (int slot = 0; slot < SLOTS; slot++) {
|
||||
owners[slot] = NO_CONTROLLER;
|
||||
partners[slot] = NO_CONTROLLER;
|
||||
@@ -525,20 +529,23 @@ public final class PadBridge {
|
||||
float lx = event.getAxisValue(MotionEvent.AXIS_X);
|
||||
float ly = event.getAxisValue(MotionEvent.AXIS_Y);
|
||||
boolean wired = wiredXboxLayout(device, event.getSource());
|
||||
float rx = event.getAxisValue(wired ? MotionEvent.AXIS_RX : MotionEvent.AXIS_Z);
|
||||
float ry = event.getAxisValue(wired ? MotionEvent.AXIS_RY : MotionEvent.AXIS_RZ);
|
||||
boolean rxRyStick = rightStickUsesRxRy(event, device, rightStickLayouts);
|
||||
float rx = event.getAxisValue(rxRyStick ? MotionEvent.AXIS_RX : MotionEvent.AXIS_Z);
|
||||
float ry = event.getAxisValue(rxRyStick ? MotionEvent.AXIS_RY : MotionEvent.AXIS_RZ);
|
||||
retainStick(slot, JoyCon.LEFT, lx, ly);
|
||||
retainStick(slot, JoyCon.RIGHT, rx, ry);
|
||||
projectSticks(slot);
|
||||
int source = event.getSource();
|
||||
float lt = 0f;
|
||||
float rt = 0f;
|
||||
if (wired || hasAxis(device, source, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE)) {
|
||||
lt = axisTrigger(leftTrigger(event, wired), keyTriggers[slot], 0);
|
||||
boolean signedLeft = signedZTriggers(event, device, wired, rxRyStick, true);
|
||||
boolean signedRight = signedZTriggers(event, device, wired, rxRyStick, false);
|
||||
if (signedLeft || hasAxis(device, source, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE)) {
|
||||
lt = axisTrigger(triggerValue(event, device, wired, rxRyStick, true), keyTriggers[slot], 0);
|
||||
pad.leftTrigger = lt;
|
||||
}
|
||||
if (wired || hasAxis(device, source, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS)) {
|
||||
rt = axisTrigger(rightTrigger(event, wired), keyTriggers[slot], 1);
|
||||
if (signedRight || hasAxis(device, source, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS)) {
|
||||
rt = axisTrigger(triggerValue(event, device, wired, rxRyStick, false), keyTriggers[slot], 1);
|
||||
pad.rightTrigger = rt;
|
||||
}
|
||||
if (hasAxis(device, source, MotionEvent.AXIS_HAT_X)) {
|
||||
@@ -596,6 +603,92 @@ public final class PadBridge {
|
||||
return false;
|
||||
}
|
||||
|
||||
static boolean rightStickUsesRxRy(MotionEvent event, InputDevice device, Map<Integer, Boolean> layouts) {
|
||||
int source = event.getSource();
|
||||
if (wiredXboxLayout(device, source)) return true;
|
||||
boolean hasRxRy = hasAxis(device, source, MotionEvent.AXIS_RX)
|
||||
&& hasAxis(device, source, MotionEvent.AXIS_RY);
|
||||
boolean hasZRz = hasAxis(device, source, MotionEvent.AXIS_Z)
|
||||
&& hasAxis(device, source, MotionEvent.AXIS_RZ);
|
||||
if (!hasRxRy) return false;
|
||||
if (!hasZRz) return true;
|
||||
Boolean cached = layouts.get(event.getDeviceId());
|
||||
if (cached != null) return cached;
|
||||
boolean rxRyEvidence = atMinimum(device, source, event, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ)
|
||||
&& nearCentre(device, source, event, MotionEvent.AXIS_RX, MotionEvent.AXIS_RY);
|
||||
boolean zRzEvidence = atMinimum(device, source, event, MotionEvent.AXIS_RX, MotionEvent.AXIS_RY)
|
||||
&& nearCentre(device, source, event, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ);
|
||||
if (rxRyEvidence == zRzEvidence) return false;
|
||||
boolean useRxRy = rxRyEvidence;
|
||||
layouts.put(event.getDeviceId(), useRxRy);
|
||||
return useRxRy;
|
||||
}
|
||||
|
||||
static boolean signedZTriggers(MotionEvent event, InputDevice device, boolean wired, boolean rxRyStick, boolean left) {
|
||||
if (wired) return true;
|
||||
if (!rxRyStick) return false;
|
||||
int source = event.getSource();
|
||||
int signedAxis = left ? MotionEvent.AXIS_Z : MotionEvent.AXIS_RZ;
|
||||
int dedicatedAxis = left ? MotionEvent.AXIS_LTRIGGER : MotionEvent.AXIS_RTRIGGER;
|
||||
int alternateAxis = left ? MotionEvent.AXIS_BRAKE : MotionEvent.AXIS_GAS;
|
||||
return hasAxis(device, source, signedAxis)
|
||||
&& !hasAxis(device, source, dedicatedAxis, alternateAxis);
|
||||
}
|
||||
|
||||
static float triggerValue(MotionEvent event, InputDevice device, boolean wired, boolean rxRyStick, boolean left) {
|
||||
if (signedZTriggers(event, device, wired, rxRyStick, left)) {
|
||||
int axis = left ? MotionEvent.AXIS_Z : MotionEvent.AXIS_RZ;
|
||||
float value = event.getAxisValue(axis);
|
||||
if (!wired && device != null) {
|
||||
InputDevice.MotionRange range = device.getMotionRange(axis, event.getSource());
|
||||
if (range != null && range.getMax() > range.getMin()) {
|
||||
return Math.max(0f, Math.min(1f,
|
||||
(value - range.getMin()) / (range.getMax() - range.getMin())));
|
||||
}
|
||||
}
|
||||
return Math.max(0f, Math.min(1f, (value + 1f) / 2f));
|
||||
}
|
||||
int source = event.getSource();
|
||||
int axis = left ? MotionEvent.AXIS_LTRIGGER : MotionEvent.AXIS_RTRIGGER;
|
||||
int alternate = left ? MotionEvent.AXIS_BRAKE : MotionEvent.AXIS_GAS;
|
||||
if (device == null) {
|
||||
float value = event.getAxisValue(axis);
|
||||
return value != 0f ? value : event.getAxisValue(alternate);
|
||||
}
|
||||
if (hasAxis(device, source, axis)) {
|
||||
float value = event.getAxisValue(axis);
|
||||
return value != 0f ? value : event.getAxisValue(alternate);
|
||||
}
|
||||
if (hasAxis(device, source, alternate)) return event.getAxisValue(alternate);
|
||||
return 0f;
|
||||
}
|
||||
|
||||
private static float restDistance(InputDevice device, int source, MotionEvent event, int xAxis, int yAxis) {
|
||||
return (restDistance(device.getMotionRange(xAxis, source), event.getAxisValue(xAxis))
|
||||
+ restDistance(device.getMotionRange(yAxis, source), event.getAxisValue(yAxis))) / 2f;
|
||||
}
|
||||
|
||||
private static float restDistance(InputDevice.MotionRange range, float value) {
|
||||
float span = range.getMax() - range.getMin();
|
||||
if (span <= 0f) return 1f;
|
||||
return Math.abs(value - (range.getMin() + range.getMax()) / 2f) / span;
|
||||
}
|
||||
|
||||
private static boolean atMinimum(InputDevice device, int source, MotionEvent event, int xAxis, int yAxis) {
|
||||
return atMinimum(device.getMotionRange(xAxis, source), event.getAxisValue(xAxis))
|
||||
&& atMinimum(device.getMotionRange(yAxis, source), event.getAxisValue(yAxis));
|
||||
}
|
||||
|
||||
private static boolean atMinimum(InputDevice.MotionRange range, float value) {
|
||||
float span = range.getMax() - range.getMin();
|
||||
return value - range.getMin() <= span * 0.02f;
|
||||
}
|
||||
|
||||
private static boolean nearCentre(InputDevice device, int source, MotionEvent event, int xAxis, int yAxis) {
|
||||
return restDistance(device.getMotionRange(xAxis, source), event.getAxisValue(xAxis)) <= 0.1f
|
||||
&& restDistance(device.getMotionRange(yAxis, source), event.getAxisValue(yAxis)) <= 0.1f;
|
||||
}
|
||||
|
||||
public interface TouchRoute {
|
||||
boolean active();
|
||||
|
||||
@@ -1182,16 +1275,4 @@ public final class PadBridge {
|
||||
&& device.getMotionRange(MotionEvent.AXIS_RZ, source) != null;
|
||||
}
|
||||
|
||||
public static float leftTrigger(MotionEvent event, boolean wired) {
|
||||
if (wired) return Math.max(0f, Math.min(1f, (event.getAxisValue(MotionEvent.AXIS_Z) + 1f) / 2f));
|
||||
float value = event.getAxisValue(MotionEvent.AXIS_LTRIGGER);
|
||||
return value != 0f ? value : event.getAxisValue(MotionEvent.AXIS_BRAKE);
|
||||
}
|
||||
|
||||
public static float rightTrigger(MotionEvent event, boolean wired) {
|
||||
if (wired) return Math.max(0f, Math.min(1f, (event.getAxisValue(MotionEvent.AXIS_RZ) + 1f) / 2f));
|
||||
float value = event.getAxisValue(MotionEvent.AXIS_RTRIGGER);
|
||||
return value != 0f ? value : event.getAxisValue(MotionEvent.AXIS_GAS);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -42,6 +42,7 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S
|
||||
private val total = Sticks()
|
||||
private val triggerAxes = HashMap<Int, Boolean>()
|
||||
private val wiredLayout = HashMap<Int, Boolean>()
|
||||
private val rightStickLayouts = HashMap<Int, Boolean>()
|
||||
private val down = HashMap<Int, MutableSet<Int>>()
|
||||
private val sent = HashMap<Int, IntArray>()
|
||||
private val held = LinkedHashMap<Int, Int>()
|
||||
@@ -87,14 +88,21 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S
|
||||
fun onMotion(event: MotionEvent): Boolean {
|
||||
if (event.actionMasked != MotionEvent.ACTION_MOVE) return true
|
||||
val sticks = physical.getOrPut(event.deviceId) { Sticks() }
|
||||
val wired = wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(event) }
|
||||
val device = event.device
|
||||
val wired = wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(device, event.source) }
|
||||
val rxRyStick = PadBridge.rightStickUsesRxRy(event, device, rightStickLayouts)
|
||||
sticks.leftX = event.getAxisValue(MotionEvent.AXIS_X)
|
||||
sticks.leftY = event.getAxisValue(MotionEvent.AXIS_Y)
|
||||
sticks.rightX = scrollAxis(event, if (wired) MotionEvent.AXIS_RX else MotionEvent.AXIS_Z)
|
||||
sticks.rightY = scrollAxis(event, if (wired) MotionEvent.AXIS_RY else MotionEvent.AXIS_RZ)
|
||||
if (hasTriggerAxes(event)) {
|
||||
sticks.leftTrigger = PadBridge.leftTrigger(event, wired)
|
||||
sticks.rightTrigger = PadBridge.rightTrigger(event, wired)
|
||||
sticks.rightX = scrollAxis(event, if (rxRyStick) MotionEvent.AXIS_RX else MotionEvent.AXIS_Z)
|
||||
sticks.rightY = scrollAxis(event, if (rxRyStick) MotionEvent.AXIS_RY else MotionEvent.AXIS_RZ)
|
||||
val signedLeft = PadBridge.signedZTriggers(event, device, wired, rxRyStick, true)
|
||||
val signedRight = PadBridge.signedZTriggers(event, device, wired, rxRyStick, false)
|
||||
val analogTriggers = hasTriggerAxes(event)
|
||||
if (analogTriggers || signedLeft) {
|
||||
sticks.leftTrigger = PadBridge.triggerValue(event, device, wired, rxRyStick, true)
|
||||
}
|
||||
if (analogTriggers || signedRight) {
|
||||
sticks.rightTrigger = PadBridge.triggerValue(event, device, wired, rxRyStick, false)
|
||||
}
|
||||
val hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X)
|
||||
val hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y)
|
||||
@@ -129,6 +137,7 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S
|
||||
physical.clear()
|
||||
triggerAxes.clear()
|
||||
wiredLayout.clear()
|
||||
rightStickLayouts.clear()
|
||||
touch.clear()
|
||||
down.clear()
|
||||
sent.clear()
|
||||
@@ -207,6 +216,7 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S
|
||||
private fun hasTriggerAxes(event: android.view.InputEvent): Boolean = triggerAxes.getOrPut(event.deviceId) {
|
||||
val device = event.device ?: return@getOrPut true
|
||||
device.getMotionRange(MotionEvent.AXIS_LTRIGGER) != null || device.getMotionRange(MotionEvent.AXIS_BRAKE) != null ||
|
||||
device.getMotionRange(MotionEvent.AXIS_RTRIGGER) != null || device.getMotionRange(MotionEvent.AXIS_GAS) != null ||
|
||||
(event is MotionEvent && wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(event) })
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,7 @@ class ScrollTouchGestures(
|
||||
private var flingY = 0f
|
||||
private var flingAt = 0L
|
||||
private var flinging = false
|
||||
var clicks = true
|
||||
|
||||
private val longPress = Runnable {
|
||||
held = true
|
||||
@@ -86,7 +87,7 @@ class ScrollTouchGestures(
|
||||
lastY = startY
|
||||
tracker = VelocityTracker.obtain().also { it.addMovement(event) }
|
||||
listener.onMove(startX, startY)
|
||||
handler.postDelayed(longPress, TouchTiming.HOLD_MS)
|
||||
if (clicks) handler.postDelayed(longPress, TouchTiming.HOLD_MS)
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
val index = event.findPointerIndex(pointerId).takeIf { it >= 0 } ?: return true
|
||||
@@ -153,6 +154,7 @@ class ScrollTouchGestures(
|
||||
|
||||
private fun click(button: Int) {
|
||||
releaseClick()
|
||||
if (!clicks) return
|
||||
listener.onButton(button, true)
|
||||
clicked = button
|
||||
handler.postDelayed(clickUp, TouchTiming.CLICK_MS)
|
||||
|
||||
@@ -40,6 +40,18 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindi
|
||||
data class SecondScreenDisplay(val id: Int, val label: String)
|
||||
|
||||
object SecondScreenDisplays {
|
||||
fun selection(selected: Int, available: List<Int>, gameRequested: Boolean): Int =
|
||||
if (selected in available || gameRequested && selected >= 0) selected else available.firstOrNull() ?: -1
|
||||
|
||||
fun selection(selected: Int, available: List<Int>, gameRequested: Boolean, save: (Int) -> Unit): Int =
|
||||
selection(selected, available, gameRequested).also { if (it != selected) save(it) }
|
||||
|
||||
fun keyboardOnPrimary(gameRequested: Boolean, selected: Int, available: List<Int>, visible: Boolean = true, taken: (Int) -> Boolean): Boolean =
|
||||
visible && gameRequested && selected >= 0 && (selected !in available || taken(selected))
|
||||
|
||||
fun routeKeyboard(steam: Boolean, enabled: Boolean, panel: Boolean, dock: Boolean, primaryFallback: Boolean): Boolean =
|
||||
steam && enabled && (panel || dock || primaryFallback)
|
||||
|
||||
fun available(displayManager: DisplayManager, primaryDisplayId: Int = Display.DEFAULT_DISPLAY): List<SecondScreenDisplay> =
|
||||
displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION)
|
||||
.asSequence()
|
||||
|
||||
@@ -178,4 +178,56 @@ class ShortcutsRelay : Service(), InputManager.InputDeviceListener {
|
||||
private companion object {
|
||||
const val KEY_TIMEOUT_MS = 200L
|
||||
}
|
||||
|
||||
// Frontends such as Cocoon treat a running player process as an open game, so the relay runs only while a screen is started.
|
||||
object Holder : android.app.Application.ActivityLifecycleCallbacks, android.content.ServiceConnection {
|
||||
private const val RELEASE_MS = 1_000L
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var app: android.app.Application? = null
|
||||
private var started = 0
|
||||
private var bound = false
|
||||
private val release = Runnable { unbind() }
|
||||
|
||||
fun install(application: android.app.Application) {
|
||||
app?.unregisterActivityLifecycleCallbacks(this)
|
||||
handler.removeCallbacks(release)
|
||||
started = 0
|
||||
bound = false
|
||||
app = application
|
||||
application.registerActivityLifecycleCallbacks(this)
|
||||
}
|
||||
|
||||
override fun onActivityStarted(activity: android.app.Activity) {
|
||||
started++
|
||||
handler.removeCallbacks(release)
|
||||
if (!bound) bind()
|
||||
}
|
||||
|
||||
override fun onActivityStopped(activity: android.app.Activity) {
|
||||
started = (started - 1).coerceAtLeast(0)
|
||||
if (started == 0) handler.postDelayed(release, RELEASE_MS)
|
||||
}
|
||||
|
||||
private fun bind() {
|
||||
val context = app ?: return
|
||||
if (runCatching { context.packageManager.getPackageInfo(Relay.PACKAGE, 0) }.isFailure) return
|
||||
bound = runCatching {
|
||||
context.bindService(Intent(context, ShortcutsRelay::class.java), this, Context.BIND_AUTO_CREATE)
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
|
||||
private fun unbind() {
|
||||
if (!bound) return
|
||||
bound = false
|
||||
runCatching { app?.unbindService(this) }
|
||||
}
|
||||
|
||||
override fun onServiceConnected(name: android.content.ComponentName?, service: IBinder?) = Unit
|
||||
override fun onServiceDisconnected(name: android.content.ComponentName?) = Unit
|
||||
override fun onActivityCreated(activity: android.app.Activity, savedInstanceState: android.os.Bundle?) = Unit
|
||||
override fun onActivityResumed(activity: android.app.Activity) = Unit
|
||||
override fun onActivityPaused(activity: android.app.Activity) = Unit
|
||||
override fun onActivitySaveInstanceState(activity: android.app.Activity, outState: android.os.Bundle) = Unit
|
||||
override fun onActivityDestroyed(activity: android.app.Activity) = Unit
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,11 @@ class TouchpadGestures(
|
||||
var bounds: android.graphics.RectF = android.graphics.RectF(0f, 0f, 1f, 1f)
|
||||
var sensitivity = 1.15f
|
||||
var desktop = false
|
||||
var clicks = true
|
||||
set(value) {
|
||||
if (field != value) lastTapAt = 0L
|
||||
field = value
|
||||
}
|
||||
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var lastX = 0f
|
||||
@@ -50,12 +55,17 @@ class TouchpadGestures(
|
||||
held = true
|
||||
dragging = true
|
||||
listener.onLongPress()
|
||||
listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
|
||||
press(PointerGestures.BTN_LEFT)
|
||||
}
|
||||
private val clickUp = Runnable { releaseClick() }
|
||||
|
||||
private fun press(button: Int) {
|
||||
if (clicks) listener.onButton(button, true, x, y)
|
||||
}
|
||||
|
||||
private fun click(button: Int) {
|
||||
releaseClick()
|
||||
if (!clicks) return
|
||||
listener.onButton(button, true, x, y)
|
||||
clicked = button
|
||||
handler.postDelayed(clickUp, TouchTiming.CLICK_MS)
|
||||
@@ -108,12 +118,12 @@ class TouchpadGestures(
|
||||
travelled = 0f; held = false; twoFingers = false; scrolled = false; secondWasTap = false
|
||||
fingers = 1; pinching = false
|
||||
anchorId = event.getPointerId(0); moverId = -1; holdDrag = false; scrollLocked = false
|
||||
if (event.eventTime - lastTapAt < TouchTiming.DOUBLE_TAP_MS) {
|
||||
if (clicks && event.eventTime - lastTapAt < TouchTiming.DOUBLE_TAP_MS) {
|
||||
dragging = true
|
||||
listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
|
||||
press(PointerGestures.BTN_LEFT)
|
||||
} else {
|
||||
dragging = false
|
||||
handler.postDelayed(longPress, TouchTiming.HOLD_MS)
|
||||
if (clicks) handler.postDelayed(longPress, TouchTiming.HOLD_MS)
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -153,7 +163,7 @@ class TouchpadGestures(
|
||||
secondWasTap = false
|
||||
if (!dragging) {
|
||||
dragging = true
|
||||
listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
|
||||
press(PointerGestures.BTN_LEFT)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,12 +218,15 @@ object BwrapSpawner {
|
||||
private fun runtimeLib(rootfs: String, name: String): File? =
|
||||
LIB_DIRS.map { File(rootfs, "$it/$name") }.firstOrNull { it.exists() }
|
||||
|
||||
private fun gpu(rootfs: String, root: File, env: MutableMap<String, String>): List<Bind>? {
|
||||
internal fun gpu(
|
||||
rootfs: String, root: File, env: MutableMap<String, String>,
|
||||
kgslAvailable: Boolean = File("/dev/kgsl-3d0").exists(),
|
||||
): List<Bind>? {
|
||||
env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock) }
|
||||
val driver = runtimeLib(rootfs, "libvulkan_freedreno.so")
|
||||
if (driver == null || !File("/dev/kgsl-3d0").exists()) return null
|
||||
if (driver == null || !kgslAvailable) return null
|
||||
if (env.containsKey("VK_ICD_FILENAMES") || env.containsKey("VK_DRIVER_FILES")) return null
|
||||
if (env["BL_DESKTOP"] == "1" && env["GAMESCOPE_WAYLAND_DISPLAY"] == null) return null
|
||||
if (env["LIBGL_ALWAYS_SOFTWARE"] == "1" && env["GAMESCOPE_WAYLAND_DISPLAY"] == null) return null
|
||||
val binds = arrayListOf(Bind(driver.canonicalPath, "$GPU_DIR/libvulkan_freedreno.so"))
|
||||
for (name in GPU_LIBS) {
|
||||
val f = runtimeLib(rootfs, name) ?: continue
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
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.WindowManager
|
||||
|
||||
// While a session runs, sits invisibly on top of every other display until it ends, 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.
|
||||
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_TOUCHABLE or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
|
||||
val id = display?.displayId ?: Display.INVALID_DISPLAY
|
||||
starting.remove(id)
|
||||
guards[id]?.takeIf { it !== this && !it.isFinishing }?.finishAndRemoveTask()
|
||||
guards[id] = this
|
||||
}
|
||||
|
||||
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>()
|
||||
|
||||
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 || 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 release() {
|
||||
generation++
|
||||
guards.values.toList().forEach { it.finishAndRemoveTask() }
|
||||
guards.clear()
|
||||
starting.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())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
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 }
|
||||
}
|
||||
@@ -544,6 +544,7 @@ object SessionArtifacts {
|
||||
"session died of a crash, the entry is in there unless the device rebooted.\n" +
|
||||
(if (newest) exitReasons(context) else "")
|
||||
)
|
||||
restartNote(File(dir, "device.txt").lastModified(), bootedAt())?.let { recoveryNote.appendText(it) }
|
||||
if (newest && lastExitForMemory(context)) killedForMemory = true
|
||||
}
|
||||
if (recoveryPreviouslyAttempted && !runtimeCaptured.exists() &&
|
||||
@@ -686,5 +687,21 @@ object SessionArtifacts {
|
||||
return gone.size
|
||||
}
|
||||
|
||||
private fun bootedAt(): Long = System.currentTimeMillis() - android.os.SystemClock.elapsedRealtime()
|
||||
|
||||
internal fun restartNote(sessionStartedAt: Long, bootedAt: Long): String? {
|
||||
if (sessionStartedAt <= 0L) return null
|
||||
val stamp = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US)
|
||||
return if (bootedAt > sessionStartedAt + BOOT_CLOCK_SLACK_MS) {
|
||||
"The device itself probably restarted after this session began (estimated boot ${stamp.format(Date(bootedAt))}, from the clock and uptime, so a clock change can fake it):\n" +
|
||||
"if so, the whole system went down and crash.log is the new boot's buffer and says nothing about the session.\n"
|
||||
} else {
|
||||
"The device does not appear to have restarted since this session began (estimated boot ${stamp.format(Date(bootedAt))}, from the clock and uptime):\n" +
|
||||
"only this app's processes ended, so crash.log and the exit records cover the end.\n"
|
||||
}
|
||||
}
|
||||
|
||||
private const val BOOT_CLOCK_SLACK_MS = 60_000L
|
||||
|
||||
private fun now(): String = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date())
|
||||
}
|
||||
@@ -1428,6 +1428,28 @@ class SessionService : Service() {
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "steam library: the list could not be written; the card alone this session", e)
|
||||
}
|
||||
if (SessionState.mode == MODE_DESKTOP) {
|
||||
try {
|
||||
val listing = File(filesDir, "session/desktop-volumes.json").apply { parentFile?.mkdirs() }
|
||||
val volumes = org.json.JSONArray()
|
||||
var room = if (ProotFastPath.enabled(this)) {
|
||||
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds).size
|
||||
} else Int.MAX_VALUE
|
||||
for (root in com.droiddeck.launcher.files.StorageRoots.list(this)) {
|
||||
if (!root.removable || !root.readable) continue
|
||||
val path = root.dir.absolutePath
|
||||
if (':' in path || '|' in path || room <= 0) continue
|
||||
binds.add(path)
|
||||
room--
|
||||
volumes.put(org.json.JSONObject().put("path", path).put("label", root.label))
|
||||
}
|
||||
listing.writeText(volumes.toString())
|
||||
val envAt = guest.indexOf(LinuxRuntime.SESSION_SCRIPT).takeIf { it >= 0 } ?: guest.size
|
||||
guest.add(envAt, "BL_DESKTOP_VOLUMES=" + listing.path)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "desktop volumes: the list could not be written", e)
|
||||
}
|
||||
}
|
||||
return binds
|
||||
}
|
||||
|
||||
@@ -2325,7 +2347,8 @@ 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)) return
|
||||
com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name,
|
||||
KeepTopActivity::class.java.name)) return
|
||||
if (pipTask || xrActivityVisible) {
|
||||
Log.i(TAG, "panel task dismissed - retaining the session under its active surface policy")
|
||||
activityVisible = false
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import android.content.Context
|
||||
import java.io.File
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
internal object StoreLibraryCache {
|
||||
private fun file(context: Context, store: Store) = File(context.filesDir, "store-library/${store.id}.json")
|
||||
|
||||
fun load(context: Context, store: Store): List<CatalogItem>? {
|
||||
val f = file(context, store)
|
||||
if (!f.isFile) return null
|
||||
return runCatching { decode(store, f.readText()) }.getOrNull()
|
||||
}
|
||||
|
||||
fun save(context: Context, store: Store, items: List<CatalogItem>) {
|
||||
val f = file(context, store)
|
||||
runCatching {
|
||||
f.parentFile?.mkdirs()
|
||||
val tmp = File(f.parentFile, f.name + ".tmp")
|
||||
tmp.writeText(encode(items))
|
||||
if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) }
|
||||
}
|
||||
}
|
||||
|
||||
fun clear(context: Context, store: Store) {
|
||||
file(context, store).delete()
|
||||
}
|
||||
|
||||
internal fun encode(items: List<CatalogItem>): String {
|
||||
val out = JSONArray()
|
||||
items.forEach { i ->
|
||||
out.put(JSONObject()
|
||||
.put("id", i.id).put("title", i.title)
|
||||
.put("image", i.imageUrl ?: "").put("tall", i.tallImageUrl ?: "").put("logo", i.logoUrl ?: "")
|
||||
.put("tags", i.tags).put("free", i.isFree).put("hasPrice", i.hasPrice)
|
||||
.put("finalPrice", i.finalPrice).put("originalPrice", i.originalPrice).put("discount", i.discountPercent)
|
||||
.put("url", i.storeUrl).put("developer", i.developer).put("publisher", i.publisher)
|
||||
.put("releaseDate", i.releaseDate).put("description", i.description)
|
||||
.put("owned", i.owned).put("size", i.sizeBytes).put("extra", JSONObject(i.extra))
|
||||
.put("mature", i.mature).put("subscription", i.subscription).put("includedWith", i.includedWith))
|
||||
}
|
||||
return out.toString()
|
||||
}
|
||||
|
||||
internal fun decode(store: Store, text: String): List<CatalogItem> {
|
||||
val raw = JSONArray(text)
|
||||
return (0 until raw.length()).mapNotNull { n ->
|
||||
val o = raw.optJSONObject(n) ?: return@mapNotNull null
|
||||
val extra = o.optJSONObject("extra")
|
||||
val map = HashMap<String, String>()
|
||||
extra?.keys()?.forEach { k -> map[k] = extra.optString(k) }
|
||||
CatalogItem(
|
||||
store = store, id = o.optString("id"), title = o.optString("title"),
|
||||
imageUrl = o.optString("image").ifBlank { null }, tallImageUrl = o.optString("tall").ifBlank { null },
|
||||
logoUrl = o.optString("logo").ifBlank { null },
|
||||
tags = o.optString("tags"), isFree = o.optBoolean("free"), hasPrice = o.optBoolean("hasPrice"),
|
||||
finalPrice = o.optString("finalPrice"), originalPrice = o.optString("originalPrice"), discountPercent = o.optInt("discount"),
|
||||
storeUrl = o.optString("url"), developer = o.optString("developer"), publisher = o.optString("publisher"),
|
||||
releaseDate = o.optString("releaseDate"), description = o.optString("description"),
|
||||
owned = o.optBoolean("owned"), sizeBytes = o.optLong("size"), extra = map,
|
||||
mature = o.optBoolean("mature"), subscription = o.optBoolean("subscription"), includedWith = o.optString("includedWith"),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -202,6 +202,7 @@ object StoresState {
|
||||
backend?.signOut(app)
|
||||
if (store == Store.GOG) com.droiddeck.launcher.stores.gog.GogComet.replaceAccount { StoreAccounts.clear(app, store) }
|
||||
else if (store != Store.XBOX || backend == null) StoreAccounts.clear(app, store)
|
||||
StoreLibraryCache.clear(app, store)
|
||||
if (store == Store.GAMEJOLT) {
|
||||
com.droiddeck.launcher.stores.gamejolt.GameJoltCollections.clear()
|
||||
com.droiddeck.launcher.stores.gamejolt.GameJoltUpdates.clear(app)
|
||||
|
||||
@@ -14,6 +14,7 @@ import com.droiddeck.launcher.stores.StoreFront
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreLoginActivity
|
||||
import com.droiddeck.launcher.stores.StoreShelves
|
||||
import com.droiddeck.launcher.stores.StoreLibraryCache
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.WebCookies
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
@@ -163,7 +164,13 @@ object RockstarLibrary {
|
||||
post(gen) { StoresState.status.remove(Store.ROCKSTAR); StoresState.problems[Store.ROCKSTAR] = app.getString(R.string.stores_sync_sign_in) }
|
||||
return
|
||||
}
|
||||
if (StoresState.library[Store.ROCKSTAR].isNullOrEmpty()) post(gen) { StoresState.status[Store.ROCKSTAR] = app.getString(R.string.stores_sync_game_list) }
|
||||
val cached = StoreLibraryCache.load(app, Store.ROCKSTAR)
|
||||
post(gen) {
|
||||
if (StoresState.library[Store.ROCKSTAR] == null) {
|
||||
if (cached != null) StoresState.library[Store.ROCKSTAR] = cached
|
||||
else StoresState.status[Store.ROCKSTAR] = app.getString(R.string.stores_sync_game_list)
|
||||
}
|
||||
}
|
||||
val account = RockstarApps.fetch(t.ticket) { StoresState.logLine(it) }
|
||||
val games = games(account)
|
||||
owned(account).filter { o -> games.none { it.id == o.id } }.takeIf { it.isNotEmpty() }?.let { elsewhere ->
|
||||
@@ -175,6 +182,7 @@ object RockstarLibrary {
|
||||
StoresState.library[Store.ROCKSTAR] = games
|
||||
StoresState.shelves[Store.ROCKSTAR]?.let { StoresState.shelves[Store.ROCKSTAR] = StoreFront.markOwned(it, games, RockstarCatalog::sameGame) }
|
||||
}
|
||||
if (generation.get() == gen) StoreLibraryCache.save(app, Store.ROCKSTAR, games)
|
||||
StoresState.logLine("Rockstar: ${games.size} owned games")
|
||||
} catch (e: Exception) {
|
||||
StoresState.logLine("Rockstar: library sync failed: ${e.javaClass.simpleName} ${e.message.orEmpty().take(300)}")
|
||||
|
||||
@@ -15,6 +15,7 @@ import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.StoreLoginActivity
|
||||
import com.droiddeck.launcher.stores.StoreLibraryCache
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.WebCookies
|
||||
import org.json.JSONObject
|
||||
@@ -206,7 +207,13 @@ object UbisoftLibrary {
|
||||
post(gen) { StoresState.status.remove(Store.UBISOFT); StoresState.problems[Store.UBISOFT] = app.getString(R.string.stores_sync_sign_in) }
|
||||
return
|
||||
}
|
||||
if (StoresState.library[Store.UBISOFT].isNullOrEmpty()) post(gen) { StoresState.status[Store.UBISOFT] = app.getString(R.string.stores_sync_game_list) }
|
||||
val cached = StoreLibraryCache.load(app, Store.UBISOFT)
|
||||
post(gen) {
|
||||
if (StoresState.library[Store.UBISOFT] == null) {
|
||||
if (cached != null) StoresState.library[Store.UBISOFT] = cached
|
||||
else StoresState.status[Store.UBISOFT] = app.getString(R.string.stores_sync_game_list)
|
||||
}
|
||||
}
|
||||
val all = ArrayList<CatalogItem>()
|
||||
var offset = 0
|
||||
while (true) {
|
||||
@@ -241,6 +248,7 @@ object UbisoftLibrary {
|
||||
StoresState.library[Store.UBISOFT] = games
|
||||
StoresState.shelves[Store.UBISOFT]?.let { StoresState.shelves[Store.UBISOFT] = StoreFront.markOwned(it, games, UbisoftStore::sameGame) }
|
||||
}
|
||||
if (generation.get() == gen) StoreLibraryCache.save(app, Store.UBISOFT, games)
|
||||
StoresState.logLine("Ubisoft: ${games.size} owned games")
|
||||
} catch (e: Exception) {
|
||||
StoresState.logLine("Ubisoft: library sync failed: ${e.javaClass.simpleName} ${e.message.orEmpty().take(200)}")
|
||||
|
||||
@@ -50,7 +50,7 @@ import androidx.compose.material.icons.outlined.Mic
|
||||
import androidx.compose.material.icons.outlined.Add
|
||||
import androidx.compose.material.icons.outlined.ArrowDownward
|
||||
import androidx.compose.material.icons.outlined.AttachFile
|
||||
import androidx.compose.material.icons.outlined.AutoAwesome
|
||||
import androidx.compose.material.icons.outlined.Terminal
|
||||
import androidx.compose.material.icons.outlined.Build
|
||||
import androidx.compose.material.icons.outlined.Close
|
||||
import androidx.compose.material.icons.outlined.ExpandMore
|
||||
@@ -451,7 +451,7 @@ private fun AgentConversation(modifier: Modifier, list: LazyListState, following
|
||||
}
|
||||
if (AgentHost.entries.isEmpty() && !working) {
|
||||
Column(modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
|
||||
Icon(Icons.Outlined.AutoAwesome, null, tint = pal.primary, modifier = Modifier.size(40.dp))
|
||||
Icon(Icons.Outlined.Terminal, null, tint = pal.primary, modifier = Modifier.size(40.dp))
|
||||
Text(stringResource(R.string.agent_empty), fontSize = 15.sp, color = pal.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center, modifier = Modifier.widthIn(max = 460.dp).padding(top = 12.dp))
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ import com.droiddeck.launcher.input.*
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
|
||||
private data class SurfaceSnapshot(val elements: List<InputSurfaceElement>, val actions: Map<String, InputAction>,
|
||||
val clicks: Map<String, InputAction>, val scale: Float)
|
||||
val clicks: Map<String, InputAction>, val scale: Float, val aspect: Float)
|
||||
|
||||
private class GamepadScaler(private val context: android.content.Context, private val width: Int, private val height: Int) {
|
||||
private fun generator(scale: Float) = LegacyGamepadLayout(context, width, height, scale = scale)
|
||||
@@ -83,6 +83,7 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
|
||||
var clickProperties by mutableStateOf(false)
|
||||
var history by mutableStateOf<List<SurfaceSnapshot>>(emptyList())
|
||||
var layoutScale by mutableFloatStateOf(layout.scale)
|
||||
var aspect by mutableFloatStateOf(layout.aspect)
|
||||
private var scaleBase by mutableStateOf<Triple<List<InputSurfaceElement>, List<InputSurfaceElement>, Float>?>(null)
|
||||
private var scaleValue by mutableIntStateOf(100)
|
||||
private val rescales get() = gamepad != null && elements.any { it.id in gamepad.ids }
|
||||
@@ -94,9 +95,14 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
|
||||
val positioned get() = (if (rescales) gamepad!!.reset(elements) else defaults?.let { elements.withPositionsOf(it) })
|
||||
?.takeIf { it != elements || rescales && layoutScale != 1f }
|
||||
val element get() = elements.firstOrNull { it.id == selected }
|
||||
val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale
|
||||
fun checkpoint() { history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale)).takeLast(40) }
|
||||
fun undo() { history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; history = history.dropLast(1) } }
|
||||
val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale || aspect != layout.aspect
|
||||
fun checkpoint() { history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale, aspect)).takeLast(40) }
|
||||
fun undo() { history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; aspect = it.aspect; history = history.dropLast(1) } }
|
||||
fun beginEdit(displayed: List<InputSurfaceElement>, aspect: Float) {
|
||||
checkpoint()
|
||||
elements = OnScreenLayout.editorFrame(layout.copy(elements = elements), displayed)
|
||||
this.aspect = aspect
|
||||
}
|
||||
fun scaleAll(percent: Int) {
|
||||
val base = scaleBase?.takeIf { it.second == elements } ?: Triple(elements, elements, if (rescales) layoutScale else 0f).also { checkpoint() }
|
||||
val factor = percent / 100f
|
||||
@@ -112,10 +118,6 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
|
||||
fun clickAction(e: InputSurfaceElement) = preset.copy(elements = actions, clicks = clicks).clickAction(e)
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun displayAspect(display: Display): Float? = android.util.DisplayMetrics().also(display::getRealMetrics)
|
||||
.takeIf { it.widthPixels > 0 && it.heightPixels > 0 }?.let { (it.widthPixels.toFloat() / it.heightPixels).coerceIn(.05f, 20f) }
|
||||
|
||||
@Composable
|
||||
fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> Unit,
|
||||
role: InputRole = InputRole.SECONDARY, layoutId: String? = null, bindingsId: String? = null) {
|
||||
@@ -153,7 +155,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
|
||||
InputLibraries.update(context) { latest ->
|
||||
val l = latest.layouts.first { it.id == savedLayout.id }
|
||||
val p = latest.preset(savedBindings.id)
|
||||
latest.withLayout(l.copy(elements = draft.elements, aspect = target?.let(::displayAspect) ?: l.aspect, scale = draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } },
|
||||
latest.withLayout(l.copy(elements = draft.elements, aspect = draft.aspect, scale = draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } },
|
||||
clicks = draft.clicks.filterKeys { id -> draft.elements.any { it.id == id && it.hasClick } }))
|
||||
}
|
||||
}.onSuccess { onChanged(); onDismiss() }.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
|
||||
@@ -253,10 +255,10 @@ private fun SurfaceCanvas(draft: SurfaceDraft, transparent: Boolean = false) {
|
||||
AndroidView(factory = { InputSurfaceEditorView(it) }, modifier = Modifier.fillMaxSize().testTag("input-layout-canvas"),
|
||||
update = { view ->
|
||||
view.setBackgroundColor(if (transparent) android.graphics.Color.TRANSPARENT else android.graphics.Color.rgb(10, 11, 13))
|
||||
view.style = draft.layout.style.copy(hidden = emptySet()); view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap
|
||||
view.style = draft.layout.style.copy(hidden = emptySet()); view.sourceLayout = draft.layout; view.aspect = draft.aspect; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap
|
||||
view.isEnabled = !draft.properties && !draft.adding
|
||||
view.onSelect = { if (!draft.properties) draft.selected = it }
|
||||
view.onBeginEdit = draft::checkpoint
|
||||
view.onBeginEdit = draft::beginEdit
|
||||
view.onChange = { e -> if (!draft.properties) draft.elements = draft.elements.map { if (it.id == e.id) e else it } }
|
||||
|
||||
})
|
||||
|
||||
@@ -9,6 +9,8 @@ import android.view.HapticFeedbackConstants
|
||||
import android.view.MotionEvent
|
||||
import android.view.ViewConfiguration
|
||||
import android.widget.FrameLayout
|
||||
import com.droiddeck.launcher.input.OnScreenLayout
|
||||
import com.droiddeck.launcher.input.SavedInputLayout
|
||||
import com.droiddeck.launcher.input.InputSurfaceElement
|
||||
import com.droiddeck.launcher.input.InputSurfaceStyle
|
||||
import com.droiddeck.launcher.input.snapSurfaceElement
|
||||
@@ -16,7 +18,11 @@ import kotlin.math.abs
|
||||
|
||||
internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
|
||||
var elements: List<InputSurfaceElement> = emptyList()
|
||||
set(value) { field = value; preview.updateCustomLayout(value); invalidate() }
|
||||
set(value) { field = value; refreshElements(); invalidate() }
|
||||
var aspect = 1f
|
||||
set(value) { field = value; refreshElements(); invalidate() }
|
||||
var sourceLayout: SavedInputLayout? = null
|
||||
set(value) { field = value; refreshElements(); invalidate() }
|
||||
var style = InputSurfaceStyle()
|
||||
set(value) { field = value; preview.updateStyle(value) }
|
||||
var snap = true
|
||||
@@ -26,7 +32,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
|
||||
var selected: String? = null
|
||||
set(value) { field = value; invalidate() }
|
||||
var onSelect: (String?) -> Unit = {}
|
||||
var onBeginEdit: () -> Unit = {}
|
||||
var onBeginEdit: (List<InputSurfaceElement>, Float) -> Unit = { _, _ -> }
|
||||
var onChange: (InputSurfaceElement) -> Unit = {}
|
||||
private val preview = InputSurfaceView(context)
|
||||
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.rgb(26, 159, 255); strokeWidth = 2 * resources.displayMetrics.density }
|
||||
@@ -37,17 +43,31 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
|
||||
private var corner = 0
|
||||
private var dragging = false
|
||||
|
||||
private var visibleElements: List<InputSurfaceElement> = emptyList()
|
||||
|
||||
init {
|
||||
setBackgroundColor(Color.rgb(10, 11, 13))
|
||||
addView(preview, LayoutParams(-1, -1))
|
||||
}
|
||||
|
||||
private fun refreshElements() {
|
||||
visibleElements = sourceLayout?.let { layout ->
|
||||
OnScreenLayout.editorElements(context, layout.copy(elements = elements, aspect = aspect), width, height)
|
||||
} ?: elements
|
||||
preview.updateCustomLayout(visibleElements)
|
||||
}
|
||||
|
||||
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
|
||||
super.onSizeChanged(w, h, oldw, oldh)
|
||||
refreshElements()
|
||||
}
|
||||
|
||||
override fun dispatchDraw(canvas: Canvas) {
|
||||
super.dispatchDraw(canvas)
|
||||
paint.style = Paint.Style.STROKE
|
||||
guideX?.let { canvas.drawLine(width * it, 0f, width * it, height.toFloat(), paint) }
|
||||
guideY?.let { canvas.drawLine(0f, height * it, width.toFloat(), height * it, paint) }
|
||||
val e = elements.firstOrNull { it.id == selected } ?: return
|
||||
val e = visibleElements.firstOrNull { it.id == selected } ?: return
|
||||
val l = width * e.x; val t = height * e.y; val r = l + width * e.width; val b = t + height * e.height
|
||||
paint.style = Paint.Style.STROKE; canvas.drawRect(l, t, r, b, paint)
|
||||
paint.style = Paint.Style.FILL
|
||||
@@ -65,7 +85,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
clearGuides()
|
||||
downX = event.x; downY = event.y; dragging = false; corner = 0
|
||||
val current = elements.firstOrNull { it.id == selected }
|
||||
val current = visibleElements.firstOrNull { it.id == selected }
|
||||
if (current != null) {
|
||||
val left = width * current.x; val top = height * current.y
|
||||
val right = left + width * current.width; val bottom = top + height * current.height
|
||||
@@ -73,7 +93,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
|
||||
val vertical = if (abs(downY - top) < radius) 4 else if (abs(downY - bottom) < radius) 8 else 0
|
||||
if (horizontal != 0 && vertical != 0) corner = horizontal or vertical
|
||||
}
|
||||
original = if (corner != 0) current else elements.asReversed().firstOrNull {
|
||||
original = if (corner != 0) current else visibleElements.asReversed().firstOrNull {
|
||||
downX / width in it.x..(it.x + it.width) && downY / height in it.y..(it.y + it.height)
|
||||
}
|
||||
selected = original?.id; onSelect(selected)
|
||||
@@ -81,7 +101,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
val e = original ?: return true
|
||||
if (!dragging && abs(event.x - downX) + abs(event.y - downY) > ViewConfiguration.get(context).scaledTouchSlop) {
|
||||
dragging = true; onBeginEdit()
|
||||
dragging = true; onBeginEdit(visibleElements, width.toFloat() / height)
|
||||
}
|
||||
if (!dragging) return true
|
||||
val dx = (event.x - downX) / width; val dy = (event.y - downY) / height
|
||||
@@ -93,7 +113,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
|
||||
val bottom = if (corner and 8 != 0) (e.y + e.height + dy).coerceIn(top + .03f, 1f) else e.y + e.height
|
||||
e.copy(x = left, y = top, width = right - left, height = bottom - top).bounded()
|
||||
}
|
||||
val aligned = if (snap) snapSurfaceElement(next, elements.filter { it.id != e.id }, 9 * resources.displayMetrics.density / width,
|
||||
val aligned = if (snap) snapSurfaceElement(next, visibleElements.filter { it.id != e.id }, 9 * resources.displayMetrics.density / width,
|
||||
9 * resources.displayMetrics.density / height, corner) else null
|
||||
if (aligned != null && (aligned.x != null && aligned.x != guideX || aligned.y != null && aligned.y != guideY)) performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
|
||||
guideX = aligned?.x; guideY = aligned?.y
|
||||
|
||||
@@ -48,7 +48,7 @@ class InputSurfaceView(
|
||||
context: Context,
|
||||
private val pad: PadBridge? = null,
|
||||
private var customLayout: List<InputSurfaceElement> = emptyList(),
|
||||
private val inputRole: InputRole = InputRole.SECONDARY,
|
||||
val inputRole: InputRole = InputRole.SECONDARY,
|
||||
private var surfaceStyle: InputSurfaceStyle = InputSurfaceStyle(),
|
||||
private val haptics: Boolean = inputRole != InputRole.PRIMARY,
|
||||
) : FrameLayout(context) {
|
||||
@@ -59,6 +59,7 @@ class InputSurfaceView(
|
||||
private var requestedLayout = customLayout
|
||||
init { customLayout = surfaceStyle.shown(customLayout); addView(content, LayoutParams(-1, -1)); renderCustom(pad) }
|
||||
|
||||
val shownElements: List<InputSurfaceElement> get() = customLayout
|
||||
var onTouchMiss: ((MotionEvent) -> Unit)? = null
|
||||
private var forwardedPointers = 0
|
||||
|
||||
|
||||
@@ -63,7 +63,8 @@ class SecondScreenPresentation(
|
||||
private var imeSeen = false
|
||||
private var fieldKeyboard = false
|
||||
private var terminalPanel: SessionTerminalPanel? = null
|
||||
private var controlsView: InputSurfaceView? = null
|
||||
var controlsView: InputSurfaceView? = null
|
||||
private set
|
||||
private var created = false
|
||||
|
||||
init {
|
||||
|
||||
@@ -43,7 +43,6 @@ import androidx.compose.material.icons.outlined.PowerSettingsNew
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.material.icons.outlined.DesktopWindows
|
||||
import androidx.compose.material.icons.outlined.Layers
|
||||
import androidx.compose.material.icons.outlined.AutoAwesome
|
||||
import androidx.compose.material.icons.outlined.ScreenShare
|
||||
import androidx.compose.material.icons.outlined.Pause
|
||||
import androidx.compose.material.icons.outlined.PictureInPictureAlt
|
||||
@@ -186,7 +185,7 @@ private val SessionDrawerPage.icon get() = when (this) {
|
||||
SessionDrawerPage.VR -> VrHeadsetIcon
|
||||
SessionDrawerPage.EFFECTS -> Icons.Outlined.AutoFixHigh
|
||||
SessionDrawerPage.GAMES -> Icons.Outlined.Layers
|
||||
SessionDrawerPage.AGENT -> Icons.Outlined.AutoAwesome
|
||||
SessionDrawerPage.AGENT -> Icons.Outlined.Terminal
|
||||
SessionDrawerPage.SESSION -> Icons.Outlined.Settings
|
||||
}
|
||||
|
||||
@@ -262,6 +261,7 @@ class DrawerActions(
|
||||
val secondScreenNone: Boolean = true,
|
||||
val gameOnBottom: Boolean = false,
|
||||
val gameSwapAvailable: Boolean = false,
|
||||
val gameSwapBuiltIn: Boolean = true,
|
||||
val onGameOnBottom: (Boolean) -> Unit = {},
|
||||
val dashboardAvailable: Boolean = false,
|
||||
val desktopAvailable: Boolean = false,
|
||||
@@ -1303,7 +1303,8 @@ private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String)
|
||||
}
|
||||
if (a.gameSwapAvailable || a.gameOnBottom) SettingsGroup(stringResource(R.string.swap_game_screen_group)) {
|
||||
ChoiceRow(host, "game-screen", stringResource(R.string.swap_game_screen), null,
|
||||
listOf(false to stringResource(R.string.swap_game_screen_top), true to stringResource(R.string.swap_game_screen_bottom)),
|
||||
if (a.gameSwapBuiltIn) listOf(false to stringResource(R.string.swap_game_screen_top), true to stringResource(R.string.swap_game_screen_bottom))
|
||||
else listOf(false to stringResource(R.string.main_primary), true to stringResource(R.string.main_secondary)),
|
||||
a.gameOnBottom, chipModifier = track("game-screen"), onPick = a.onGameOnBottom)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
<string name="input_element_dpad">Cruce</string>
|
||||
<string name="input_element_trigger">Trăgaci</string>
|
||||
<string name="input_editor_done">Gata</string>
|
||||
<string name="input_editor_undo">Anulează</string>
|
||||
<string name="input_editor_undo">Anulează ultima acțiune</string>
|
||||
<string name="input_editor_add">+ Adaugă</string>
|
||||
<string name="input_editor_hint">Trage pentru a muta. Trage de un colț pentru a redimensiona. Atinge Proprietăți pentru a atribui o acțiune.</string>
|
||||
<string name="input_editor_remote">Editare pe ecranul secundar</string>
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
<string name="input_element_dpad">Хрестовина</string>
|
||||
<string name="input_element_trigger">Тригер</string>
|
||||
<string name="input_editor_done">Готово</string>
|
||||
<string name="input_editor_undo">Скасувати</string>
|
||||
<string name="input_editor_undo">Скасувати дію</string>
|
||||
<string name="input_editor_add">+ Додати</string>
|
||||
<string name="input_editor_hint">Перетягніть, щоб перемістити. Потягніть за кут, щоб змінити розмір. Торкніться «Властивості», щоб призначити дію.</string>
|
||||
<string name="input_editor_remote">Редагування на другому екрані</string>
|
||||
|
||||
@@ -29,6 +29,26 @@ class DualScreenTest {
|
||||
assertFalse(DualScreen.isBuiltIn(5, "AYN Thor"))
|
||||
}
|
||||
|
||||
@Test @Config(sdk = [34]) fun selectedInternalAndExternalDisplaysCanBeUsed() {
|
||||
withDisplay(INTERNAL, "Bottom screen") { internal ->
|
||||
assertEquals(internal.displayId, DualScreen.selectedSessionDisplay(context, displays, Display.DEFAULT_DISPLAY, internal.displayId)?.displayId)
|
||||
}
|
||||
withDisplay(EXTERNAL, "HDMI Screen") { external ->
|
||||
assertEquals(external.displayId, DualScreen.selectedSessionDisplay(context, displays, Display.DEFAULT_DISPLAY, external.displayId)?.displayId)
|
||||
SessionPrefs.setDualScreenSessionMode(context, DualScreen.MODE_OFF)
|
||||
assertNull(DualScreen.selectedSessionDisplay(context, displays, Display.DEFAULT_DISPLAY, external.displayId))
|
||||
SessionPrefs.setDualScreenSessionMode(context, DualScreen.MODE_AUTO)
|
||||
}
|
||||
}
|
||||
|
||||
@Test @Config(sdk = [34]) fun missingOrRemovedSelectedDisplaysCannotBeUsed() {
|
||||
assertNull(DualScreen.selectedSessionDisplay(context, displays, Display.DEFAULT_DISPLAY, Display.INVALID_DISPLAY))
|
||||
val id = ShadowDisplayManager.addDisplay("w640dp-h480dp", EXTERNAL)
|
||||
shadowOf(displays.getDisplay(id)).setFlags(Display.FLAG_PRESENTATION)
|
||||
ShadowDisplayManager.removeDisplay(id)
|
||||
assertNull(DualScreen.selectedSessionDisplay(context, displays, Display.DEFAULT_DISPLAY, id))
|
||||
}
|
||||
|
||||
@Test fun knownModelsCountWhenTheTypeIsHidden() {
|
||||
assertTrue(DualScreen.isBuiltIn(null, "Retroid Pocket Duo"))
|
||||
assertTrue(DualScreen.isBuiltIn(null, " AYN Thor "))
|
||||
|
||||
@@ -162,6 +162,23 @@ class InputLayoutToolsTest {
|
||||
assertEquals(label, emptyList<Pair<String, String>>(), overlapping(elements, width, height))
|
||||
}
|
||||
|
||||
private fun assertStickView(elements: List<InputSurfaceElement>, width: Int, height: Int, label: String) {
|
||||
for (control in listOf(InputControl.LS, InputControl.RS)) {
|
||||
val stick = elements.first { it.control == control }
|
||||
assertTrue("$label ${stick.id} keeps its widened travel width", stick.width * width >= stick.height * height * 1.25f - 1f)
|
||||
assertTrue("$label ${stick.id} stays on screen", stick.x >= 0f && stick.x + stick.width <= 1.0001f)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun sticksKeepTheirFullViewAtSurfaceEdges() {
|
||||
for ((width, height) in listOf(2608 to 1200, 1920 to 1080, 1280 to 960)) {
|
||||
ControllerPrefs.setLayout(context, width, height, mapOf("ls" to (0f to .5f), "rs" to (1f to .5f)))
|
||||
val elements = LegacyGamepadLayout(context, width, height).elements()
|
||||
assertStickView(elements, width, height, "$width x $height")
|
||||
ControllerPrefs.resetLayout(context, width, height)
|
||||
}
|
||||
}
|
||||
|
||||
@Test @Config(qualifiers = "w833dp-h468dp-land-369dpi")
|
||||
fun buttonSizeKeepsTheGamepadShapeAtHandheldDensity() {
|
||||
for ((w, h) in listOf(1920 to 1080, 1920 to 1200)) {
|
||||
@@ -191,4 +208,10 @@ class InputLayoutToolsTest {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test @Config(qualifiers = "w745dp-h343dp-land-420dpi")
|
||||
fun wideHighDensityGamepadKeepsItsShape() {
|
||||
val elements = LegacyGamepadLayout(context, 2608, 1200).elements()
|
||||
assertGamepadShape(elements, 2608, 1200, "2608 x 1200")
|
||||
}
|
||||
}
|
||||
@@ -592,4 +592,45 @@ class InputLibraryTest {
|
||||
assertEquals(old.preset(InputStockLayouts.TRACKPAD), upgraded.preset(InputStockLayouts.TRACKPAD))
|
||||
assertEquals(InputStockLayouts.layouts().single { it.id == InputLibraries.DECK }.elements, upgraded.layouts.single { it.id == InputLibraries.DECK }.elements)
|
||||
}
|
||||
|
||||
@Test fun stockSecondScreenPanelsKeepTapsClicking() {
|
||||
val library = InputLibraries.read(context)
|
||||
for (desktop in listOf(false, true)) for (panel in listOf(null, InputStockLayouts.TRACKPAD) + DeckPanel.entries.map { it.bindings }) {
|
||||
val shown = library.panelLayout(desktop, panel)!!.elements
|
||||
assertTrue(shown.isNotEmpty())
|
||||
assertFalse(library.compileActive(desktop, panel).showsMouseButton(InputRole.SECONDARY, shown, library.compileStock(desktop, panel)))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun userBoundSecondScreenMouseButtonIsDetected() {
|
||||
val stock = InputLibraries.read(context)
|
||||
val grips = DeckPanel.GRIPS.bindings
|
||||
val button = stock.panelLayout(false, grips)!!.elements.first { it.control.dimensions == 1 }
|
||||
val bound = stock.withPreset(stock.preset(grips).copy(elements = mapOf(button.id to InputAction.MouseButton(272))))
|
||||
for (desktop in listOf(false, true)) {
|
||||
assertTrue(bound.compileActive(desktop, grips).showsMouseButton(InputRole.SECONDARY, listOf(button), bound.compileStock(desktop, grips)))
|
||||
assertFalse(bound.compileActive(desktop, grips).showsMouseButton(InputRole.PRIMARY, listOf(button), bound.compileStock(desktop, grips)))
|
||||
}
|
||||
val pad = stock.panelLayout(true, InputStockLayouts.TRACKPAD)!!.elements.single()
|
||||
val rebound = stock.withPreset(stock.preset(InputStockLayouts.TRACKPAD).let { it.copy(clicks = it.clicks + (pad.id to InputAction.MouseButton(273))) })
|
||||
assertTrue(rebound.compileActive(true).showsMouseButton(InputRole.SECONDARY, listOf(pad), rebound.compileStock(true)))
|
||||
}
|
||||
|
||||
@Test fun copiedStockPanelsKeepTapsClickingUntilAMouseButtonIsAdded() {
|
||||
val stock = InputLibraries.read(context)
|
||||
for (desktop in listOf(false, true)) {
|
||||
val source = stock.panelLayout(desktop, null)!!
|
||||
val copied = stock.useLayout(stock.activeId(desktop), InputRole.SECONDARY, source.id, shared = false)
|
||||
val layout = copied.activeLayout(desktop, InputRole.SECONDARY)!!
|
||||
assertNotEquals(source.id, layout.id)
|
||||
assertEquals(source.id, layout.origin)
|
||||
assertFalse(copied.compileActive(desktop).showsMouseButton(InputRole.SECONDARY, layout.elements, copied.compileStock(desktop)))
|
||||
val added = InputSurfaceElement(InputControl.A, .4f, .4f, .1f, .1f, id = "custom:added")
|
||||
val grown = copied.withLayout(layout.copy(elements = layout.elements + added))
|
||||
val bindings = grown.activePart(desktop, InputRole.SECONDARY).bindings
|
||||
val bound = grown.withPreset(grown.preset(bindings).let { it.copy(elements = it.elements + (added.id to InputAction.MouseButton(272))) })
|
||||
assertTrue(bound.compileActive(desktop).showsMouseButton(InputRole.SECONDARY, layout.elements + added, bound.compileStock(desktop)))
|
||||
assertFalse(bound.compileActive(desktop).showsMouseButton(InputRole.SECONDARY, layout.elements, bound.compileStock(desktop)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,83 @@ class OnScreenLayoutTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test @Config(qualifiers = "w745dp-h343dp-land-420dpi")
|
||||
fun aBuiltInGamepadSavedAtTheDisplaySizeRegeneratesForTheMeasuredSurface() {
|
||||
val saved = gamepad().copy(elements = LegacyGamepadLayout(context, 2608, 1200).elements(), aspect = 2608f / 1200)
|
||||
val placed = OnScreenLayout.elements(context, saved, 2048, 1200, Rect())
|
||||
assertEquals(LegacyGamepadLayout(context, 2048, 1200).regenerate(saved.elements), placed)
|
||||
}
|
||||
|
||||
@Test @Config(qualifiers = "w745dp-h343dp-land-420dpi")
|
||||
fun previouslyGeneratedEdgeSticksRegenerateWithoutOverridingCustomGeometry() {
|
||||
val w = 2608
|
||||
val h = 1200
|
||||
ControllerPrefs.setLayout(context, w, h, mapOf("ls" to (0f to .5f), "rs" to (1f to .5f)))
|
||||
val generator = LegacyGamepadLayout(context, w, h)
|
||||
val old = generator.elements(previousStickGeometry = true)
|
||||
val current = generator.elements()
|
||||
assertTrue(old.filter { it.control == InputControl.LS || it.control == InputControl.RS }.zip(current.filter { it.control == InputControl.LS || it.control == InputControl.RS }).any { (a, b) -> kotlin.math.abs(a.width - b.width) > .01f })
|
||||
val saved = gamepad().copy(elements = old, aspect = w.toFloat() / h)
|
||||
assertEquals(LegacyGamepadLayout(context, 2048, h).regenerate(old), OnScreenLayout.elements(context, saved, 2048, h, Rect()))
|
||||
val custom = saved.copy(elements = old.map { if (it.id == "legacy:a") it.copy(x = .4f) else it })
|
||||
assertEquals(OnScreenLayout.fit(custom.elements, custom.aspect, 1f, 2048, h, Rect()), OnScreenLayout.elements(context, custom, 2048, h, Rect()))
|
||||
}
|
||||
|
||||
@Test fun savingTheEditorFrameKeepsEveryControlWhereTheEditorShowsIt() {
|
||||
val w = 2608
|
||||
val h = 1200
|
||||
val layout = SavedInputLayout("custom", "Custom", listOf(
|
||||
InputSurfaceElement(InputControl.A, .1f, .2f, .1f, .2f, "custom:a"),
|
||||
InputSurfaceElement(InputControl.B, .7f, .6f, .1f, .2f, "custom:b")), aspect = 16f / 9f)
|
||||
val displayed = OnScreenLayout.editorElements(context, layout, w, h, edited = true)
|
||||
val moved = displayed.map { if (it.id == "custom:a") it.copy(x = .4f) else it }
|
||||
val frame = OnScreenLayout.editorFrame(layout, moved + InputSurfaceElement(InputControl.X, .5f, .5f, .1f, .1f, "builtin:keyboard"))
|
||||
assertEquals(layout.elements.map { it.id }, frame.map { it.id })
|
||||
val saved = layout.copy(elements = frame, aspect = w.toFloat() / h)
|
||||
val game = OnScreenLayout.elements(context, saved, w, h, Rect())
|
||||
val editor = OnScreenLayout.editorElements(context, saved, w, h, edited = true)
|
||||
for (shown in moved) {
|
||||
assertArrayEquals(px(shown, w, h), px(game.first { it.id == shown.id }, w, h), .001f)
|
||||
assertArrayEquals(px(shown, w, h), px(editor.first { it.id == shown.id }, w, h), .001f)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun editorAndGameUseTheSamePixelRectsOnWideAndStandardScreens() {
|
||||
val layout = gamepad()
|
||||
for ((w, h) in listOf(2000 to 900, 1600 to 900)) {
|
||||
val game = OnScreenLayout.elements(context, layout, w, h, Rect())
|
||||
val editor = OnScreenLayout.editorElements(context, layout, w, h)
|
||||
assertEquals(game.map { it.id }, editor.map { it.id })
|
||||
game.zip(editor).forEach { (gameElement, editorElement) ->
|
||||
assertArrayEquals(px(gameElement, w, h), px(editorElement, w, h), .001f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun editedGeneratedAndCustomLayoutsKeepTheirPixelRectsAcrossRefreshes() {
|
||||
for ((w, h) in listOf(2000 to 900, 1600 to 900)) {
|
||||
val generated = gamepad()
|
||||
val generatedEdit = generated.elements.map { if (it.id == "legacy:a") it.copy(x = .3f, y = .4f, width = .12f, height = .12f) else it }
|
||||
val generatedSaved = generated.copy(elements = generatedEdit, aspect = w.toFloat() / h)
|
||||
val generatedPixels = px(OnScreenLayout.elements(context, generatedSaved, w, h, Rect()).first { it.id == "legacy:a" }, w, h)
|
||||
val generatedRefresh = px(OnScreenLayout.editorElements(context, generatedSaved, w, h, edited = true).first { it.id == "legacy:a" }, w, h)
|
||||
assertArrayEquals(generatedPixels, generatedRefresh, .001f)
|
||||
|
||||
val custom = SavedInputLayout("custom", "Custom", listOf(InputSurfaceElement(InputControl.A, .3f, .4f, .12f, .12f)), aspect = w.toFloat() / h)
|
||||
val customRefresh = OnScreenLayout.editorElements(context, custom, w, h, edited = true)
|
||||
assertArrayEquals(px(customRefresh.single(), w, h), px(OnScreenLayout.editorElements(context, custom.copy(elements = customRefresh), w, h, edited = true).single(), w, h), .001f)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun resetPositionsRestoresGeneratedGeometryAfterAnEdit() {
|
||||
for ((w, h) in listOf(2000 to 900, 1600 to 900)) {
|
||||
val original = gamepad()
|
||||
val moved = original.copy(elements = original.elements.map { if (it.id == "legacy:a") it.copy(x = .3f) else it }, aspect = w.toFloat() / h)
|
||||
val reset = LegacyGamepadLayout(context, w, h).regenerate(moved.elements)
|
||||
assertEquals(LegacyGamepadLayout(context, w, h).regenerate(original.elements), OnScreenLayout.elements(context, moved.copy(elements = reset), w, h, Rect()))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun regenerationKeepsTheUsersButtonStylesAndRemovedButtons() {
|
||||
val layout = gamepad().let { g -> g.copy(elements = g.elements.filterNot { it.id == "legacy:y" }.map { if (it.id == "legacy:a") it.copy(opacity = .4f, icon = 0, name = "Jump") else it }) }
|
||||
val placed = OnScreenLayout.elements(context, layout, 2000, 1000, Rect())
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class OnScreenMouseButtonTest {
|
||||
private val button = InputSurfaceElement(InputControl.A, .8f, .6f, .1f, .1f, id = "custom:left")
|
||||
private val stick = InputSurfaceElement(InputControl.LS, .1f, .6f, .2f, .3f, id = "custom:stick")
|
||||
private val legacyA = InputSurfaceElement(InputControl.A, .8f, .6f, .1f, .1f)
|
||||
private val game = InputProfile.defaults(InputProfile.GAME)
|
||||
private val desktop = InputProfile.defaults(InputProfile.DESKTOP)
|
||||
private val overlay = InputControl.entries.map { InputSurfaceElement(it, .1f, .1f, .1f, .1f) }
|
||||
|
||||
private fun profile(vararg elements: Pair<String, InputAction>, clicks: Map<String, InputAction> = emptyMap(), base: InputProfile = game) =
|
||||
base.copy(elements = mapOf(InputRole.PRIMARY to elements.toMap()), clicks = mapOf(InputRole.PRIMARY to clicks))
|
||||
|
||||
@Test fun shownButtonBoundToAMouseButtonIsDetected() {
|
||||
listOf(272, 273, 274).forEach { code ->
|
||||
assertTrue(profile(button.id to InputAction.MouseButton(code)).showsMouseButton(InputRole.PRIMARY, listOf(stick, button), game))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun stickClickBoundToAMouseButtonIsDetected() {
|
||||
val profile = profile(stick.id to InputAction.Native(), clicks = mapOf(stick.id to InputAction.MouseButton(272)))
|
||||
assertTrue(profile.showsMouseButton(InputRole.PRIMARY, listOf(stick), game))
|
||||
}
|
||||
|
||||
@Test fun legacyButtonUsesItsRoleBinding() {
|
||||
val profile = game.withBinding(InputRole.PRIMARY, InputControl.A, InputAction.MouseButton(272))
|
||||
assertTrue(profile.showsMouseButton(InputRole.PRIMARY, listOf(legacyA), game))
|
||||
assertFalse(profile.showsMouseButton(InputRole.SECONDARY, listOf(legacyA), game))
|
||||
}
|
||||
|
||||
@Test fun stockDesktopOverlayKeepsTapsClicking() {
|
||||
assertFalse(desktop.showsMouseButton(InputRole.PRIMARY, overlay, desktop))
|
||||
}
|
||||
|
||||
@Test fun userBoundMouseButtonInDesktopIsDetected() {
|
||||
val rebound = desktop.withBinding(InputRole.PRIMARY, InputControl.X, InputAction.MouseButton(272))
|
||||
assertTrue(rebound.showsMouseButton(InputRole.PRIMARY, overlay, desktop))
|
||||
val stickClick = desktop.withBinding(InputRole.PRIMARY, InputControl.L3, InputAction.MouseButton(274))
|
||||
assertTrue(stickClick.showsMouseButton(InputRole.PRIMARY, overlay, desktop))
|
||||
assertTrue(profile(button.id to InputAction.MouseButton(272), base = desktop).showsMouseButton(InputRole.PRIMARY, overlay + button, desktop))
|
||||
}
|
||||
|
||||
@Test fun desktopBindingsOnAGameBaseProfileAreUserPicked() {
|
||||
val copied = desktop.copy(id = "custom")
|
||||
assertTrue(copied.showsMouseButton(InputRole.PRIMARY, overlay, game))
|
||||
}
|
||||
|
||||
@Test fun layoutWithoutAMouseButtonKeepsTapsClicking() {
|
||||
val profile = profile(button.id to InputAction.Keys(listOf(57)), stick.id to InputAction.Pointer())
|
||||
assertFalse(profile.showsMouseButton(InputRole.PRIMARY, listOf(stick, button), game))
|
||||
assertFalse(game.showsMouseButton(InputRole.PRIMARY, listOf(legacyA, stick) + overlay, game))
|
||||
}
|
||||
|
||||
@Test fun hiddenMouseButtonDoesNotCount() {
|
||||
assertFalse(profile(button.id to InputAction.MouseButton(272)).showsMouseButton(InputRole.PRIMARY, listOf(stick), game))
|
||||
assertFalse(profile(button.id to InputAction.MouseButton(272)).showsMouseButton(InputRole.PRIMARY, emptyList(), game))
|
||||
}
|
||||
|
||||
@Test fun physicalMouseBindingsDoNotCount() {
|
||||
val profile = game.withBinding(InputRole.PHYSICAL, InputControl.A, InputAction.MouseButton(272))
|
||||
assertFalse(profile.showsMouseButton(InputRole.PRIMARY, listOf(legacyA), game))
|
||||
}
|
||||
|
||||
@Test fun invalidMouseCodeDoesNotCount() {
|
||||
assertFalse(profile(button.id to InputAction.MouseButton(1)).showsMouseButton(InputRole.PRIMARY, listOf(button), game))
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,117 @@ class PadPartialAxesTest {
|
||||
assertEquals(-0.6f, pad().rightY)
|
||||
}
|
||||
|
||||
@Test fun onlyRxRyAxesProvideTheRightStick() {
|
||||
val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY)
|
||||
motion(device, MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to -0.6f)
|
||||
assertEquals(0.6f, pad().rightX)
|
||||
assertEquals(-0.6f, pad().rightY)
|
||||
}
|
||||
|
||||
@Test fun rxRyStickWithoutZRzKeepsTriggersReleased() {
|
||||
val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY)
|
||||
motion(device, MotionEvent.AXIS_RX to 0f, MotionEvent.AXIS_RY to 0f)
|
||||
assertEquals(0f, pad().leftTrigger)
|
||||
assertEquals(0f, pad().rightTrigger)
|
||||
}
|
||||
|
||||
@Test fun rxRyStickReadsDedicatedTriggerAxes() {
|
||||
val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_RTRIGGER)
|
||||
motion(device, MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to 0f,
|
||||
MotionEvent.AXIS_LTRIGGER to 0.4f, MotionEvent.AXIS_RTRIGGER to 0f)
|
||||
assertEquals(0.6f, pad().rightX)
|
||||
assertEquals(0.4f, pad().leftTrigger)
|
||||
assertEquals(0f, pad().rightTrigger)
|
||||
}
|
||||
|
||||
@Test fun leftTriggerFallsBackToBrakeWhenDedicatedAxisIsZero() {
|
||||
val device = device(MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE)
|
||||
motion(device, MotionEvent.AXIS_LTRIGGER to 0f, MotionEvent.AXIS_BRAKE to 0.7f)
|
||||
assertEquals(0.7f, pad().leftTrigger)
|
||||
}
|
||||
|
||||
@Test fun rightTriggerFallsBackToGasWhenDedicatedAxisIsZero() {
|
||||
val device = device(MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS)
|
||||
motion(device, MotionEvent.AXIS_RTRIGGER to 0f, MotionEvent.AXIS_GAS to 0.8f)
|
||||
assertEquals(0.8f, pad().rightTrigger)
|
||||
}
|
||||
|
||||
@Test fun onlyZRzAxesProvideTheRightStick() {
|
||||
val device = device(MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ)
|
||||
motion(device, MotionEvent.AXIS_Z to 0.6f, MotionEvent.AXIS_RZ to -0.6f)
|
||||
assertEquals(0.6f, pad().rightX)
|
||||
assertEquals(-0.6f, pad().rightY)
|
||||
}
|
||||
|
||||
@Test fun bothPairsUseThePairAtRestNearCentreAsTheStick() {
|
||||
val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ)
|
||||
motion(device, MotionEvent.AXIS_RX to -1f, MotionEvent.AXIS_RY to -1f,
|
||||
MotionEvent.AXIS_Z to 0f, MotionEvent.AXIS_RZ to 0f)
|
||||
assertEquals(0f, pad().rightX)
|
||||
assertEquals(0f, pad().rightY)
|
||||
motion(device, MotionEvent.AXIS_RX to 0.2f, MotionEvent.AXIS_RY to -0.3f,
|
||||
MotionEvent.AXIS_Z to 0.7f, MotionEvent.AXIS_RZ to -0.8f)
|
||||
assertEquals(0.7f, pad().rightX)
|
||||
assertEquals(-0.8f, pad().rightY)
|
||||
}
|
||||
|
||||
@Test fun bothPairsUseRxRyAsStickWhenZRzRestAtMinimum() {
|
||||
val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ)
|
||||
motion(device, MotionEvent.AXIS_RX to 0f, MotionEvent.AXIS_RY to 0f,
|
||||
MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to -1f)
|
||||
assertEquals(0f, pad().rightX)
|
||||
assertEquals(0f, pad().rightY)
|
||||
assertEquals(0f, pad().leftTrigger)
|
||||
assertEquals(0f, pad().rightTrigger)
|
||||
motion(device, MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to -0.6f,
|
||||
MotionEvent.AXIS_Z to 1f, MotionEvent.AXIS_RZ to 1f)
|
||||
assertEquals(0.6f, pad().rightX)
|
||||
assertEquals(-0.6f, pad().rightY)
|
||||
assertEquals(1f, pad().leftTrigger)
|
||||
assertEquals(1f, pad().rightTrigger)
|
||||
}
|
||||
|
||||
@Test fun nonWiredZeroToOneSignedZTriggersNormalizeFromTheirRange() {
|
||||
val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ,
|
||||
zeroToOneAxes = setOf(MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ))
|
||||
motion(device, MotionEvent.AXIS_RX to 0f, MotionEvent.AXIS_RY to 0f,
|
||||
MotionEvent.AXIS_Z to 0f, MotionEvent.AXIS_RZ to 0f)
|
||||
assertEquals(0f, pad().leftTrigger)
|
||||
assertEquals(0f, pad().rightTrigger)
|
||||
motion(device, MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to -0.6f,
|
||||
MotionEvent.AXIS_Z to 1f, MotionEvent.AXIS_RZ to 1f)
|
||||
assertEquals(1f, pad().leftTrigger)
|
||||
assertEquals(1f, pad().rightTrigger)
|
||||
}
|
||||
|
||||
@Test fun movingFirstEventDoesNotLockTheWrongStickPair() {
|
||||
val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ)
|
||||
motion(device, MotionEvent.AXIS_RX to 1f, MotionEvent.AXIS_RY to 0f,
|
||||
MotionEvent.AXIS_Z to 0f, MotionEvent.AXIS_RZ to 0f)
|
||||
assertEquals(0f, pad().rightX)
|
||||
assertEquals(0f, pad().rightY)
|
||||
motion(device, MotionEvent.AXIS_RX to 0f, MotionEvent.AXIS_RY to 0f,
|
||||
MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to -1f)
|
||||
motion(device, MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to -0.6f,
|
||||
MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to -1f)
|
||||
assertEquals(0.6f, pad().rightX)
|
||||
assertEquals(-0.6f, pad().rightY)
|
||||
}
|
||||
|
||||
@Test fun dedicatedRightTriggerWinsOverSignedRightTrigger() {
|
||||
val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z,
|
||||
MotionEvent.AXIS_RZ, MotionEvent.AXIS_RTRIGGER)
|
||||
motion(device, MotionEvent.AXIS_RX to 0f, MotionEvent.AXIS_RY to 0f,
|
||||
MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to -1f)
|
||||
motion(device, MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to -0.6f,
|
||||
MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to -1f,
|
||||
MotionEvent.AXIS_RTRIGGER to 0.7f)
|
||||
assertEquals(0f, pad().leftTrigger)
|
||||
assertEquals(0.7f, pad().rightTrigger)
|
||||
assertEquals(0.6f, pad().rightX)
|
||||
assertEquals(-0.6f, pad().rightY)
|
||||
}
|
||||
|
||||
@Test fun sticksWithoutTriggerOrHatAxesPreserveAllDigitalControls() {
|
||||
val device = device()
|
||||
key(device, KeyEvent.KEYCODE_BUTTON_L2)
|
||||
@@ -208,14 +319,15 @@ class PadPartialAxesTest {
|
||||
try { assertTrue(bridge.onMotionEvent(event)) } finally { event.recycle() }
|
||||
}
|
||||
|
||||
private fun device(vararg axes: Int, wired: Boolean = false): InputDevice {
|
||||
private fun device(vararg axes: Int, wired: Boolean = false, zeroToOneAxes: Set<Int> = emptySet()): InputDevice {
|
||||
val builder = InputDeviceBuilder.newBuilder().setId(60).setName("partial pad")
|
||||
.setDescriptor("partial-pad").setExternal(true)
|
||||
.setSources(InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK)
|
||||
.setKeyboardType(InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC)
|
||||
.setVendorId(if (wired) 0x20d6 else 0).setProductId(if (wired) 0x2063 else 0)
|
||||
for (axis in axes.toList() + MotionEvent.AXIS_X) {
|
||||
builder.addMotionRange(axis, InputDevice.SOURCE_JOYSTICK, -1f, 1f, 0f, 0f, 0f)
|
||||
val min = if (axis in zeroToOneAxes) 0f else -1f
|
||||
builder.addMotionRange(axis, InputDevice.SOURCE_JOYSTICK, min, 1f, 0f, 0f, 0f)
|
||||
}
|
||||
return builder.build().also {
|
||||
shadowOf(RuntimeEnvironment.getApplication().getSystemService(InputManager::class.java)).addInputDevice(it)
|
||||
|
||||
@@ -131,6 +131,50 @@ class ScrollTouchGesturesTest {
|
||||
assertEquals(listOf("move 400,300"), events)
|
||||
}
|
||||
|
||||
@Test fun tapsAndHoldsDoNotClickWhileClicksAreOff() {
|
||||
gestures.clicks = false
|
||||
touch(MotionEvent.ACTION_DOWN, 400f, 300f)
|
||||
advance(80)
|
||||
touch(MotionEvent.ACTION_UP, 400f, 300f)
|
||||
advance(100)
|
||||
touch(MotionEvent.ACTION_DOWN, 400f, 300f)
|
||||
advance(600)
|
||||
touch(MotionEvent.ACTION_UP, 402f, 301f)
|
||||
advance(100)
|
||||
assertEquals(listOf("move 400,300", "move 400,300"), events)
|
||||
}
|
||||
|
||||
@Test fun holdThenMoveScrollsWhileClicksAreOff() {
|
||||
gestures.clicks = false
|
||||
touch(MotionEvent.ACTION_DOWN, 400f, 800f)
|
||||
advance(600)
|
||||
touch(MotionEvent.ACTION_MOVE, 402f, 500f)
|
||||
advance(200)
|
||||
touch(MotionEvent.ACTION_UP, 402f, 500f)
|
||||
advance(100)
|
||||
assertEquals(300f, scrolledY, 0.01f)
|
||||
assertEquals(listOf("move 400,800"), events)
|
||||
}
|
||||
|
||||
@Test fun turningClicksOffReleasesAClickInFlight() {
|
||||
touch(MotionEvent.ACTION_DOWN, 400f, 300f)
|
||||
advance(80)
|
||||
touch(MotionEvent.ACTION_UP, 400f, 300f)
|
||||
gestures.clicks = false
|
||||
touch(MotionEvent.ACTION_DOWN, 400f, 300f)
|
||||
advance(80)
|
||||
touch(MotionEvent.ACTION_UP, 400f, 300f)
|
||||
advance(100)
|
||||
assertEquals(listOf("move 400,300", "left down", "left up", "move 400,300"), events)
|
||||
events.clear()
|
||||
gestures.clicks = true
|
||||
touch(MotionEvent.ACTION_DOWN, 400f, 300f)
|
||||
advance(80)
|
||||
touch(MotionEvent.ACTION_UP, 400f, 300f)
|
||||
advance(100)
|
||||
assertEquals(listOf("move 400,300", "left down", "left up"), events)
|
||||
}
|
||||
|
||||
@Test fun aSecondFingerDoesNotJumpTheScroll() {
|
||||
touch(MotionEvent.ACTION_DOWN, 400f, 900f)
|
||||
advance(100)
|
||||
|
||||
@@ -1,9 +1,58 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SecondScreenModeTest {
|
||||
@Test fun fallbackSelectionSurvivesRecreationAndRequestedDisplaySurvivesDisconnect() {
|
||||
var saved = 2
|
||||
SecondScreenDisplays.selection(saved, listOf(3), false) { saved = it }
|
||||
assertEquals(3, saved)
|
||||
assertEquals(3, SecondScreenDisplays.selection(saved, listOf(3), true))
|
||||
SecondScreenDisplays.selection(saved, listOf(2), true) { saved = it }
|
||||
assertEquals(3, saved)
|
||||
}
|
||||
|
||||
@Test fun keyboardFallsBackOnlyForADisconnectedRequestedDisplay() {
|
||||
val taken: (Int) -> Boolean = { it == 2 }
|
||||
val free: (Int) -> Boolean = { false }
|
||||
assertTrue(SecondScreenDisplays.keyboardOnPrimary(true, 2, listOf(3), taken = free))
|
||||
assertTrue(SecondScreenDisplays.keyboardOnPrimary(true, 2, listOf(2, 3), taken = taken))
|
||||
assertFalse(SecondScreenDisplays.keyboardOnPrimary(true, 2, listOf(2, 3), taken = free))
|
||||
assertFalse(SecondScreenDisplays.keyboardOnPrimary(false, 2, listOf(3), taken = taken))
|
||||
assertFalse(SecondScreenDisplays.keyboardOnPrimary(true, -1, listOf(3), taken = taken))
|
||||
}
|
||||
|
||||
@Test fun primaryFallbackRequiresVisibleActivity() {
|
||||
for (available in listOf(emptyList(), listOf(2))) {
|
||||
assertTrue(SecondScreenDisplays.keyboardOnPrimary(true, 2, available, true) { true })
|
||||
assertFalse(SecondScreenDisplays.keyboardOnPrimary(true, 2, available, false) { true })
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun keyboardRouteIncludesOccupiedDisplayFallbackOnlyWhenEnabled() {
|
||||
val fallback = SecondScreenDisplays.keyboardOnPrimary(true, 2, listOf(2)) { it == 2 }
|
||||
assertTrue(fallback)
|
||||
assertTrue(SecondScreenDisplays.routeKeyboard(true, true, false, false, fallback))
|
||||
assertFalse(SecondScreenDisplays.routeKeyboard(true, false, false, false, fallback))
|
||||
assertFalse(SecondScreenDisplays.routeKeyboard(false, true, false, false, fallback))
|
||||
assertFalse(SecondScreenDisplays.routeKeyboard(true, true, false, false, false))
|
||||
assertTrue(SecondScreenDisplays.routeKeyboard(true, true, true, false, false))
|
||||
assertTrue(SecondScreenDisplays.routeKeyboard(true, true, false, true, false))
|
||||
}
|
||||
|
||||
@Test fun selectedGameDisplayIsNotReplacedWhenItDisconnects() {
|
||||
assertEquals(2, SecondScreenDisplays.selection(2, listOf(3), true))
|
||||
assertEquals(2, SecondScreenDisplays.selection(2, emptyList(), true))
|
||||
assertEquals(2, SecondScreenDisplays.selection(2, listOf(3, 2), true))
|
||||
assertEquals(3, SecondScreenDisplays.selection(3, listOf(3), true))
|
||||
assertEquals(3, SecondScreenDisplays.selection(2, listOf(3), false))
|
||||
assertEquals(3, SecondScreenDisplays.selection(-1, listOf(3), true))
|
||||
assertEquals(-1, SecondScreenDisplays.selection(-1, emptyList(), false))
|
||||
}
|
||||
|
||||
@Test fun withNothingRememberedDeckPadsGetControlsAndOthersTheDashboard() {
|
||||
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening(null, deckPad = true, dashboard = true))
|
||||
assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening(null, deckPad = false, dashboard = true))
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.view.KeyEvent
|
||||
import android.view.WindowInsets
|
||||
import com.droiddeck.launcher.SessionActivity
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.util.ReflectionHelpers
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class SessionFieldKeyboardTest {
|
||||
private lateinit var activity: SessionActivity
|
||||
private lateinit var keyboard: KeyboardHost
|
||||
|
||||
@Before fun setUp() {
|
||||
activity = Robolectric.buildActivity(SessionActivity::class.java).get()
|
||||
keyboard = KeyboardHost(activity)
|
||||
ReflectionHelpers.setField(activity, "keyboard", keyboard)
|
||||
keyboard.onImeChanged = { visible ->
|
||||
ReflectionHelpers.callInstanceMethod<Any?>(activity, "onPrimaryImeChanged",
|
||||
ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, visible))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun guestDismissalClosesOnlyTheGuestOwnedKeyboard() {
|
||||
openFieldKeyboard()
|
||||
call("dismissFieldKeyboard")
|
||||
assertFalse(keyboard.shown)
|
||||
call("showPrimaryKeyboard")
|
||||
call("dismissFieldKeyboard")
|
||||
assertTrue(keyboard.shown)
|
||||
}
|
||||
|
||||
@Test fun pauseHideThenManualReopenSurvivesGuestDismissal() {
|
||||
openFieldKeyboard()
|
||||
call("hidePrimaryKeyboard")
|
||||
assertFalse(keyboard.shown)
|
||||
call("showPrimaryKeyboard")
|
||||
call("dismissFieldKeyboard")
|
||||
assertTrue(keyboard.shown)
|
||||
openFieldKeyboard()
|
||||
call("dismissFieldKeyboard")
|
||||
assertFalse(keyboard.shown)
|
||||
}
|
||||
|
||||
@Test fun manualToggleAndPcKeyboardRelinquishGuestOwnership() {
|
||||
openFieldKeyboard()
|
||||
call("togglePrimaryKeyboard")
|
||||
call("togglePrimaryKeyboard")
|
||||
call("dismissFieldKeyboard")
|
||||
assertTrue(keyboard.shown)
|
||||
openFieldKeyboard()
|
||||
call("togglePcKeyboard")
|
||||
call("showPrimaryKeyboard")
|
||||
call("dismissFieldKeyboard")
|
||||
assertTrue(keyboard.shown)
|
||||
}
|
||||
|
||||
@Test fun pendingGuestRequestWaitsForFocusAndCanBeDismissed() {
|
||||
ReflectionHelpers.callInstanceMethod<Any?>(activity, "setGameOnBottom", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true))
|
||||
ReflectionHelpers.callInstanceMethod<Any?>(activity, "setSelectedSecondScreenDisplay", ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 2))
|
||||
ReflectionHelpers.callInstanceMethod<Any?>(activity, "setResumed", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true))
|
||||
call("openBottomKeyboard")
|
||||
ReflectionHelpers.callInstanceMethod<Any?>(activity, "retryFieldKeyboard", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, false))
|
||||
assertFalse(keyboard.shown)
|
||||
call("dismissFieldKeyboard")
|
||||
ReflectionHelpers.callInstanceMethod<Any?>(activity, "retryFieldKeyboard", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true))
|
||||
assertFalse(keyboard.shown)
|
||||
call("openBottomKeyboard")
|
||||
ReflectionHelpers.callInstanceMethod<Any?>(activity, "retryFieldKeyboard", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true))
|
||||
assertTrue(keyboard.shown)
|
||||
call("dismissFieldKeyboard")
|
||||
assertFalse(keyboard.shown)
|
||||
}
|
||||
|
||||
@Config(sdk = [33])
|
||||
@Test fun staleHiddenEventFromEarlierHideKeepsNewGuestOwnership() {
|
||||
call("showPrimaryKeyboard")
|
||||
ime(true)
|
||||
call("hidePrimaryKeyboard")
|
||||
requestFieldKeyboard()
|
||||
ime(false)
|
||||
assertTrue(owned())
|
||||
ime(true)
|
||||
call("dismissFieldKeyboard")
|
||||
assertFalse(keyboard.shown)
|
||||
}
|
||||
|
||||
@Config(sdk = [33])
|
||||
@Test fun hiddenEventAfterGuestKeyboardShowsClearsOwnership() {
|
||||
requestFieldKeyboard()
|
||||
ime(true)
|
||||
ime(false)
|
||||
assertFalse(owned())
|
||||
call("showPrimaryKeyboard")
|
||||
call("dismissFieldKeyboard")
|
||||
assertTrue(keyboard.shown)
|
||||
}
|
||||
|
||||
@Config(sdk = [33])
|
||||
@Test fun guestRequestWhileKeyboardAlreadyVisibleClearsOnRealDismissal() {
|
||||
call("showPrimaryKeyboard")
|
||||
ime(true)
|
||||
requestFieldKeyboard()
|
||||
assertTrue(owned())
|
||||
ime(false)
|
||||
assertFalse(owned())
|
||||
}
|
||||
|
||||
@Test fun backDismissalWithoutImeInsetsClearsOwnership() {
|
||||
requestFieldKeyboard()
|
||||
assertTrue(owned())
|
||||
val t = System.currentTimeMillis()
|
||||
keyboard.onKeyPreIme(KeyEvent.KEYCODE_BACK, KeyEvent(t, t, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK, 0))
|
||||
assertFalse(keyboard.shown)
|
||||
assertFalse(owned())
|
||||
}
|
||||
|
||||
@Test fun focusReturnSkipsPrimaryKeyboardWhenDestinationNoLongerPrimary() {
|
||||
setFlag("setGameOnBottom", true)
|
||||
selectDisplay(2)
|
||||
setFlag("setResumed", true)
|
||||
call("openBottomKeyboard")
|
||||
retry(false)
|
||||
setFlag("setGameOnBottom", false)
|
||||
retry(true)
|
||||
assertFalse(keyboard.shown)
|
||||
assertFalse(owned())
|
||||
assertFalse(ReflectionHelpers.getField<Boolean>(activity, "pendingFieldKeyboard"))
|
||||
}
|
||||
|
||||
private fun requestFieldKeyboard() {
|
||||
setFlag("setGameOnBottom", true)
|
||||
selectDisplay(2)
|
||||
setFlag("setResumed", true)
|
||||
call("openBottomKeyboard")
|
||||
retry(true)
|
||||
assertTrue(keyboard.shown)
|
||||
}
|
||||
|
||||
private fun ime(visible: Boolean) {
|
||||
keyboard.dispatchApplyWindowInsets(WindowInsets.Builder().setVisible(WindowInsets.Type.ime(), visible).build())
|
||||
}
|
||||
|
||||
private fun owned() = ReflectionHelpers.getField<Boolean>(activity, "fieldKeyboardOnPrimary")
|
||||
|
||||
private fun selectDisplay(id: Int) = ReflectionHelpers.callInstanceMethod<Any?>(activity, "setSelectedSecondScreenDisplay",
|
||||
ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, id))
|
||||
|
||||
private fun retry(focus: Boolean) = ReflectionHelpers.callInstanceMethod<Any?>(activity, "retryFieldKeyboard",
|
||||
ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, focus))
|
||||
|
||||
private fun setFlag(name: String, value: Boolean) = ReflectionHelpers.callInstanceMethod<Any?>(activity, name,
|
||||
ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, value))
|
||||
|
||||
private fun openFieldKeyboard() {
|
||||
ReflectionHelpers.setField(activity, "fieldKeyboardOnPrimary", true)
|
||||
keyboard.show()
|
||||
}
|
||||
|
||||
private fun call(name: String) = ReflectionHelpers.callInstanceMethod<Any?>(activity, name)
|
||||
}
|
||||
@@ -32,9 +32,10 @@ class ShortcutsRelayTest {
|
||||
private fun choose(value: String?) =
|
||||
Settings.Secure.putString(context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, value)
|
||||
|
||||
private fun installCompanion() {
|
||||
@Suppress("DEPRECATION")
|
||||
private fun installCompanion(version: Int = Relay.VERSION) {
|
||||
val app = ApplicationInfo().apply { packageName = Relay.PACKAGE; uid = companionUid }
|
||||
shadowOf(context.packageManager).installPackage(PackageInfo().apply { packageName = Relay.PACKAGE; applicationInfo = app })
|
||||
shadowOf(context.packageManager).installPackage(PackageInfo().apply { packageName = Relay.PACKAGE; applicationInfo = app; versionCode = version })
|
||||
shadowOf(context.packageManager).setPackagesForUid(companionUid, Relay.PACKAGE)
|
||||
}
|
||||
|
||||
@@ -84,6 +85,26 @@ class ShortcutsRelayTest {
|
||||
assertEquals(0, config(binder, companionUid))
|
||||
}
|
||||
|
||||
@Test fun anOldCompanionIsOfferedAsAnUpdate() {
|
||||
installCompanion(version = 1)
|
||||
choose("${Relay.PACKAGE}/${Relay.SERVICE}")
|
||||
assertTrue(SteamIntegration.shortcutsEnabled(context))
|
||||
assertFalse(SteamIntegration.read(context).shortcuts)
|
||||
installCompanion()
|
||||
assertTrue(SteamIntegration.read(context).shortcuts)
|
||||
}
|
||||
|
||||
@Test fun droidDeckHoldsTheRelayOnlyWhileAScreenIsStarted() {
|
||||
installCompanion()
|
||||
ShortcutsRelay.Holder.install(context)
|
||||
val activity = Robolectric.buildActivity(android.app.Activity::class.java).create()
|
||||
activity.start()
|
||||
assertEquals(1, shadowOf(context).boundServiceConnections.size)
|
||||
activity.stop()
|
||||
shadowOf(android.os.Looper.getMainLooper()).idleFor(java.time.Duration.ofSeconds(2))
|
||||
assertEquals(0, shadowOf(context).boundServiceConnections.size)
|
||||
}
|
||||
|
||||
@Test fun windowSnapshotsSurviveTheTrip() {
|
||||
val sent = mapOf(2 to listOf(Relay.Window(7, 1, 3, Rect(0, 0, 1080, 1240), "guest.app"), Relay.Window(8, 2, 1, Rect(1, 2, 3, 4), null)))
|
||||
val got = Relay.decode(Relay.encode(sent))
|
||||
|
||||
@@ -262,6 +262,75 @@ class TouchpadGesturesTest {
|
||||
assertFalse(events.contains("left down"))
|
||||
}
|
||||
|
||||
@Test fun tapsDoNotClickWhileClicksAreOff() {
|
||||
touchpad.clicks = false
|
||||
tap()
|
||||
advance(20)
|
||||
tap()
|
||||
advance(TouchTiming.HOLD_MS + 100)
|
||||
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
|
||||
advance(TouchTiming.HOLD_MS + 100)
|
||||
touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f))
|
||||
advance(200)
|
||||
assertFalse(events.any { it.endsWith(" down") })
|
||||
}
|
||||
|
||||
@Test fun twoFingerTapDoesNotClickWhileClicksAreOff() {
|
||||
touchpad.clicks = false
|
||||
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
|
||||
advance(10)
|
||||
touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (400f to 300f), 2 to (600f to 310f))
|
||||
advance(60)
|
||||
touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (400f to 300f), 2 to (600f to 310f))
|
||||
advance(10)
|
||||
touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f))
|
||||
advance(200)
|
||||
assertFalse(events.any { it.endsWith(" down") })
|
||||
}
|
||||
|
||||
@Test fun pointerStillMovesWhileClicksAreOff() {
|
||||
touchpad.clicks = false
|
||||
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
|
||||
advance(10)
|
||||
touch(MotionEvent.ACTION_MOVE, 0, 1 to (440f to 300f))
|
||||
advance(10)
|
||||
touch(MotionEvent.ACTION_UP, 0, 1 to (440f to 300f))
|
||||
assertTrue(events.contains("move"))
|
||||
assertTrue(touchpad.x > 960f)
|
||||
assertFalse(events.any { it.endsWith(" down") })
|
||||
}
|
||||
|
||||
@Test fun tapsClickAgainOnceClicksAreBackOn() {
|
||||
touchpad.clicks = false
|
||||
tap()
|
||||
advance(400)
|
||||
touchpad.clicks = true
|
||||
tap()
|
||||
advance(200)
|
||||
assertEquals(listOf("left down", "left up"), events)
|
||||
}
|
||||
|
||||
@Test fun aTapWhileClicksWereOffDoesNotStartADragOnceTheyAreBackOn() {
|
||||
touchpad.clicks = false
|
||||
tap()
|
||||
advance(20)
|
||||
touchpad.clicks = true
|
||||
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
|
||||
assertEquals(emptyList<String>(), events)
|
||||
advance(80)
|
||||
touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f))
|
||||
advance(200)
|
||||
assertEquals(listOf("left down", "left up"), events)
|
||||
}
|
||||
|
||||
@Test fun doubleTapStillDragsWhileClicksStayOn() {
|
||||
tap()
|
||||
advance(20)
|
||||
touchpad.clicks = true
|
||||
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
|
||||
assertEquals(listOf("left down", "left up", "left down"), events)
|
||||
}
|
||||
|
||||
private fun tap() {
|
||||
touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f))
|
||||
advance(80)
|
||||
|
||||
@@ -112,6 +112,40 @@ class BwrapSpawnerPlanTest {
|
||||
.put("cwd", "/app")
|
||||
.put("ops", JSONArray().apply { ops.forEach { put(it) } })
|
||||
|
||||
@Test fun desktopSandboxesGetTheRuntimeGpuWithoutReplacingExplicitChoices() {
|
||||
val lib = File(runtime, "usr/lib/aarch64-linux-gnu/libvulkan_freedreno.so")
|
||||
lib.parentFile!!.mkdirs()
|
||||
lib.writeText("")
|
||||
val root = File(dir, "root").apply { mkdirs() }
|
||||
for (session in listOf(emptyMap(), mapOf("BL_DESKTOP" to "1"),
|
||||
mapOf("BL_DESKTOP" to "1", "GALLIUM_DRIVER" to "zink", "MESA_LOADER_DRIVER_OVERRIDE" to "zink"))) {
|
||||
val env = session.toMutableMap()
|
||||
val binds = BwrapSpawner.gpu(runtime.path, root, env, true)!!
|
||||
assertTrue(binds.any { it.host == lib.canonicalPath && it.guest == "/run/droiddeck-gpu/libvulkan_freedreno.so" })
|
||||
assertEquals("/run/droiddeck-gpu/freedreno_icd.json", env["VK_DRIVER_FILES"])
|
||||
assertEquals("zink", env["GALLIUM_DRIVER"])
|
||||
assertEquals(session["BL_DESKTOP"], env["BL_DESKTOP"])
|
||||
}
|
||||
for (choice in listOf(mapOf("VK_DRIVER_FILES" to "/custom/icd.json"),
|
||||
mapOf("VK_ICD_FILENAMES" to ""), mapOf("LIBGL_ALWAYS_SOFTWARE" to "1"))) {
|
||||
val env = (choice + ("BL_DESKTOP" to "1")).toMutableMap()
|
||||
val original = env.toMap()
|
||||
assertEquals(null, BwrapSpawner.gpu(runtime.path, root, env, true))
|
||||
assertEquals(original, env)
|
||||
}
|
||||
val env = mutableMapOf("BL_DESKTOP" to "1", "GALLIUM_DRIVER" to "llvmpipe")
|
||||
assertTrue(BwrapSpawner.gpu(runtime.path, root, env, true)!!.isNotEmpty())
|
||||
assertEquals("llvmpipe", env["GALLIUM_DRIVER"])
|
||||
val gamescope = mutableMapOf("BL_DESKTOP" to "1", "LIBGL_ALWAYS_SOFTWARE" to "1", "GAMESCOPE_WAYLAND_DISPLAY" to "gamescope-0")
|
||||
assertTrue(BwrapSpawner.gpu(runtime.path, root, gamescope, true)!!.isNotEmpty())
|
||||
val unavailable = mutableMapOf("BL_DESKTOP" to "1")
|
||||
assertEquals(null, BwrapSpawner.gpu(runtime.path, root, unavailable, false))
|
||||
assertEquals(mapOf("BL_DESKTOP" to "1"), unavailable)
|
||||
assertTrue(lib.delete())
|
||||
assertEquals(null, BwrapSpawner.gpu(runtime.path, root, unavailable, true))
|
||||
assertEquals(mapOf("BL_DESKTOP" to "1"), unavailable)
|
||||
}
|
||||
|
||||
@Test fun buildsTheTreeFlatpakAsksFor() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val info = Base64.encodeToString("[Application]\nname=org.example.Game\n".toByteArray(), Base64.NO_WRAP)
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SessionRestartNoteTest {
|
||||
private val started = 1_731_100_000_000L
|
||||
|
||||
@Test fun aBootAfterTheSessionBeganIsReportedAsARestart() {
|
||||
val note = SessionArtifacts.restartNote(started, started + 20 * 60_000L)
|
||||
assertNotNull(note)
|
||||
assertTrue(note!!.startsWith("The device itself probably restarted"))
|
||||
}
|
||||
|
||||
@Test fun aBootBeforeTheSessionBeganMeansOnlyTheAppEnded() {
|
||||
val note = SessionArtifacts.restartNote(started, started - 3 * 3_600_000L)
|
||||
assertTrue(note!!.startsWith("The device does not appear to have restarted"))
|
||||
}
|
||||
|
||||
@Test fun clockCorrectionsWithinAMinuteAreNotARestart() {
|
||||
val note = SessionArtifacts.restartNote(started, started + 30_000L)
|
||||
assertTrue(note!!.startsWith("The device does not appear to have restarted"))
|
||||
}
|
||||
|
||||
@Test fun aFolderWithoutAStartTimeSaysNothing() {
|
||||
assertNull(SessionArtifacts.restartNote(0L, started))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34], application = android.app.Application::class)
|
||||
class StoreLibraryCacheTest {
|
||||
@Test
|
||||
fun listsRoundTripWithTheirStoreAndExtras() {
|
||||
val games = listOf(
|
||||
CatalogItem(
|
||||
Store.UBISOFT, "4553", "Far Cry 3 Blood Dragon", "https://img/wide.jpg", tallImageUrl = "https://img/tall.jpg",
|
||||
logoUrl = "https://img/logo.png", owned = true, sizeBytes = 2_000_000L, extra = mapOf("productId" to "205", "spaceId" to "abc"),
|
||||
subscription = true, includedWith = "Ubisoft+",
|
||||
),
|
||||
CatalogItem(Store.UBISOFT, "1", "No art", null),
|
||||
)
|
||||
assertEquals(games, StoreLibraryCache.decode(Store.UBISOFT, StoreLibraryCache.encode(games)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anEmptyLibraryStaysEmptyRatherThanUnknown() {
|
||||
assertEquals(emptyList<CatalogItem>(), StoreLibraryCache.decode(Store.ROCKSTAR, StoreLibraryCache.encode(emptyList())))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.view.MotionEvent
|
||||
import com.droiddeck.launcher.input.InputControl
|
||||
import com.droiddeck.launcher.input.InputSurfaceElement
|
||||
import com.droiddeck.launcher.input.OnScreenLayout
|
||||
import com.droiddeck.launcher.input.SavedInputLayout
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34], manifest = Config.NONE)
|
||||
class InputSurfaceEditorViewTest {
|
||||
private val context get() = RuntimeEnvironment.getApplication()
|
||||
private val layout = SavedInputLayout("custom", "Custom", listOf(InputSurfaceElement(InputControl.A, .1f, .2f, .2f, .2f)), aspect = 2f)
|
||||
|
||||
private fun view() = InputSurfaceEditorView(context).apply {
|
||||
layout(0, 0, 1000, 1000)
|
||||
sourceLayout = layout
|
||||
aspect = layout.aspect
|
||||
elements = layout.elements
|
||||
snap = false
|
||||
}
|
||||
|
||||
private fun center() = OnScreenLayout.editorElements(context, layout, 1000, 1000).first().let { (it.x + it.width / 2) * 1000 to (it.y + it.height / 2) * 1000 }
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
private fun InputSurfaceEditorView.rendered() = javaClass.getDeclaredField("visibleElements").also { it.isAccessible = true }.get(this) as List<InputSurfaceElement>
|
||||
|
||||
private fun InputSurfaceEditorView.touch(action: Int, x: Float, y: Float) {
|
||||
MotionEvent.obtain(0, 10, action, x, y, 0).also { onTouchEvent(it); it.recycle() }
|
||||
}
|
||||
|
||||
@Test fun editingStartsInTheDisplayedFrame() {
|
||||
val view = view()
|
||||
var started: Pair<List<InputSurfaceElement>, Float>? = null
|
||||
view.onBeginEdit = { elements, aspect -> started = elements to aspect }
|
||||
val (x, y) = center()
|
||||
view.touch(MotionEvent.ACTION_DOWN, x, y)
|
||||
view.touch(MotionEvent.ACTION_MOVE, x + 100f, y + 50f)
|
||||
val (elements, aspect) = requireNotNull(started)
|
||||
assertEquals(1f, aspect, .0001f)
|
||||
assertEquals(OnScreenLayout.editorElements(context, layout, 1000, 1000), elements)
|
||||
}
|
||||
|
||||
@Test fun undoRestoresTheSavedFrameForHitTesting() {
|
||||
val view = view()
|
||||
var selection: String? = null
|
||||
view.onSelect = { selection = it }
|
||||
view.elements = layout.elements.map { it.copy(x = .5f) }
|
||||
view.elements = layout.elements
|
||||
val (x, y) = center()
|
||||
view.touch(MotionEvent.ACTION_DOWN, x, y)
|
||||
assertEquals("legacy:a", selection)
|
||||
}
|
||||
|
||||
@Test fun editorFramePreservesAddedAndRemovedDraftElements() {
|
||||
val added = layout.elements + InputSurfaceElement(InputControl.B, .6f, .2f, .2f, .2f, id = "added")
|
||||
val removed = layout.copy(elements = emptyList())
|
||||
assertEquals(added, OnScreenLayout.editorFrame(layout.copy(elements = added), added))
|
||||
assertEquals(emptyList<InputSurfaceElement>(), OnScreenLayout.editorFrame(removed, emptyList()))
|
||||
}
|
||||
|
||||
@Test fun savedAspectRemainsStableForRenamesAndResizes() {
|
||||
val view = view()
|
||||
val renamed = layout.elements.map { it.copy(name = "Renamed") }
|
||||
view.elements = renamed
|
||||
view.aspect = 2f
|
||||
assertEquals(OnScreenLayout.editorElements(context, layout.copy(elements = renamed, aspect = 2f), 1000, 1000), view.rendered())
|
||||
view.layout(0, 0, 800, 1000)
|
||||
assertEquals(OnScreenLayout.editorElements(context, layout.copy(elements = renamed, aspect = 2f), 800, 1000), view.rendered())
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,12 @@ retry delay, up to five minutes. After game exit, speculative launcher readback
|
||||
until the session is under any explicit RAM cap, pressure has subsided, and available RAM
|
||||
can cover twice the launcher's swap while leaving the headroom reserve. Normal demand paging
|
||||
continues while readback is deferred; Steam does not have to wait for the monitor to recover.
|
||||
The same readback runs while the game is still running once the client has been in front of it
|
||||
for five seconds (a game stuck on a black screen and left through Steam, or a long stay in the
|
||||
Steam menu), under the same memory checks and only without an explicit RAM cap. Missing or
|
||||
unreadable focus data never counts as the client in front. Demand paging
|
||||
alone left the Steam library and menus blank for about half a minute in that case. The
|
||||
client is compressed again 20 seconds after the game is back in front.
|
||||
Missing memory counters disable automatic pressure reclaim and speculative readback. Missing
|
||||
PSI alone still permits the `MemAvailable` fallback. No root settings, swap sizes, compression
|
||||
algorithms, Android process priorities or game-specific settings are changed.
|
||||
@@ -58,7 +64,7 @@ and the RAM cap are unaffected.
|
||||
The session request runs when real headroom falls below a quarter of RAM (bounded to
|
||||
768–2560 MiB), or below one and a half times that with at least 1% `some` or `full avg10`
|
||||
memory stall. Real headroom subtracts positive growth in KGSL allocation, `Unevictable`, and
|
||||
`Shmem` from `MemAvailable`; a rapid fall also qualifies near twice the headroom. The monitor
|
||||
`Shmem` from `MemAvailable`; a rapid fall also qualifies below twice the headroom or two fifths of RAM, whichever is larger (a 15 GB Thor Max was killed with 5.3 GB still available while memory fell about 400 MB per tick). The monitor
|
||||
may first request page-out of idle Steam and hidden launchers, subject to the Performance
|
||||
setting and client reclaim limits. When both qualify, both requests are sent before waiting
|
||||
for either to complete, so a slow launcher acknowledgement does not delay the game request. Until the client
|
||||
|
||||
@@ -64,6 +64,17 @@ inherit those routes. Managed shortcuts are replaced; user-created shortcuts and
|
||||
unreadable shortcut files are preserved. Both routes use the existing ARM64 Proton
|
||||
registration.
|
||||
|
||||
## Adopting shared library folders
|
||||
|
||||
At every session start, `droiddeck-steam-library` looks through `steamapps/common` of each
|
||||
added library for non-empty folders no manifest names. A folder whose name is the
|
||||
`config.installdir` of exactly one playable app in `appcache/appinfo.vdf` (the `game`
|
||||
type wins over a demo; tools, DLC and ambiguous names are skipped) gets an
|
||||
`appmanifest_<id>.acf` with `Universe=1`, `StateFlags=4` and no build, so Steam verifies
|
||||
the existing files and downloads only what differs. Existing manifests are never
|
||||
rewritten, an app installed in another library is skipped, and only the added library is
|
||||
written to. Ownership is not read before the client runs; Steam enforces the license.
|
||||
|
||||
## Launcher artwork
|
||||
|
||||
The installed Steam game scan lists each game's `appcache/librarycache/<appid>`
|
||||
|
||||
@@ -9,9 +9,9 @@ android {
|
||||
defaultConfig {
|
||||
applicationId 'com.droiddeck.shortcuts'
|
||||
minSdkVersion 26
|
||||
targetSdkVersion 28
|
||||
versionCode 1
|
||||
versionName '1'
|
||||
targetSdkVersion 34
|
||||
versionCode 3
|
||||
versionName '3'
|
||||
}
|
||||
|
||||
sourceSets.main.java.srcDir('src/protocol/java')
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<queries>
|
||||
<intent>
|
||||
<action android:name="com.droiddeck.shortcuts.RELAY" />
|
||||
</intent>
|
||||
</queries>
|
||||
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:icon="@android:drawable/sym_def_app_icon"
|
||||
|
||||
@@ -71,7 +71,8 @@ public class ShortcutsService extends AccessibilityService {
|
||||
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
|
||||
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
|
||||
filter.addDataScheme("package");
|
||||
registerReceiver(packages, filter);
|
||||
if (Build.VERSION.SDK_INT >= 33) registerReceiver(packages, filter, Context.RECEIVER_NOT_EXPORTED);
|
||||
else registerReceiver(packages, filter);
|
||||
receiving = true;
|
||||
bindAll();
|
||||
}
|
||||
@@ -88,7 +89,8 @@ public class ShortcutsService extends AccessibilityService {
|
||||
if (linked) continue;
|
||||
Link link = new Link(component);
|
||||
try {
|
||||
if (bindService(new Intent(Relay.ACTION).setComponent(component), link, Context.BIND_AUTO_CREATE)) links.add(link);
|
||||
// No BIND_AUTO_CREATE: frontends read a running player as an open game, so the relay app decides when it runs.
|
||||
if (bindService(new Intent(Relay.ACTION).setComponent(component), link, 0)) links.add(link);
|
||||
else unbindService(link);
|
||||
} catch (RuntimeException ignored) {
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ public final class Relay {
|
||||
public static final String SERVICE = PACKAGE + ".ShortcutsService";
|
||||
public static final String ACTION = "com.droiddeck.shortcuts.RELAY";
|
||||
public static final String DESCRIPTOR = "com.droiddeck.shortcuts.Relay";
|
||||
public static final int VERSION = 3;
|
||||
|
||||
public static final int CONFIG = 1;
|
||||
public static final int KEY = 2;
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
diff --git a/ThunkLibs/include/common/X11Manager.h b/ThunkLibs/include/common/X11Manager.h
|
||||
index a0b1f9e..3843a5f 100644
|
||||
--- a/ThunkLibs/include/common/X11Manager.h
|
||||
+++ b/ThunkLibs/include/common/X11Manager.h
|
||||
@@ -24,7 +24,7 @@ using guest_size_t = size_t;
|
||||
* guest display/connection.
|
||||
*/
|
||||
struct X11Manager {
|
||||
- std::mutex mutex;
|
||||
+ std::recursive_mutex mutex;
|
||||
|
||||
// Maps guest connection to intermediary host connection
|
||||
std::unordered_map<xcb_connection_t*, xcb_connection_t*> connections;
|
||||
@@ -68,18 +68,25 @@ struct X11Manager {
|
||||
return it->second;
|
||||
}
|
||||
|
||||
+ _XDisplay* FindGuestDisplay(const _XDisplay* from) {
|
||||
+ std::unique_lock lock(mutex);
|
||||
+ for (auto& [guest, host] : displays) {
|
||||
+ if (host == from) {
|
||||
+ return guest;
|
||||
+ }
|
||||
+ }
|
||||
+ return nullptr;
|
||||
+ }
|
||||
+
|
||||
guest_layout<_XDisplay*> HostToGuestDisplay(const _XDisplay* from) {
|
||||
if (from == nullptr) {
|
||||
return {.data = 0};
|
||||
}
|
||||
|
||||
- std::unique_lock lock(mutex);
|
||||
- for (auto& [guest, host] : displays) {
|
||||
- if (host == from) {
|
||||
- guest_layout<_XDisplay*> ret;
|
||||
- ret.data = reinterpret_cast<uintptr_t>(guest);
|
||||
- return ret;
|
||||
- }
|
||||
+ if (auto guest = FindGuestDisplay(from)) {
|
||||
+ guest_layout<_XDisplay*> ret;
|
||||
+ ret.data = reinterpret_cast<uintptr_t>(guest);
|
||||
+ return ret;
|
||||
}
|
||||
|
||||
fprintf(stderr, "ERROR: Could not map host display %p back to guest\n", from);
|
||||
@@ -106,6 +113,21 @@ struct X11Manager {
|
||||
return func(Name);
|
||||
}
|
||||
|
||||
+ static XErrorHandler HostXSetErrorHandler(XErrorHandler Handler) {
|
||||
+ static auto func = reinterpret_cast<decltype(&XSetErrorHandler)>(dlsym(GetLibX11(), "XSetErrorHandler"));
|
||||
+ return func(Handler);
|
||||
+ }
|
||||
+
|
||||
+ static void HostXLockDisplay(Display* a) {
|
||||
+ static auto func = reinterpret_cast<decltype(&XLockDisplay)>(dlsym(GetLibX11(), "XLockDisplay"));
|
||||
+ func(a);
|
||||
+ }
|
||||
+
|
||||
+ static void HostXUnlockDisplay(Display* a) {
|
||||
+ static auto func = reinterpret_cast<decltype(&XUnlockDisplay)>(dlsym(GetLibX11(), "XUnlockDisplay"));
|
||||
+ func(a);
|
||||
+ }
|
||||
+
|
||||
static XVisualInfo* HostXGetVisualInfo(Display* a, long b, XVisualInfo* c, int* d) {
|
||||
static auto func = reinterpret_cast<decltype(&XGetVisualInfo)>(dlsym(GetLibX11(), "XGetVisualInfo"));
|
||||
return func(a, b, c, d);
|
||||
@@ -114,6 +136,7 @@ struct X11Manager {
|
||||
// NOTE: Struct pointers are replaced by void* to avoid involving data layout conversion here.
|
||||
int (*GuestXSync)(void*, int) = nullptr;
|
||||
void* (*GuestXGetVisualInfo)(void*, guest_long, void*, int*) = nullptr;
|
||||
+ int (*GuestXErrorForward)(void*, guest_long, int, int, int) = nullptr;
|
||||
|
||||
// XDisplayString internally just reads data from _XDisplay's internal struct definition.
|
||||
// This breaks when data layout is different, so allow reading from a guest context instead.
|
||||
diff --git a/ThunkLibs/libGL/libGL_Guest.cpp b/ThunkLibs/libGL/libGL_Guest.cpp
|
||||
index b0eea5b..01eb801 100644
|
||||
--- a/ThunkLibs/libGL/libGL_Guest.cpp
|
||||
+++ b/ThunkLibs/libGL/libGL_Guest.cpp
|
||||
@@ -28,6 +28,8 @@ $end_info$
|
||||
|
||||
#include "thunkgen_guest_libGL.inl"
|
||||
|
||||
+#include <X11/Xlibint.h>
|
||||
+
|
||||
typedef void voidFunc();
|
||||
|
||||
// Maps OpenGL API function names to the address of a guest function which is
|
||||
@@ -79,11 +81,26 @@ static void* malloc_wrapper(size_t size) {
|
||||
return malloc(size);
|
||||
}
|
||||
|
||||
+static int ForwardXError(Display* display, long resourceid, int error_code, int request_code, int minor_code) {
|
||||
+ xError error {};
|
||||
+ error.type = X_Error;
|
||||
+ error.errorCode = error_code;
|
||||
+ error.resourceID = resourceid;
|
||||
+ error.majorCode = request_code;
|
||||
+ error.minorCode = minor_code;
|
||||
+ LockDisplay(display);
|
||||
+ error.sequenceNumber = display->request;
|
||||
+ int result = _XError(display, &error);
|
||||
+ UnlockDisplay(display);
|
||||
+ return result;
|
||||
+}
|
||||
+
|
||||
static void OnInit() {
|
||||
fexfn_pack_GL_SetGuestMalloc((uintptr_t)malloc_wrapper, (uintptr_t)CallbackUnpack<decltype(malloc_wrapper)>::Unpack);
|
||||
fexfn_pack_GL_SetGuestXSync((uintptr_t)XSync, (uintptr_t)CallbackUnpack<decltype(XSync)>::Unpack);
|
||||
fexfn_pack_GL_SetGuestXGetVisualInfo((uintptr_t)XGetVisualInfo, (uintptr_t)CallbackUnpack<decltype(XGetVisualInfo)>::Unpack);
|
||||
fexfn_pack_GL_SetGuestXDisplayString((uintptr_t)XDisplayString, (uintptr_t)CallbackUnpack<decltype(XDisplayString)>::Unpack);
|
||||
+ fexfn_pack_GL_SetGuestXErrorForward((uintptr_t)ForwardXError, (uintptr_t)CallbackUnpack<decltype(ForwardXError)>::Unpack);
|
||||
}
|
||||
|
||||
// libGL.so must pull in libX11.so as a dependency. Referencing some libX11
|
||||
diff --git a/ThunkLibs/libGL/libGL_Host.cpp b/ThunkLibs/libGL/libGL_Host.cpp
|
||||
index dd3cec4..84efe41 100644
|
||||
--- a/ThunkLibs/libGL/libGL_Host.cpp
|
||||
+++ b/ThunkLibs/libGL/libGL_Host.cpp
|
||||
@@ -66,6 +66,28 @@ static void fexfn_impl_libGL_GL_SetGuestXDisplayString(uintptr_t GuestTarget, ui
|
||||
MakeHostTrampolineForGuestFunctionAt(GuestTarget, GuestUnpacker, &x11_manager.GuestXDisplayString);
|
||||
}
|
||||
|
||||
+static XErrorHandler HostPreviousXErrorHandler = nullptr;
|
||||
+
|
||||
+static int HostXErrorHandler(Display* HostDisplay, XErrorEvent* Event) {
|
||||
+ auto GuestDisplay = x11_manager.FindGuestDisplay(HostDisplay);
|
||||
+ if (!GuestDisplay || !x11_manager.GuestXErrorForward) {
|
||||
+ return HostPreviousXErrorHandler ? HostPreviousXErrorHandler(HostDisplay, Event) : 0;
|
||||
+ }
|
||||
+ x11_manager.HostXUnlockDisplay(HostDisplay);
|
||||
+ int Result = x11_manager.GuestXErrorForward(GuestDisplay, static_cast<guest_long>(Event->resourceid), Event->error_code,
|
||||
+ Event->request_code, Event->minor_code);
|
||||
+ x11_manager.HostXLockDisplay(HostDisplay);
|
||||
+ return Result;
|
||||
+}
|
||||
+
|
||||
+static void fexfn_impl_libGL_GL_SetGuestXErrorForward(uintptr_t GuestTarget, uintptr_t GuestUnpacker) {
|
||||
+ MakeHostTrampolineForGuestFunctionAt(GuestTarget, GuestUnpacker, &x11_manager.GuestXErrorForward);
|
||||
+ auto Previous = x11_manager.HostXSetErrorHandler(HostXErrorHandler);
|
||||
+ if (Previous != HostXErrorHandler) {
|
||||
+ HostPreviousXErrorHandler = Previous;
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
#include "thunkgen_host_libGL.inl"
|
||||
|
||||
auto fexfn_impl_libGL_glXGetProcAddress(const GLubyte* name) -> void (*)() {
|
||||
diff --git a/ThunkLibs/libGL/libGL_interface.cpp b/ThunkLibs/libGL/libGL_interface.cpp
|
||||
index 04a2d2b..b769cda 100644
|
||||
--- a/ThunkLibs/libGL/libGL_interface.cpp
|
||||
+++ b/ThunkLibs/libGL/libGL_interface.cpp
|
||||
@@ -26,6 +26,7 @@ void GL_SetGuestMalloc(uintptr_t, uintptr_t);
|
||||
void GL_SetGuestXSync(uintptr_t, uintptr_t);
|
||||
void GL_SetGuestXGetVisualInfo(uintptr_t, uintptr_t);
|
||||
void GL_SetGuestXDisplayString(uintptr_t, uintptr_t);
|
||||
+void GL_SetGuestXErrorForward(uintptr_t, uintptr_t);
|
||||
template<>
|
||||
struct fex_gen_config<GL_SetGuestMalloc> : fexgen::custom_guest_entrypoint, fexgen::custom_host_impl {};
|
||||
template<>
|
||||
@@ -34,6 +35,8 @@ template<>
|
||||
struct fex_gen_config<GL_SetGuestXGetVisualInfo> : fexgen::custom_guest_entrypoint, fexgen::custom_host_impl {};
|
||||
template<>
|
||||
struct fex_gen_config<GL_SetGuestXDisplayString> : fexgen::custom_guest_entrypoint, fexgen::custom_host_impl {};
|
||||
+template<>
|
||||
+struct fex_gen_config<GL_SetGuestXErrorForward> : fexgen::custom_guest_entrypoint, fexgen::custom_host_impl {};
|
||||
|
||||
template<typename>
|
||||
struct fex_gen_type {};
|
||||
@@ -125,9 +125,8 @@ if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then
|
||||
chmod 755 /run/droiddeck/kwin/kwin_wayland
|
||||
export PATH=/run/droiddeck/kwin:$PATH
|
||||
fi
|
||||
if /usr/local/bin/droiddeck-pipewire start; then
|
||||
eval "$(/usr/local/bin/droiddeck-pipewire env)"
|
||||
else
|
||||
# Plasma uses the rootfs libpipewire; the bundle's module and plugin paths leave it without a shell.
|
||||
if ! /usr/local/bin/droiddeck-pipewire start; then
|
||||
echo "== pipewire: not running; screen capture has no picture"
|
||||
fi
|
||||
echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"
|
||||
|
||||
@@ -391,18 +391,26 @@ class FocusWatcher(threading.Thread):
|
||||
x.close()
|
||||
except (OSError, AgentError) as e:
|
||||
log("focus snapshot failed: %s" % e)
|
||||
self.publish({})
|
||||
time.sleep(2)
|
||||
continue
|
||||
if tag_game_windows(snap):
|
||||
self.changed.set()
|
||||
continue
|
||||
body = {k: v for k, v in snap.items() if k != "t"}
|
||||
if body == self.last:
|
||||
continue
|
||||
self.last = body
|
||||
self.seq += 1
|
||||
snap["seq"] = self.seq
|
||||
write_json(self.path, snap)
|
||||
self.publish(snap)
|
||||
|
||||
def publish(self, snap):
|
||||
body = {k: v for k, v in snap.items() if k != "t"}
|
||||
if body == self.last:
|
||||
return
|
||||
try:
|
||||
write_json(self.path, dict(snap, seq=self.seq + 1))
|
||||
except OSError as e:
|
||||
log("focus publication failed: %s" % e)
|
||||
self.changed.set()
|
||||
return
|
||||
self.seq += 1
|
||||
self.last = body
|
||||
|
||||
def listen(self):
|
||||
while True:
|
||||
|
||||
@@ -67,7 +67,25 @@ def place_uri(uri):
|
||||
return uri
|
||||
|
||||
|
||||
def update_places(path, libraries):
|
||||
def removable_volumes():
|
||||
listing = os.environ.get("BL_DESKTOP_VOLUMES")
|
||||
if not listing:
|
||||
return {}
|
||||
volumes = {}
|
||||
for entry in json.loads(Path(listing).read_text()):
|
||||
path = Path(entry["path"])
|
||||
if not path.is_absolute():
|
||||
continue
|
||||
try:
|
||||
with os.scandir(path):
|
||||
pass
|
||||
except OSError:
|
||||
continue
|
||||
volumes[path.as_uri()] = " ".join(str(entry["label"]).split()) or path.name
|
||||
return volumes
|
||||
|
||||
|
||||
def update_places(path, libraries, mark=MARK, icon_name="steam", id_prefix="droiddeck-steam-"):
|
||||
if path.is_file():
|
||||
parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True, insert_pis=True))
|
||||
root = ET.fromstring(path.read_bytes(), parser=parser)
|
||||
@@ -80,10 +98,10 @@ def update_places(path, libraries):
|
||||
before = ET.tostring(root)
|
||||
seen = set()
|
||||
personal = {place_uri(b.get("href")) for b in root.findall("bookmark")
|
||||
if b.find("info/metadata[@owner='" + KDE_OWNER + "']/" + MARK) is None}
|
||||
if b.find("info/metadata[@owner='" + KDE_OWNER + "']/" + mark) is None}
|
||||
for bookmark in root.findall("bookmark"):
|
||||
metadata = bookmark.find("info/metadata[@owner='" + KDE_OWNER + "']")
|
||||
if metadata is None or metadata.find(MARK) is None:
|
||||
if metadata is None or metadata.find(mark) is None:
|
||||
continue
|
||||
uri = place_uri(bookmark.get("href"))
|
||||
if uri not in libraries or uri in seen or uri in personal:
|
||||
@@ -101,10 +119,10 @@ def update_places(path, libraries):
|
||||
ET.SubElement(bookmark, "title").text = label
|
||||
info = ET.SubElement(bookmark, "info")
|
||||
icon = ET.SubElement(info, "metadata", {"owner": "http://freedesktop.org"})
|
||||
ET.SubElement(icon, "{" + ICON_NS + "}icon", {"name": "steam"})
|
||||
ET.SubElement(icon, "{" + ICON_NS + "}icon", {"name": icon_name})
|
||||
metadata = ET.SubElement(info, "metadata", {"owner": KDE_OWNER})
|
||||
ET.SubElement(metadata, "ID").text = "droiddeck-steam-" + hashlib.sha256(uri.encode()).hexdigest()[:16]
|
||||
ET.SubElement(metadata, MARK).text = "true"
|
||||
ET.SubElement(metadata, "ID").text = id_prefix + hashlib.sha256(uri.encode()).hexdigest()[:16]
|
||||
ET.SubElement(metadata, mark).text = "true"
|
||||
ET.SubElement(metadata, "isSystemItem").text = "false"
|
||||
if ET.tostring(root) != before:
|
||||
atomic_write(path, ET.tostring(root, encoding="unicode", xml_declaration=True))
|
||||
@@ -154,7 +172,9 @@ def main():
|
||||
available = bool(label) and (LIBRARY / "steamapps").is_dir()
|
||||
update_bookmark(bookmarks_file(home, config), label if available else None)
|
||||
data = Path(os.environ.get("XDG_DATA_HOME") or home / ".local/share")
|
||||
update_places(data / "user-places.xbel", steam_libraries(home, data))
|
||||
places = data / "user-places.xbel"
|
||||
update_places(places, steam_libraries(home, data))
|
||||
update_places(places, removable_volumes(), "DroidDeckRemovableVolume", "drive-removable-media", "droiddeck-volume-")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -38,7 +38,7 @@ RUNTIMES = {SNIPER_APPID: ("sniper_platform_", "Steam Linux Runtime 3.0 (sniper"
|
||||
SLR4_APPID: ("steamrt4_platform_", "Steam Linux Runtime 4.0 (steamrt4")}
|
||||
MARKER = ".droiddeck-fex"
|
||||
LAYOUT = 1
|
||||
ROOTFS_LAYOUT = 4
|
||||
ROOTFS_LAYOUT = 10
|
||||
BLOB_DIRS = re.compile(r"^(?:\.ref|[0-9a-f]{2})$")
|
||||
ROOTFS_LIBRARY_DIRS = ("lib", "lib64")
|
||||
ARCH_DIRS = ("x86_64-linux-gnu", "i386-linux-gnu")
|
||||
@@ -49,7 +49,15 @@ PROVIDED = frozenset((
|
||||
"libnss_compat.so.2", "libnss_dns.so.2", "libnss_files.so.2", "libnss_hesiod.so.2", "libthread_db.so.1",
|
||||
"libmemusage.so", "libpcprofile.so", "libc_malloc_debug.so.0", "gconv", "libstdc++.so.6", "libgcc_s.so.1",
|
||||
"libssl.so.3", "libcrypto.so.3",
|
||||
"libfreetype.so.6", "libpng16.so.16", "libbrotlidec.so.1", "libbrotlicommon.so.1", "libbz2.so.1.0", "libz.so.1",
|
||||
"libwayland-client.so.0", "libwayland-egl.so.1", "libwayland-server.so.0", "libffi.so.8",
|
||||
"libgbm.so.1", "libdrm.so.2", "libexpat.so.1",
|
||||
))
|
||||
PROVIDED_NEEDS = {
|
||||
"libwayland-client.so.0": ("libffi.so.8",),
|
||||
"libwayland-server.so.0": ("libffi.so.8",),
|
||||
"libgbm.so.1": ("libdrm.so.2", "libexpat.so.1"),
|
||||
}
|
||||
GLIBC_BUILD = re.compile(r"^(?:ld|lib[A-Za-z_]+)-2\.[0-9]+\.so$|^libSegFault\.so$")
|
||||
GUEST_LIBDIRS = (("x86_64", "lib/x86_64-linux-gnu"), ("i386", "lib/i386-linux-gnu"))
|
||||
PRELOAD_NAMES = ("libblsession.so", "libfakeinput.so")
|
||||
@@ -343,10 +351,14 @@ def stays_in_libraries(root, target, link):
|
||||
|
||||
|
||||
def mirror(source, provider, name, target, root):
|
||||
if provider and name in PROVIDED and os.path.lexists(os.path.join(provider, name)):
|
||||
usable_provider = provider and all(os.path.exists(os.path.join(provider, needed))
|
||||
for needed in (name,) + PROVIDED_NEEDS.get(name, ()))
|
||||
if name in PROVIDED and usable_provider:
|
||||
clone(os.path.join(provider, name), os.path.join(target, name))
|
||||
return
|
||||
path = os.path.join(source, name)
|
||||
if not os.path.lexists(path):
|
||||
return
|
||||
link = os.readlink(path) if os.path.islink(path) else None
|
||||
if link and GLIBC_BUILD.match(os.path.basename(link)):
|
||||
if name not in INTERPRETERS:
|
||||
@@ -365,6 +377,16 @@ def build_rootfs(base, provider):
|
||||
rootfs = os.path.join(STATE, "rootfs")
|
||||
stamp = "%d\n%s\n%s%s\n%s" % (ROOTFS_LAYOUT, os.path.realpath(base), read_text(os.path.join(base_files, MARKER)) or "",
|
||||
os.path.realpath(provider), read_text(os.path.join(provider_files, MARKER)) or "")
|
||||
for top in ("lib", "lib64"):
|
||||
for arch in ARCH_DIRS:
|
||||
for name in sorted(PROVIDED):
|
||||
path = os.path.join(provider_files, top, arch, name)
|
||||
try:
|
||||
info = os.stat(path)
|
||||
stamp += "\n%s %s %d %d %d %d" % (path, os.path.realpath(path), info.st_ino, info.st_size,
|
||||
info.st_mtime_ns, info.st_ctime_ns)
|
||||
except OSError:
|
||||
stamp += "\n%s missing" % path
|
||||
if read_text(os.path.join(rootfs, MARKER)) == stamp:
|
||||
return False
|
||||
for entry in os.listdir(STATE):
|
||||
@@ -384,7 +406,7 @@ def build_rootfs(base, provider):
|
||||
if entry in ARCH_DIRS and os.path.isdir(path) and not os.path.islink(path):
|
||||
provided = os.path.join(provider_files, top, entry)
|
||||
os.makedirs(os.path.join(tmp, top, entry))
|
||||
for name in set(os.listdir(path)) | {name for name in PROVIDED if os.path.lexists(os.path.join(provided, name))}:
|
||||
for name in set(os.listdir(path)) | {name for name in PROVIDED if os.path.exists(os.path.join(provided, name))}:
|
||||
mirror(path, provided, name, os.path.join(tmp, top, entry), tmp)
|
||||
else:
|
||||
mirror(source, None, entry, os.path.join(tmp, top), tmp)
|
||||
|
||||
@@ -887,8 +887,10 @@ case $mode in
|
||||
_bl_fall=$((_bl_sample_available - _bl_available))
|
||||
[ "$_saved_growth" -gt "$_bl_growth" ] && _bl_growth=$_saved_growth
|
||||
[ "$_saved_fall" -gt "$_bl_fall" ] && _bl_fall=$_saved_fall
|
||||
_bl_sample_at=$SECONDS _bl_sample_available=$_bl_available _bl_sample_gpu=$_bl_gpu
|
||||
_bl_sample_unevictable=$_bl_unevictable _bl_sample_shmem=$_bl_shmem
|
||||
if [ $((SECONDS - _bl_sample_at)) -ge 5 ]; then
|
||||
_bl_sample_at=$SECONDS _bl_sample_available=$_bl_available _bl_sample_gpu=$_bl_gpu
|
||||
_bl_sample_unevictable=$_bl_unevictable _bl_sample_shmem=$_bl_shmem
|
||||
fi
|
||||
fi
|
||||
_bl_real_available=$_bl_available
|
||||
[ "$_bl_real_available" -ge 0 ] && _bl_real_available=$((_bl_real_available - _bl_growth))
|
||||
@@ -898,6 +900,8 @@ case $mode in
|
||||
_bl_tier_headroom=$((_bl_mem_total / 4))
|
||||
[ "$_bl_tier_headroom" -ge $((768 * 1024)) ] || _bl_tier_headroom=$((768 * 1024))
|
||||
[ "$_bl_tier_headroom" -le $((2560 * 1024)) ] || _bl_tier_headroom=$((2560 * 1024))
|
||||
_bl_fall_headroom=$((_bl_tier_headroom * 2))
|
||||
[ "$_bl_fall_headroom" -ge $((_bl_mem_total * 2 / 5)) ] || _bl_fall_headroom=$((_bl_mem_total * 2 / 5))
|
||||
_bl_swap_reserve=$((_bl_swap_total / 5))
|
||||
[ "$_bl_swap_reserve" -ge $((256 * 1024)) ] || _bl_swap_reserve=$((256 * 1024))
|
||||
}
|
||||
@@ -967,7 +971,7 @@ case $mode in
|
||||
[ "$_bl_mem_total" -gt 0 ] && [ "$_bl_available" -ge 0 ] &&
|
||||
{ [ "$_bl_real_available" -lt "$_bl_tier_headroom" ] ||
|
||||
{ [ "$_bl_psi" -ge 100 ] && [ "$_bl_real_available" -lt $((_bl_tier_headroom * 3 / 2)) ]; } ||
|
||||
{ [ "$_bl_fall" -ge $((256 * 1024)) ] && [ "$_bl_real_available" -lt $((_bl_tier_headroom * 2)) ]; }; }
|
||||
{ [ "$_bl_fall" -ge $((256 * 1024)) ] && [ "$_bl_real_available" -lt "$_bl_fall_headroom" ]; }; }
|
||||
}
|
||||
bl_session_pressure() {
|
||||
bl_memory_read
|
||||
@@ -1030,7 +1034,7 @@ case $mode in
|
||||
}
|
||||
bl_watch_nap() {
|
||||
local _i
|
||||
if [ "$_bl_game" = 1 ] && [ "$_bl_available" -ge 0 ] && [ "$_bl_real_available" -lt $((_bl_tier_headroom * 2)) ]; then
|
||||
if [ "$_bl_game" = 1 ] && [ "$_bl_available" -ge 0 ] && [ "$_bl_real_available" -lt "$_bl_fall_headroom" ]; then
|
||||
for _i in 1 2 3 4 5; do
|
||||
nap 1
|
||||
bl_memory_read
|
||||
@@ -1104,7 +1108,7 @@ case $mode in
|
||||
local id
|
||||
id=$(sed -n 's/.*"focusedApp"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' \
|
||||
"$BL_LAUNCH_DIR/agent/focus.json" 2>/dev/null | head -1)
|
||||
[ -n "$id" ] || return "${1:-1}"
|
||||
[ -n "$id" ] || return "${1:-2}"
|
||||
case " ${_bl_apps-} " in
|
||||
*" $id "*) return 0 ;;
|
||||
esac
|
||||
@@ -1122,7 +1126,7 @@ case $mode in
|
||||
}
|
||||
_bl_since=-1 _bl_since_apps= _bl_packed=-1 _bl_measured=-1 _bl_unpack=0 _bl_capped=-1 _bl_backoff=30
|
||||
_bl_pressure_at=-1 _bl_pressure_backoff=30 _bl_tier_at=-1 _bl_tier_backoff=30 _bl_tier_pushed=0 _bl_tier_back=0 _bl_tier_targets=() _bl_tier_swaps=() _bl_tier_starts=()
|
||||
_bl_client_pending=0 _bl_client_reserve=0 _bl_client_targets=()
|
||||
_bl_client_pending=0 _bl_client_reserve=0 _bl_client_targets=() _bl_away=
|
||||
_bl_sample_at= _bl_sample_available=0 _bl_sample_gpu=0 _bl_sample_unevictable=0 _bl_sample_shmem=0
|
||||
while kill -0 $$ 2>/dev/null; do
|
||||
bl_zram_scan
|
||||
@@ -1155,7 +1159,10 @@ case $mode in
|
||||
_bl_preserved_growth=$_bl_growth _bl_preserved_fall=$_bl_fall
|
||||
bl_session_pressure
|
||||
bl_client_pressure_finish
|
||||
if [ "$_bl_game" = 1 ] && bl_game_focused; then
|
||||
_bl_focus=1
|
||||
[ "$_bl_game" = 1 ] && { bl_game_focused && _bl_focus=0 || _bl_focus=$?; }
|
||||
if [ "$_bl_game" = 1 ] && [ "$_bl_focus" = 0 ]; then
|
||||
_bl_away=
|
||||
if [ "$_bl_since" -lt 0 ] || [ "$_bl_since_apps" != "$_bl_apps" ]; then
|
||||
_bl_since=$SECONDS _bl_since_apps=$_bl_apps
|
||||
fi
|
||||
@@ -1165,15 +1172,31 @@ case $mode in
|
||||
_bl_packed=$SECONDS
|
||||
fi
|
||||
elif [ "$_bl_game" != 1 ]; then
|
||||
_bl_away=
|
||||
if [ "$_bl_packed" -ge 0 ]; then
|
||||
_bl_unpack=1
|
||||
fi
|
||||
_bl_since=-1 _bl_packed=-1 _bl_tier_at=-1 _bl_tier_backoff=30 _bl_tier_pushed=0 _bl_tier_targets=() _bl_tier_swaps=() _bl_tier_starts=()
|
||||
else
|
||||
_bl_since=-1
|
||||
if [ "$_bl_focus" = 1 ]; then
|
||||
[ -n "${_bl_away-}" ] || _bl_away=$SECONDS
|
||||
else
|
||||
_bl_away=
|
||||
fi
|
||||
if [ "$_bl_packed" -ge 0 ]; then
|
||||
_bl_unpack=1
|
||||
fi
|
||||
fi
|
||||
if [ "$_bl_unpack" = 1 ] && [ "$_bl_game" = 0 ] && ! bl_over_cap && bl_client_can_readback; then
|
||||
bl_zram_send 0 "memory recovered, reading the client back" client
|
||||
if [ "$_bl_unpack" = 1 ] &&
|
||||
{ [ "$_bl_game" = 0 ] || { [ "${_bl_ram_cap:-0}" = 0 ] && [ -n "${_bl_away-}" ] && [ $((SECONDS - _bl_away)) -ge 5 ]; }; } &&
|
||||
! bl_over_cap && bl_client_can_readback; then
|
||||
if [ "$_bl_game" = 0 ]; then
|
||||
bl_zram_send 0 "memory recovered, reading the client back" client
|
||||
else
|
||||
bl_zram_send 0 "the client is in front of the game, reading it back" client
|
||||
_bl_packed=-1
|
||||
fi
|
||||
_bl_unpack=0
|
||||
fi
|
||||
bl_watch_nap
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
import ctypes as C
|
||||
import functools
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import runpy
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -445,18 +447,22 @@ def park(steamapps):
|
||||
print(f"droiddeck-steam-games: {appid} is not here this session; its install is set aside until it is")
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=1)
|
||||
def compatibility():
|
||||
return runpy.run_path(os.path.join(os.path.dirname(os.path.abspath(__file__)), "steam-compatibility"))
|
||||
|
||||
|
||||
def seed_install(steam_root, game, appid):
|
||||
steamapps = Path(steam_root) / "steamapps"
|
||||
common = steamapps / "common"
|
||||
name = f"DroidDeck-{appid}"
|
||||
target = common / name
|
||||
source = Path(game["folder"])
|
||||
title = game["name"].replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ")
|
||||
minimal = ('"AppState"\n{\n' + f' "appid" "{appid}"\n "Universe" "1"\n "name" "{title}"\n'
|
||||
+ f' "StateFlags" "4"\n "installdir" "{name}"\n' + '}\n')
|
||||
manifest_text = compatibility()["manifest_text"]
|
||||
minimal = manifest_text(appid, game["name"], name)
|
||||
legacy = minimal.replace(' "Universe" "1"\n', '')
|
||||
# Steam checks every file of an import with no build before updating it, from scratch each time it is interrupted.
|
||||
bare = minimal[:-2] + ' "AutoUpdateBehavior" "1"\n}\n'
|
||||
bare = manifest_text(appid, game["name"], name, True)
|
||||
build = installed_build(source, appid, name)
|
||||
if build is None:
|
||||
content = bare
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import runpy
|
||||
import sys
|
||||
|
||||
BIN_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
LIBRARIES = (("/mnt/droiddeck-sd", os.environ.get("BL_LIBRARY_LABEL", "SD Card")),)
|
||||
MAIN_LABEL = "Internal Storage"
|
||||
|
||||
@@ -50,6 +52,77 @@ def register(steam_root, library, label):
|
||||
return len(apps)
|
||||
|
||||
|
||||
def installdirs(libraries):
|
||||
found = set()
|
||||
for library in libraries:
|
||||
steamapps = os.path.join(library, "steamapps")
|
||||
try:
|
||||
names = os.listdir(steamapps)
|
||||
except OSError:
|
||||
continue
|
||||
for name in names:
|
||||
if not re.fullmatch(r"appmanifest_\d+\.acf", name):
|
||||
continue
|
||||
try:
|
||||
with open(os.path.join(steamapps, name), encoding="utf-8", errors="replace") as f:
|
||||
m = re.search(r'"installdir"\s+"([^"]*)"', f.read(), re.I)
|
||||
except OSError:
|
||||
continue
|
||||
if m:
|
||||
found.add(m.group(1))
|
||||
return found
|
||||
|
||||
|
||||
def populated(path):
|
||||
try:
|
||||
with os.scandir(path) as entries:
|
||||
return next(entries, None) is not None
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def adoptable(library, known):
|
||||
common = os.path.join(library, "steamapps", "common")
|
||||
try:
|
||||
names = sorted(os.listdir(common))
|
||||
except OSError:
|
||||
return []
|
||||
return [n for n in names if n not in known and not n.startswith(".")
|
||||
and os.path.isdir(os.path.join(common, n)) and populated(os.path.join(common, n))]
|
||||
|
||||
|
||||
def adopt(steam_root, library):
|
||||
compat = runpy.run_path(os.path.join(BIN_DIR, "steam-compatibility"))
|
||||
known = compat["libraries"](steam_root)
|
||||
folders = adoptable(library, installdirs(known + [library]))
|
||||
if not folders:
|
||||
return 0
|
||||
entries = compat["appinfo_entries"](os.path.join(steam_root, "appcache", "appinfo.vdf"))
|
||||
by_dir = {}
|
||||
for app, info in entries.items():
|
||||
if app not in compat["NOT_GAMES"] and info["type"] in compat["PLAYABLE_TYPES"] and info["installdir"]:
|
||||
by_dir.setdefault(info["installdir"], []).append((app, info))
|
||||
steamapps = os.path.join(library, "steamapps")
|
||||
adopted = 0
|
||||
for folder in folders:
|
||||
matches = by_dir.get(folder, [])
|
||||
games = [m for m in matches if m[1]["type"] == "game"] or matches
|
||||
if len(games) != 1:
|
||||
continue
|
||||
app, info = games[0]
|
||||
if any(os.path.isfile(os.path.join(root, "steamapps", "appmanifest_%s.acf" % app))
|
||||
for root in known + [library]):
|
||||
continue
|
||||
try:
|
||||
with open(os.path.join(steamapps, "appmanifest_%s.acf" % app), "x", encoding="utf-8") as f:
|
||||
f.write(compat["manifest_text"](app, info["name"] or folder, folder, True))
|
||||
except OSError:
|
||||
continue
|
||||
adopted += 1
|
||||
print("droiddeck-steam-library: adopted %s as app %s in %s" % (folder, app, library))
|
||||
return adopted
|
||||
|
||||
|
||||
RETIRED = ("/mnt/bannerlator",)
|
||||
RENAMED = (("/mnt/bannerlator-sd", "/mnt/droiddeck-sd"),)
|
||||
|
||||
@@ -176,6 +249,7 @@ def main():
|
||||
managed = libraries is not None
|
||||
for library, label in libraries if managed else LIBRARIES:
|
||||
if os.path.isdir(os.path.join(library, "steamapps")):
|
||||
adopt(steam_root, library)
|
||||
register(steam_root, library, label)
|
||||
relabel(steam_root, library, label)
|
||||
else:
|
||||
|
||||
@@ -7,6 +7,7 @@ import os
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import stat
|
||||
import sys
|
||||
import time
|
||||
import subprocess
|
||||
@@ -291,6 +292,8 @@ def exited(argv, code=0):
|
||||
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH")
|
||||
if compat_data:
|
||||
(Path(compat_data) / "pfx" / ROCKSTAR_FOLDER / "launch.json").unlink(missing_ok=True)
|
||||
for line in rockstar_launcher_log(compat_data):
|
||||
log("rockstar launcher: " + line)
|
||||
return 0
|
||||
if found is not None and str(found[1].get("store")) == "epic" and os.environ.get(EPIC_HANDLED) != "1" \
|
||||
and os.access(EPIC_CLIENT, os.X_OK):
|
||||
@@ -320,6 +323,29 @@ ROCKSTAR_TITLES = {"gta3": "Grand Theft Auto III", "gtavc": "Grand Theft Auto: V
|
||||
"gta4": "Grand Theft Auto IV", "lanoire": "LANoireMTL"}
|
||||
|
||||
|
||||
def rockstar_launcher_log(compat_data, limit=65536):
|
||||
pfx = Path(compat_data) / "pfx"
|
||||
target = pfx / ROCKSTAR_FOLDER
|
||||
if not target.resolve().is_relative_to(pfx.resolve()):
|
||||
return []
|
||||
path = target / "launcher.log"
|
||||
try:
|
||||
descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
|
||||
except OSError:
|
||||
return []
|
||||
try:
|
||||
if not stat.S_ISREG(os.fstat(descriptor).st_mode):
|
||||
return []
|
||||
with os.fdopen(descriptor, "rb", closefd=False) as source:
|
||||
data = source.read(limit)
|
||||
path.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
return []
|
||||
finally:
|
||||
os.close(descriptor)
|
||||
return [line.strip() for line in data.decode("utf-8", "replace").splitlines() if line.strip()]
|
||||
|
||||
|
||||
def rockstar_sdk(folder, sidecar):
|
||||
if str(sidecar.get("id")) in ("gta4", "lanoire"):
|
||||
return True
|
||||
@@ -464,6 +490,7 @@ def prepare_rockstar(folder, sidecar, compat_data, launch_dir, proton="", ask_ap
|
||||
return "invalid-service-path"
|
||||
config = target / "launch.json"
|
||||
config.unlink(missing_ok=True)
|
||||
(target / "launcher.log").unlink(missing_ok=True)
|
||||
legacy = str(sidecar.get("id")) in ROCKSTAR_TITLES
|
||||
sdk = rockstar_sdk(folder, sidecar)
|
||||
title = ROCKSTAR_TITLES.get(str(sidecar.get("id")))
|
||||
|
||||
@@ -86,6 +86,7 @@ bl_run() {
|
||||
set -- /usr/local/bin/droiddeck-steamvr-game "$@"
|
||||
fi
|
||||
if [ -n "${BL_STORE_EXIT:-}" ]; then
|
||||
trap : INT TERM HUP
|
||||
"$@"
|
||||
rc=$?
|
||||
/usr/local/bin/droiddeck-store-launch --exited --code "$rc" "${BL_STORE_ARGS[@]}" || true
|
||||
@@ -892,7 +893,10 @@ def appinfo_entries(path, wanted=None):
|
||||
deck = common.get("steam_deck_compatibility")
|
||||
configuration = deck.get("configuration") if isinstance(deck, dict) else None
|
||||
recommended = configuration.get("recommended_runtime", "") if isinstance(configuration, dict) else ""
|
||||
config = info.get("config") if isinstance(info.get("config"), dict) else {}
|
||||
entry = {
|
||||
"name": str(common.get("name", "")),
|
||||
"installdir": str(config.get("installdir", "")),
|
||||
"oslist": {part.strip().lower() for part in str(common.get("oslist", "")).split(",") if part.strip()},
|
||||
"osarch": str(common.get("osarch", "")).lower(),
|
||||
"type": str(common.get("type", "")).lower(),
|
||||
@@ -959,6 +963,13 @@ def native_targets(steam_root, apps):
|
||||
return targets
|
||||
|
||||
|
||||
def manifest_text(appid, name, installdir, bare=False):
|
||||
title = name.replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ")
|
||||
text = ('"AppState"\n{\n' + f' "appid" "{appid}"\n "Universe" "1"\n "name" "{title}"\n'
|
||||
+ f' "StateFlags" "4"\n "installdir" "{installdir}"\n' + '}\n')
|
||||
return text[:-2] + ' "AutoUpdateBehavior" "1"\n}\n' if bare else text
|
||||
|
||||
|
||||
def app_manifest(steam_root, app):
|
||||
for library in libraries(steam_root):
|
||||
try:
|
||||
|
||||
@@ -45,6 +45,7 @@ static size_t private_range(uintptr_t start, uintptr_t end, struct span *spans,
|
||||
char buf[4096];
|
||||
size_t used = 0, count = 0;
|
||||
uintptr_t covered = start;
|
||||
int file_backed = 0;
|
||||
int fd = open("/proc/self/maps", O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return 0;
|
||||
for (;;) {
|
||||
@@ -59,7 +60,13 @@ static size_t private_range(uintptr_t start, uintptr_t end, struct span *spans,
|
||||
char *p = line;
|
||||
uintptr_t lo = strtoull(p, &p, 16), hi = strtoull(p + 1, &p, 16);
|
||||
char perms[5] = {0};
|
||||
if (*p == ' ') memcpy(perms, p + 1, 4);
|
||||
int inode = 0;
|
||||
if (*p == ' ') {
|
||||
memcpy(perms, p + 1, 4);
|
||||
char *field = p + 5;
|
||||
strtoull(field, &field, 16);
|
||||
inode = *field && (field = strchr(field + 1, ' ')) && strtoull(field, NULL, 10);
|
||||
}
|
||||
line = nl + 1;
|
||||
if (hi <= covered || lo >= end) continue;
|
||||
if (lo > covered || perms[3] != 'p' || count == cap) {
|
||||
@@ -68,11 +75,12 @@ static size_t private_range(uintptr_t start, uintptr_t end, struct span *spans,
|
||||
}
|
||||
spans[count].lo = covered;
|
||||
spans[count].hi = hi < end ? hi : end;
|
||||
file_backed |= inode;
|
||||
spans[count].prot = (perms[0] == 'r' ? PROT_READ : 0) | (perms[1] == 'w' ? PROT_WRITE : 0) | (perms[2] == 'x' ? PROT_EXEC : 0);
|
||||
covered = spans[count++].hi;
|
||||
if (covered >= end) {
|
||||
close(fd);
|
||||
return count;
|
||||
return file_backed ? count : 0;
|
||||
}
|
||||
}
|
||||
used = strlen(line);
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/uio.h>
|
||||
#include <unistd.h>
|
||||
@@ -20,11 +21,14 @@
|
||||
#endif
|
||||
#define ZR_SWAPPED (1ULL << 62)
|
||||
#define ZR_BATCH 512
|
||||
#define ZR_FUTEX_WAIT 0
|
||||
#define ZR_FUTEX_WAKE 1
|
||||
|
||||
static long (*zr_sys)(long, ...);
|
||||
static unsigned long zr_page;
|
||||
static int zr_busy;
|
||||
static int zr_pending;
|
||||
static int zr_worker;
|
||||
static char zr_maps[8192];
|
||||
static uint64_t zr_entries[ZR_BATCH];
|
||||
static struct iovec zr_iov[ZR_BATCH];
|
||||
@@ -143,19 +147,36 @@ static void zr_ack(int done) {
|
||||
zr_sys(SYS_close, fd);
|
||||
}
|
||||
|
||||
static void zr_request(void) {
|
||||
int mode = zr_mode();
|
||||
if (mode == 1) zr_ack(0);
|
||||
if (mode >= 0) zr_walk(mode);
|
||||
if (mode == 1) zr_ack(1);
|
||||
}
|
||||
|
||||
static void *zr_worker_main(void *unused) {
|
||||
(void)unused;
|
||||
prctl(PR_SET_NAME, "zr-worker", 0, 0, 0);
|
||||
for (;;) {
|
||||
while (!__atomic_exchange_n(&zr_pending, 0, __ATOMIC_SEQ_CST))
|
||||
zr_sys(SYS_futex, &zr_pending, ZR_FUTEX_WAIT, 0, NULL, NULL, 0);
|
||||
zr_request();
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void zr_handler(int sig, siginfo_t *info, void *context) {
|
||||
(void)sig;
|
||||
(void)context;
|
||||
if (info == NULL || info->si_code != SI_USER) return;
|
||||
int saved = errno;
|
||||
__atomic_store_n(&zr_pending, 1, __ATOMIC_SEQ_CST);
|
||||
while (__atomic_load_n(&zr_pending, __ATOMIC_SEQ_CST)
|
||||
&& !__atomic_exchange_n(&zr_busy, 1, __ATOMIC_SEQ_CST)) {
|
||||
if (__atomic_load_n(&zr_worker, __ATOMIC_ACQUIRE)) {
|
||||
zr_sys(SYS_futex, &zr_pending, ZR_FUTEX_WAKE, 1, NULL, NULL, 0);
|
||||
} else while (__atomic_load_n(&zr_pending, __ATOMIC_SEQ_CST)
|
||||
&& !__atomic_exchange_n(&zr_busy, 1, __ATOMIC_SEQ_CST)) {
|
||||
__atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST);
|
||||
int mode = zr_mode();
|
||||
if (mode == 1) zr_ack(0);
|
||||
if (mode >= 0) zr_walk(mode);
|
||||
if (mode == 1) zr_ack(1);
|
||||
zr_request();
|
||||
__atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST);
|
||||
}
|
||||
errno = saved;
|
||||
@@ -164,6 +185,7 @@ static void zr_handler(int sig, siginfo_t *info, void *context) {
|
||||
static void zr_child(void) {
|
||||
__atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST);
|
||||
__atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST);
|
||||
__atomic_store_n(&zr_worker, 0, __ATOMIC_RELEASE);
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void zr_init(void) {
|
||||
@@ -184,5 +206,21 @@ __attribute__((constructor)) static void zr_init(void) {
|
||||
sa.sa_sigaction = zr_handler;
|
||||
sa.sa_flags = SA_SIGINFO | SA_RESTART;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
if (sigaction(SIGURG, &sa, NULL) == 0) pthread_atfork(NULL, NULL, zr_child);
|
||||
if (sigaction(SIGURG, &sa, NULL) == 0) {
|
||||
pthread_atfork(NULL, NULL, zr_child);
|
||||
pthread_attr_t attr;
|
||||
if (pthread_attr_init(&attr) == 0) {
|
||||
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
|
||||
pthread_t thread;
|
||||
sigset_t blocked;
|
||||
sigset_t previous;
|
||||
if (sigfillset(&blocked) == 0 &&
|
||||
pthread_sigmask(SIG_SETMASK, &blocked, &previous) == 0) {
|
||||
if (pthread_create(&thread, &attr, zr_worker_main, NULL) == 0)
|
||||
__atomic_store_n(&zr_worker, 1, __ATOMIC_RELEASE);
|
||||
pthread_sigmask(SIG_SETMASK, &previous, NULL);
|
||||
}
|
||||
pthread_attr_destroy(&attr);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -423,6 +423,9 @@ ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) {
|
||||
if (is_proc_self_exe(pathname)) {
|
||||
ssize_t exe_len = handle_proc_self_exe(buf, bufsiz);
|
||||
if (exe_len >= 0) return exe_len;
|
||||
} else {
|
||||
ssize_t exe_len = handle_proc_other_exe(pathname, buf, bufsiz);
|
||||
if (exe_len >= 0) return exe_len;
|
||||
}
|
||||
static ssize_t (*orig_readlink)(const char *, char *, size_t) = NULL;
|
||||
if (!orig_readlink) orig_readlink = (ssize_t (*)(const char *, char *, size_t))dlsym(RTLD_NEXT, "readlink");
|
||||
@@ -443,9 +446,16 @@ ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) {
|
||||
if (!orig_readlinkat) orig_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat");
|
||||
DDNATV_AT_REMAP(dirfd, pathname);
|
||||
// after the remap: "proc/self/exe" relative to a descriptor for "/" is /proc/self/exe as well
|
||||
{
|
||||
ssize_t exe_len = handle_proc_exe_at(dirfd, pathname, buf, bufsiz);
|
||||
if (exe_len >= 0) return exe_len;
|
||||
}
|
||||
if (is_proc_self_exe(pathname)) {
|
||||
ssize_t exe_len = handle_proc_self_exe(buf, bufsiz);
|
||||
if (exe_len >= 0) return exe_len;
|
||||
} else {
|
||||
ssize_t exe_len = handle_proc_other_exe(pathname, buf, bufsiz);
|
||||
if (exe_len >= 0) return exe_len;
|
||||
}
|
||||
char pbuf[PATH_MAX];
|
||||
const char *target = (pathname && pathname[0] == '/') ? rewrite_path(pathname, pbuf, sizeof(pbuf)) : pathname;
|
||||
|
||||
+173
-49
@@ -165,64 +165,188 @@ static int is_proc_self_exe(const char *path) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void exe_from_cmdline(const char *cmdline_path, char *out, size_t outsz) {
|
||||
int fd = open(cmdline_path, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return;
|
||||
char cmdline[8192];
|
||||
ssize_t n = read(fd, cmdline, sizeof(cmdline) - 1);
|
||||
close(fd);
|
||||
if (n <= 0) return;
|
||||
cmdline[n] = '\0';
|
||||
char *args[64] = {0};
|
||||
int ac = 0;
|
||||
char *p = cmdline;
|
||||
while (p < cmdline + n && ac < 64) {
|
||||
args[ac++] = p;
|
||||
p += strlen(p) + 1;
|
||||
}
|
||||
for (int i = 0; i < ac; i++) {
|
||||
if (strcmp(args[i], "--argv0") == 0 && i + 2 < ac) {
|
||||
ddnatv_copy_cstr(out, outsz, args[i + 2]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (ac > 0 && args[0] && args[0][0] != '\0') ddnatv_copy_cstr(out, outsz, args[0]);
|
||||
}
|
||||
|
||||
static ssize_t copy_guest_exe(const char *real_exe, char *buf, size_t bufsiz) {
|
||||
const char *out_path = real_exe;
|
||||
if (g_ddnatv_root[0] != '\0') {
|
||||
size_t rlen = g_ddnatv_root_len;
|
||||
if (strncmp(real_exe, g_ddnatv_root, rlen) == 0 &&
|
||||
(real_exe[rlen] == '/' || real_exe[rlen] == '\0')) {
|
||||
out_path = real_exe + rlen;
|
||||
if (out_path[0] == '\0') out_path = "/";
|
||||
}
|
||||
}
|
||||
size_t len = strlen(out_path);
|
||||
size_t copy_len = (len < bufsiz) ? len : bufsiz;
|
||||
memcpy(buf, out_path, copy_len);
|
||||
return (ssize_t)copy_len;
|
||||
}
|
||||
|
||||
static ssize_t handle_proc_self_exe(char *buf, size_t bufsiz) {
|
||||
if (!buf || bufsiz == 0) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
init_ddnatv_hook();
|
||||
if (g_real_exe[0] == '\0') {
|
||||
int fd = open("/proc/self/cmdline", O_RDONLY);
|
||||
if (fd >= 0) {
|
||||
char cmdline[8192];
|
||||
ssize_t n = read(fd, cmdline, sizeof(cmdline) - 1);
|
||||
close(fd);
|
||||
if (n > 0) {
|
||||
cmdline[n] = '\0';
|
||||
char *args[64] = {0};
|
||||
int ac = 0;
|
||||
char *p = cmdline;
|
||||
while (p < cmdline + n && ac < 64) {
|
||||
args[ac++] = p;
|
||||
p += strlen(p) + 1;
|
||||
}
|
||||
for (int i = 0; i < ac; i++) {
|
||||
if (strcmp(args[i], "--argv0") == 0 && i + 2 < ac) {
|
||||
strncpy(g_real_exe, args[i + 2], sizeof(g_real_exe) - 1);
|
||||
g_real_exe[sizeof(g_real_exe) - 1] = '\0';
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (g_real_exe[0] == '\0' && ac > 0 && args[0] && args[0][0] != '\0') {
|
||||
strncpy(g_real_exe, args[0], sizeof(g_real_exe) - 1);
|
||||
g_real_exe[sizeof(g_real_exe) - 1] = '\0';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (g_real_exe[0] != '\0') {
|
||||
char stripped[PATH_MAX];
|
||||
const char *out_path = g_real_exe;
|
||||
if (g_ddnatv_root[0] != '\0') {
|
||||
size_t rlen = g_ddnatv_root_len;
|
||||
if (strncmp(g_real_exe, g_ddnatv_root, rlen) == 0 &&
|
||||
(g_real_exe[rlen] == '/' || g_real_exe[rlen] == '\0')) {
|
||||
out_path = g_real_exe + rlen;
|
||||
if (out_path[0] == '\0') out_path = "/";
|
||||
}
|
||||
}
|
||||
strncpy(stripped, out_path, sizeof(stripped) - 1);
|
||||
stripped[sizeof(stripped) - 1] = '\0';
|
||||
|
||||
size_t len = strlen(stripped);
|
||||
size_t copy_len = (len < bufsiz) ? len : bufsiz;
|
||||
memcpy(buf, stripped, copy_len);
|
||||
return (ssize_t)copy_len;
|
||||
}
|
||||
if (g_real_exe[0] == '\0') exe_from_cmdline("/proc/self/cmdline", g_real_exe, sizeof(g_real_exe));
|
||||
if (g_real_exe[0] != '\0') return copy_guest_exe(g_real_exe, buf, bufsiz);
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int is_ld_linux(const char *path);
|
||||
|
||||
static ssize_t (*real_readlinkat_fn(void))(int, const char *, char *, size_t) {
|
||||
static ssize_t (*fn)(int, const char *, char *, size_t) = NULL;
|
||||
if (!fn) fn = (ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat");
|
||||
return fn;
|
||||
}
|
||||
|
||||
static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) {
|
||||
char path[64];
|
||||
snprintf(path, sizeof(path), "/proc/%d/environ", (int)pid);
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return 0;
|
||||
size_t cap = 65536, used = 0, keylen = strlen(key);
|
||||
char *env = malloc(cap + 1);
|
||||
ssize_t got;
|
||||
while (env && (got = read(fd, env + used, cap - used)) > 0) {
|
||||
used += (size_t)got;
|
||||
if (used == cap) {
|
||||
char *bigger = cap < (8u << 20) ? realloc(env, cap * 2 + 1) : NULL;
|
||||
if (!bigger) break;
|
||||
env = bigger;
|
||||
cap *= 2;
|
||||
}
|
||||
}
|
||||
close(fd);
|
||||
int found = 0;
|
||||
if (env) {
|
||||
env[used] = '\0';
|
||||
for (char *e = env; e < env + used; e += strlen(e) + 1) {
|
||||
if (strncmp(e, key, keylen) == 0 && e[keylen] == '=' && e[keylen + 1] != '\0') {
|
||||
ddnatv_copy_cstr(out, outsz, e + keylen + 1);
|
||||
found = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
free(env);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
// Overlay filesystems report a different device to stat() than in /proc/<pid>/maps; the path, as the
|
||||
// kernel resolved it, then stands in for the device.
|
||||
static int proc_maps_file(pid_t pid, dev_t dev, ino_t ino, const char *resolved) {
|
||||
char path[64];
|
||||
snprintf(path, sizeof(path), "/proc/%d/maps", (int)pid);
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return 0;
|
||||
char chunk[4096], line[1024];
|
||||
size_t len = 0;
|
||||
ssize_t got;
|
||||
int found = 0;
|
||||
while (!found && (got = read(fd, chunk, sizeof(chunk))) > 0) {
|
||||
for (ssize_t i = 0; i < got && !found; i++) {
|
||||
if (chunk[i] != '\n') {
|
||||
if (len < sizeof(line) - 1) line[len++] = chunk[i];
|
||||
continue;
|
||||
}
|
||||
line[len] = '\0';
|
||||
len = 0;
|
||||
unsigned long long offset, inode;
|
||||
unsigned int major_nr, minor_nr;
|
||||
int name_at = 0;
|
||||
if (sscanf(line, "%*s %*s %llx %x:%x %llu %n", &offset, &major_nr, &minor_nr, &inode, &name_at) == 4 &&
|
||||
offset == 0 && inode == (unsigned long long)ino &&
|
||||
(makedev(major_nr, minor_nr) == dev || (resolved && name_at > 0 && strcmp(line + name_at, resolved) == 0))) {
|
||||
found = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
close(fd);
|
||||
return found;
|
||||
}
|
||||
|
||||
// The kernel's /proc/<pid>/exe of every other guest program is the loader that started it. KWin
|
||||
// grants privileged Wayland interfaces by matching that path to a desktop file's Exec, so it is the
|
||||
// program the loader runs, as for the calling process. A process can set its environment and
|
||||
// arguments, so the program they name counts only if that process has the file mapped from its start.
|
||||
static ssize_t handle_proc_other_exe(const char *path, char *buf, size_t bufsiz) {
|
||||
if (!path || !buf || bufsiz == 0 || strncmp(path, "/proc/", 6) != 0) return -1;
|
||||
const char *p = path + 6;
|
||||
if (*p < '1' || *p > '9') return -1;
|
||||
while (*p >= '0' && *p <= '9') p++;
|
||||
if (strcmp(p, "/exe") != 0) return -1;
|
||||
pid_t pid = (pid_t)atoi(path + 6);
|
||||
if (pid == getpid()) return -1;
|
||||
init_ddnatv_hook();
|
||||
if (g_ddnatv_root[0] == '\0') return -1;
|
||||
ssize_t (*real_readlinkat)(int, const char *, char *, size_t) = real_readlinkat_fn();
|
||||
static int (*real_fstatat)(int, const char *, struct stat *, int) = NULL;
|
||||
if (!real_fstatat) real_fstatat = (int (*)(int, const char *, struct stat *, int))dlsym(RTLD_NEXT, "fstatat");
|
||||
if (!real_readlinkat || !real_fstatat) return -1;
|
||||
char loader[PATH_MAX];
|
||||
ssize_t n = real_readlinkat(AT_FDCWD, path, loader, sizeof(loader) - 1);
|
||||
if (n <= 0) return -1;
|
||||
loader[n] = '\0';
|
||||
const char *base = strrchr(loader, '/');
|
||||
base = base ? base + 1 : loader;
|
||||
if (strcmp(base, "libddexec.so") != 0 && !is_ld_linux(loader)) return -1;
|
||||
|
||||
char real_exe[PATH_MAX] = "";
|
||||
if (!proc_env_value(pid, "DDNATV_REAL_EXE", real_exe, sizeof(real_exe))) {
|
||||
char cmdline[64];
|
||||
snprintf(cmdline, sizeof(cmdline), "/proc/%d/cmdline", (int)pid);
|
||||
exe_from_cmdline(cmdline, real_exe, sizeof(real_exe));
|
||||
}
|
||||
static char *(*real_realpath)(const char *, char *) = NULL;
|
||||
if (!real_realpath) real_realpath = (char *(*)(const char *, char *))dlsym(RTLD_NEXT, "realpath");
|
||||
struct stat st;
|
||||
char resolved[PATH_MAX];
|
||||
if (real_exe[0] != '/' || real_fstatat(AT_FDCWD, real_exe, &st, 0) != 0) return -1;
|
||||
if (!real_realpath || !real_realpath(real_exe, resolved)) resolved[0] = '\0';
|
||||
if (!proc_maps_file(pid, st.st_dev, st.st_ino, resolved[0] ? resolved : NULL)) return -1;
|
||||
return copy_guest_exe(real_exe, buf, bufsiz);
|
||||
}
|
||||
|
||||
// readlinkat(<descriptor for /proc/<pid>>, "exe"), as the absolute path would be answered.
|
||||
static ssize_t handle_proc_exe_at(int dirfd, const char *pathname, char *buf, size_t bufsiz) {
|
||||
if (!pathname || pathname[0] == '/' || dirfd == AT_FDCWD || strcmp(pathname, "exe") != 0) return -1;
|
||||
ssize_t (*real_readlinkat)(int, const char *, char *, size_t) = real_readlinkat_fn();
|
||||
if (!real_readlinkat) return -1;
|
||||
char link[64], dir[PATH_MAX], full[PATH_MAX];
|
||||
snprintf(link, sizeof(link), "/proc/self/fd/%d", dirfd);
|
||||
ssize_t n = real_readlinkat(AT_FDCWD, link, dir, sizeof(dir) - 1);
|
||||
if (n <= 0) return -1;
|
||||
dir[n] = '\0';
|
||||
if (strncmp(dir, "/proc/", 6) != 0 || snprintf(full, sizeof(full), "%s/exe", dir) >= (int)sizeof(full)) return -1;
|
||||
if (is_proc_self_exe(full)) return handle_proc_self_exe(buf, bufsiz);
|
||||
return handle_proc_other_exe(full, buf, bufsiz);
|
||||
}
|
||||
|
||||
static const char *rewrite_path(const char *path, char *buffer, size_t bufsize) {
|
||||
if (!path) return NULL;
|
||||
// Relative paths must NEVER be rewritten to rootfs root
|
||||
|
||||
@@ -102,6 +102,12 @@ Added by DroidDeck:
|
||||
`libblsession.so`'s robust.c never sees: `libopenvr_api.so` opens it `RTLD_DEEPBIND`. Steam
|
||||
aborted on "futex robust_list not initialized by pthreads" as soon as SteamVR was registered.
|
||||
|
||||
- `0029-proc-pid-root-guest.patch` - `/proc/<pid>/root` of a tracee resolved to the rootfs's host
|
||||
path, which does not exist inside the guest, so opening it failed with `ENOENT`. It now reads
|
||||
as `/`, like `exe` and `cwd` read as guest paths. xdg-desktop-portal opens it for every caller to
|
||||
tell sandboxed apps from host ones, so every portal request failed with "Unable to open
|
||||
/proc/<pid>/root", Sunshine's screen capture included.
|
||||
|
||||
Prototype (inert unless `PROOT_FASTPATH` is set; see `docs/development/proot-performance.md`):
|
||||
|
||||
- `0014-fastpath-trampoline.patch` - with `PROOT_FASTPATH`, every `SECCOMP_RET_TRACE` in the filter
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
--- a/src/path/proc.c
|
||||
+++ b/src/path/proc.c
|
||||
@@ -112,7 +112,7 @@
|
||||
* of tracee->???. */
|
||||
SUBSTITUTE(exe, known_tracee->exe);
|
||||
SUBSTITUTE(cwd, known_tracee->fs->cwd);
|
||||
- SUBSTITUTE(root, get_root(known_tracee));
|
||||
+ SUBSTITUTE(root, "/");
|
||||
#undef SUBSTITUTE
|
||||
return DEFAULT;
|
||||
|
||||
@@ -29,7 +29,7 @@ else
|
||||
"$P=$pkg" "$P.androidx-startup=$pkg.androidx-startup" "$P.logs=$pkg.logs" \
|
||||
"$P.pairingguide=$pkg.pairingguide" "$P.devicecode=$pkg.devicecode" "$P.pin=$pkg.pin" \
|
||||
"$P.documents=$pkg.documents" "$P.home=$pkg.home" "$P.agent=$pkg.agent" \
|
||||
"$P.vr_recovery=$pkg.vr_recovery" "$P.dualscreen=$pkg.dualscreen" "$P.typing=$pkg.typing" \
|
||||
"$P.vr_recovery=$pkg.vr_recovery" "$P.dualscreen=$pkg.dualscreen" "$P.typing=$pkg.typing" "$P.keeptop=$pkg.keeptop" \
|
||||
"$P.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION=$pkg.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION"
|
||||
fi
|
||||
got=$("$BUILD_TOOLS/aapt" dump badging "$work/renamed.apk" | sed -n "s/^package: name='\([^']*\)'.*/\1/p")
|
||||
|
||||
@@ -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 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. 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.
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const LIMIT: usize = 4096;
|
||||
|
||||
@@ -10,7 +12,13 @@ fn invalid() -> io::Error {
|
||||
)
|
||||
}
|
||||
|
||||
fn collect(bytes: &[u8], names: &mut BTreeSet<String>) {
|
||||
type Names = BTreeMap<String, String>;
|
||||
|
||||
const SCAN_LIMIT: u64 = 256 * 1024 * 1024;
|
||||
const NAME_LIMIT: usize = 4;
|
||||
const SIBLING_LIMIT: usize = 32;
|
||||
|
||||
fn collect(bytes: &[u8], names: &mut Names) {
|
||||
let prefix = br"\\.\pipe\";
|
||||
for (index, window) in bytes.windows(prefix.len()).enumerate() {
|
||||
if window != prefix {
|
||||
@@ -28,41 +36,95 @@ fn collect(bytes: &[u8], names: &mut BTreeSet<String>) {
|
||||
{
|
||||
let name = std::str::from_utf8(name).unwrap();
|
||||
if name.ends_with("LauncherPipe") || name.ends_with("Launcher_Pipe") {
|
||||
names.insert(name.to_owned());
|
||||
names
|
||||
.entry(name.to_ascii_lowercase())
|
||||
.or_insert_with(|| name.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pipe_names(reader: &mut impl Read) -> io::Result<Vec<String>> {
|
||||
let mut names = BTreeSet::new();
|
||||
pub fn title_pipe_names(exe: &Path) -> io::Result<Vec<String>> {
|
||||
discover(exe, SCAN_LIMIT)
|
||||
}
|
||||
|
||||
fn discover(exe: &Path, limit: u64) -> io::Result<Vec<String>> {
|
||||
let mut names = Names::new();
|
||||
let mut principal = limit;
|
||||
scan(&mut File::open(exe)?, &mut names, &mut principal)?;
|
||||
let mut extra = Names::new();
|
||||
let mut budget = limit;
|
||||
for path in siblings(exe) {
|
||||
if extra.len() >= NAME_LIMIT || budget == 0 {
|
||||
break;
|
||||
}
|
||||
let Ok(mut file) = File::open(&path) else {
|
||||
continue;
|
||||
};
|
||||
if !file
|
||||
.metadata()
|
||||
.is_ok_and(|metadata| metadata.len() <= budget)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut own = Names::new();
|
||||
if scan(&mut file, &mut own, &mut budget).is_err() {
|
||||
continue;
|
||||
}
|
||||
for (key, name) in own {
|
||||
if extra.len() < NAME_LIMIT && !names.contains_key(&key) {
|
||||
extra.entry(key).or_insert(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
names.append(&mut extra);
|
||||
Ok(names.into_values().collect())
|
||||
}
|
||||
|
||||
fn siblings(exe: &Path) -> Vec<PathBuf> {
|
||||
let Some(entries) = exe.parent().and_then(|folder| fs::read_dir(folder).ok()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut paths: Vec<_> = entries
|
||||
.flatten()
|
||||
.filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_file()))
|
||||
.map(|entry| entry.path())
|
||||
.filter(|path| {
|
||||
path != exe
|
||||
&& path
|
||||
.extension()
|
||||
.is_some_and(|extension| extension.eq_ignore_ascii_case("exe"))
|
||||
})
|
||||
.collect();
|
||||
paths.sort();
|
||||
paths.truncate(SIBLING_LIMIT);
|
||||
paths
|
||||
}
|
||||
|
||||
fn scan(reader: &mut impl Read, names: &mut Names, budget: &mut u64) -> io::Result<()> {
|
||||
let mut carry = Vec::new();
|
||||
let mut chunk = [0; 65536];
|
||||
let mut total = 0usize;
|
||||
loop {
|
||||
let count = reader.read(&mut chunk)?;
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
total += count;
|
||||
if total > 256 * 1024 * 1024 {
|
||||
return Err(invalid());
|
||||
}
|
||||
*budget = budget.checked_sub(count as u64).ok_or_else(invalid)?;
|
||||
carry.extend_from_slice(&chunk[..count]);
|
||||
collect(&carry, &mut names);
|
||||
collect(&carry, names);
|
||||
for offset in 0..2 {
|
||||
let ascii: Vec<_> = carry[offset..]
|
||||
.chunks_exact(2)
|
||||
.map(|pair| if pair[1] == 0 { pair[0] } else { 0 })
|
||||
.collect();
|
||||
collect(&ascii, &mut names);
|
||||
collect(&ascii, names);
|
||||
}
|
||||
if names.len() > 4 {
|
||||
if names.len() > NAME_LIMIT {
|
||||
return Err(invalid());
|
||||
}
|
||||
carry.drain(..carry.len().saturating_sub(256));
|
||||
}
|
||||
Ok(names.into_iter().collect())
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn exchange(reader: &mut impl Read) -> io::Result<Vec<u8>> {
|
||||
@@ -134,12 +196,165 @@ mod tests {
|
||||
}
|
||||
bytes.extend_from_slice(br"\\.\pipe\..\outsideLauncherPipe");
|
||||
bytes.push(0);
|
||||
let mut names = Names::new();
|
||||
scan(&mut Cursor::new(bytes), &mut names, &mut SCAN_LIMIT.clone()).unwrap();
|
||||
assert_eq!(
|
||||
pipe_names(&mut Cursor::new(bytes)).unwrap(),
|
||||
names.into_values().collect::<Vec<_>>(),
|
||||
["GameLauncherPipe", "OtherLauncher_Pipe"]
|
||||
);
|
||||
}
|
||||
|
||||
fn folder(name: &str) -> std::path::PathBuf {
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("droiddeck-identity-{name}-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir(&path).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn title_names_include_sibling_launcher_executables() {
|
||||
let root = folder("siblings");
|
||||
let game = root.join("Game.exe");
|
||||
fs::write(&game, b"MZ obfuscated").unwrap();
|
||||
fs::write(
|
||||
root.join("TitleLauncher.exe"),
|
||||
[br"MZ \\.\pipe\TitleLauncher_Pipe".as_slice(), b"\0"].concat(),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("Data.dat"),
|
||||
[br"\\.\pipe\DataLauncher_Pipe".as_slice(), b"\0"].concat(),
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir(root.join("Folder.exe")).unwrap();
|
||||
let names = title_pipe_names(&game).unwrap();
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
assert_eq!(names, ["TitleLauncher_Pipe"]);
|
||||
}
|
||||
|
||||
fn executable(path: &Path, names: &[&str]) {
|
||||
let mut bytes = b"MZ ".to_vec();
|
||||
for name in names {
|
||||
bytes.extend_from_slice(br"\\.\pipe\");
|
||||
bytes.extend_from_slice(name.as_bytes());
|
||||
bytes.push(0);
|
||||
}
|
||||
fs::write(path, bytes).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn title_names_keep_the_game_executable_names_and_limits() {
|
||||
let root = folder("principal");
|
||||
let game = root.join("Game.exe");
|
||||
executable(&game, &["GameLauncherPipe"]);
|
||||
fs::write(root.join("Tool.exe"), b"MZ plain").unwrap();
|
||||
assert_eq!(title_pipe_names(&game).unwrap(), ["GameLauncherPipe"]);
|
||||
for index in 0..40 {
|
||||
fs::write(root.join(format!("Extra{index:02}.exe")), b"MZ").unwrap();
|
||||
}
|
||||
executable(&root.join("Zz.exe"), &["LateLauncher_Pipe"]);
|
||||
let crowded = title_pipe_names(&game);
|
||||
executable(
|
||||
&game,
|
||||
&[
|
||||
"ALauncherPipe",
|
||||
"BLauncherPipe",
|
||||
"CLauncherPipe",
|
||||
"DLauncherPipe",
|
||||
"ELauncherPipe",
|
||||
],
|
||||
);
|
||||
let overfull = title_pipe_names(&game);
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
assert_eq!(crowded.unwrap(), ["GameLauncherPipe"]);
|
||||
assert!(overfull.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn title_names_skip_siblings_that_cannot_be_scanned() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let root = folder("unscannable");
|
||||
let game = root.join("Game.exe");
|
||||
executable(&game, &["GameLauncherPipe"]);
|
||||
let locked = root.join("Locked.exe");
|
||||
executable(&locked, &["LockedLauncher_Pipe"]);
|
||||
fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).unwrap();
|
||||
let locked_open = File::open(&locked).is_ok();
|
||||
File::create(root.join("Huge.exe"))
|
||||
.unwrap()
|
||||
.set_len(SCAN_LIMIT + 1)
|
||||
.unwrap();
|
||||
executable(
|
||||
&root.join("Noisy.exe"),
|
||||
&[
|
||||
"NALauncherPipe",
|
||||
"NBLauncherPipe",
|
||||
"NCLauncherPipe",
|
||||
"NDLauncherPipe",
|
||||
"NELauncherPipe",
|
||||
],
|
||||
);
|
||||
let names = title_pipe_names(&game);
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
let mut expected = vec!["GameLauncherPipe".to_owned()];
|
||||
if locked_open {
|
||||
expected.push("LockedLauncher_Pipe".to_owned());
|
||||
}
|
||||
assert_eq!(names.unwrap(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn title_names_bound_the_bytes_read_from_siblings() {
|
||||
let root = folder("budget");
|
||||
let game = root.join("Game.exe");
|
||||
executable(&game, &["GameLauncherPipe"]);
|
||||
executable(&root.join("First.exe"), &["FirstLauncherPipe"]);
|
||||
executable(&root.join("Second.exe"), &["SecondLauncherPipe"]);
|
||||
let size = fs::metadata(root.join("First.exe")).unwrap().len();
|
||||
let names = discover(&game, size + 8);
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
assert_eq!(names.unwrap(), ["FirstLauncherPipe", "GameLauncherPipe"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn title_names_merge_case_insensitively_and_cap_sibling_names() {
|
||||
let root = folder("merge");
|
||||
let game = root.join("Game.exe");
|
||||
executable(
|
||||
&game,
|
||||
&[
|
||||
"ALauncherPipe",
|
||||
"BLauncherPipe",
|
||||
"CLauncherPipe",
|
||||
"GTAVLauncher_Pipe",
|
||||
],
|
||||
);
|
||||
executable(
|
||||
&root.join("A.exe"),
|
||||
&["gtavLauncher_Pipe", "ELauncherPipe", "FLauncherPipe"],
|
||||
);
|
||||
executable(
|
||||
&root.join("B.exe"),
|
||||
&["GLauncherPipe", "HLauncherPipe", "ILauncherPipe"],
|
||||
);
|
||||
let names = title_pipe_names(&game);
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
assert_eq!(
|
||||
names.unwrap(),
|
||||
[
|
||||
"ALauncherPipe",
|
||||
"BLauncherPipe",
|
||||
"CLauncherPipe",
|
||||
"ELauncherPipe",
|
||||
"FLauncherPipe",
|
||||
"GLauncherPipe",
|
||||
"GTAVLauncher_Pipe",
|
||||
"HLauncherPipe"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_replies_echo_only_a_valid_challenge() {
|
||||
struct Split<R>(R);
|
||||
|
||||
@@ -146,14 +146,21 @@ fn run() -> Result<i32, Box<dyn std::error::Error>> {
|
||||
None
|
||||
};
|
||||
let mut identity_listeners = Vec::new();
|
||||
let mut identity_names = Vec::new();
|
||||
if session.is_some() {
|
||||
for name in
|
||||
droiddeck_rockstar_launcher::identity::pipe_names(&mut std::fs::File::open(&exe)?)?
|
||||
{
|
||||
identity_listeners.push(Listener::new(&name, Duration::from_secs(90))?);
|
||||
identity_names = droiddeck_rockstar_launcher::identity::title_pipe_names(&exe)?;
|
||||
for name in &identity_names {
|
||||
identity_listeners.push(Listener::new(name, Duration::from_secs(90))?);
|
||||
}
|
||||
}
|
||||
log("launcher pipes created");
|
||||
log(&format!(
|
||||
"launcher pipes created, identity: {}",
|
||||
if identity_names.is_empty() {
|
||||
"none".to_owned()
|
||||
} else {
|
||||
identity_names.join(", ")
|
||||
}
|
||||
));
|
||||
let mut command = std::process::Command::new(exe);
|
||||
command.current_dir(workdir).args(args?);
|
||||
if session.is_some() {
|
||||
@@ -256,7 +263,9 @@ fn run() -> Result<i32, Box<dyn std::error::Error>> {
|
||||
}
|
||||
let _ = result.send(outcome);
|
||||
});
|
||||
Ok(wait_for_game(&mut child, handshake)?.code().unwrap_or(1))
|
||||
let code = wait_for_game(&mut child, handshake)?.code().unwrap_or(1);
|
||||
log(&format!("game exited with code {code}"));
|
||||
Ok(code)
|
||||
}
|
||||
|
||||
fn main() {
|
||||
|
||||
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user