mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 12:28:40 +00:00
Merge remote-tracking branch 'origin/main' into review/malibridge-1950
This commit is contained in:
commit
f05e0df39e
135 files changed
+5415
-979
No files matched your search
@@ -55,6 +55,7 @@ class App : Application() {
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.epic.EpicBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.itch.ItchBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.gamejolt.GameJoltBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
|
||||
com.droiddeck.launcher.sync.Syncthing.init(this)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.battlenet.BattleNetBackend)
|
||||
|
||||
@@ -465,7 +465,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var fexPreset by mutableStateOf("")
|
||||
private var forceSsbs by mutableStateOf(false)
|
||||
private var steamClientArch by mutableStateOf("arm64")
|
||||
private var runSteamAtStartup by mutableStateOf(false)
|
||||
private var startupSession by mutableStateOf(SessionPrefs.STARTUP_OFF)
|
||||
private var bootMovie by mutableStateOf(com.droiddeck.launcher.session.BootMovie.DROIDDECK_30)
|
||||
private var bootMovieSound by mutableStateOf(true)
|
||||
private var bootMovieCustomName by mutableStateOf<String?>(null)
|
||||
@@ -500,19 +500,39 @@ class FrontEndActivity : ComponentActivity() {
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> setGameStorage(path, GameStorage.labelFor(this, path)) }
|
||||
}
|
||||
private var steamLibraries by mutableStateOf<List<SteamLibraries.Entry>>(emptyList())
|
||||
private var foundSteamLibraries by mutableStateOf<List<SteamLibraries.Found>>(emptyList())
|
||||
private var allFilesAccessMissing by mutableStateOf(false)
|
||||
private var steamLibraryScan = 0
|
||||
private val pickSteamLibrary = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
val path = if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data) else null
|
||||
if (path != null) Thread({
|
||||
if (path != null) addSteamLibrary(path)
|
||||
}
|
||||
|
||||
private fun addSteamLibrary(path: String) {
|
||||
Thread({
|
||||
val result = SteamLibraries.add(this, path)
|
||||
ui.post {
|
||||
steamLibraries = SteamLibraries.list(this)
|
||||
refreshFoundSteamLibraries()
|
||||
refresh()
|
||||
if (result is SteamLibraries.AddResult.Refused) {
|
||||
android.widget.Toast.makeText(this, getString(R.string.main_storage_not_usable, result.reason), android.widget.Toast.LENGTH_LONG).show()
|
||||
when {
|
||||
result is SteamLibraries.AddResult.Refused ->
|
||||
android.widget.Toast.makeText(this, getString(R.string.main_storage_not_usable, result.reason), android.widget.Toast.LENGTH_LONG).show()
|
||||
result is SteamLibraries.AddResult.Added && result.entry.path != path ->
|
||||
android.widget.Toast.makeText(this, getString(R.string.libraries_used_inner, result.entry.label), android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
}, "steam-library-add").start()
|
||||
}
|
||||
|
||||
private fun refreshFoundSteamLibraries() {
|
||||
allFilesAccessMissing = com.droiddeck.launcher.files.AllFilesAccess.missing()
|
||||
val scan = ++steamLibraryScan
|
||||
Thread({
|
||||
val found = SteamLibraries.found(this)
|
||||
ui.post { if (scan == steamLibraryScan) foundSteamLibraries = found }
|
||||
}, "steam-library-scan").start()
|
||||
}
|
||||
private var romsDir by mutableStateOf<String?>(null)
|
||||
private var steamGames by mutableStateOf<List<Library.SteamGame>>(emptyList())
|
||||
private var steamGamesX64 by mutableStateOf(false)
|
||||
@@ -553,7 +573,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var dualDisplayId by mutableStateOf(-1)
|
||||
private var dualScreenDevice by mutableStateOf(false)
|
||||
private var dualScreenMode by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO)
|
||||
private var dualScreenLauncher by mutableStateOf(true)
|
||||
private var dualScreenSessions by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO)
|
||||
private var dualScreenControls by mutableStateOf(true)
|
||||
private var launcherStarted = false
|
||||
private lateinit var displayManager: DisplayManager
|
||||
@@ -562,6 +582,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays()
|
||||
override fun onDisplayChanged(displayId: Int) = refreshSecondScreenDisplays()
|
||||
}
|
||||
private val bottomScreenListener: () -> Unit = { refreshSecondScreenDisplays() }
|
||||
private val secondScreenTouchListener = object : android.hardware.input.InputManager.InputDeviceListener {
|
||||
override fun onInputDeviceAdded(deviceId: Int) = refreshSecondScreenDisplays()
|
||||
override fun onInputDeviceRemoved(deviceId: Int) = refreshSecondScreenDisplays()
|
||||
@@ -1087,7 +1108,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
dualScreen = dualDisplayId >= 0 && com.droiddeck.launcher.ui.DualScreenPanel.available,
|
||||
dualScreenDevice = dualScreenDevice,
|
||||
dualScreenMode = dualScreenMode,
|
||||
dualScreenLauncher = dualScreenLauncher,
|
||||
dualScreenSessions = dualScreenSessions,
|
||||
dualScreenControls = dualScreenControls,
|
||||
packages = packageRows,
|
||||
packageCatalogLoading = catalogLoading,
|
||||
@@ -1330,8 +1351,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
SessionPrefs.setDualScreenMode(this, mode)
|
||||
refreshSecondScreenDisplays()
|
||||
},
|
||||
onDualScreenLauncher = { on ->
|
||||
SessionPrefs.setDualScreenLauncher(this, on)
|
||||
onDualScreenSessions = { mode ->
|
||||
SessionPrefs.setDualScreenSessionMode(this, mode)
|
||||
refreshSecondScreenDisplays()
|
||||
},
|
||||
onDualScreenControls = { on ->
|
||||
@@ -1536,7 +1557,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled() }
|
||||
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled(cold = true) }
|
||||
else {
|
||||
restoreCompatLaunch(savedInstanceState)
|
||||
pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH)
|
||||
@@ -1579,9 +1600,14 @@ class FrontEndActivity : ComponentActivity() {
|
||||
startSteamAtStartupIfEnabled()
|
||||
}
|
||||
|
||||
private fun startSteamAtStartupIfEnabled() {
|
||||
if (intent.action != Intent.ACTION_MAIN) return
|
||||
if (SessionPrefs.runSteamAtStartup(this) && !isFinishing && !isDestroyed) startSteamSession()
|
||||
private fun startSteamAtStartupIfEnabled(cold: Boolean = false) {
|
||||
if (intent.action != Intent.ACTION_MAIN && !(cold && intent.action == null)) return
|
||||
if (isFinishing || isDestroyed) return
|
||||
when (SessionPrefs.startupSession(this)) {
|
||||
SessionPrefs.STARTUP_STEAM -> startSteamSession()
|
||||
SessionPrefs.STARTUP_DESKTOP -> startSession(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP))
|
||||
}
|
||||
}
|
||||
|
||||
private fun playSteam() {
|
||||
@@ -1689,6 +1715,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries()
|
||||
compatLaunchVisible = true
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, false)
|
||||
@@ -1747,6 +1774,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
addDataScheme("file")
|
||||
})
|
||||
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
|
||||
com.droiddeck.launcher.input.DualScreen.watchTaken(bottomScreenListener)
|
||||
getSystemService(android.hardware.input.InputManager::class.java)?.registerInputDeviceListener(secondScreenTouchListener, ui)
|
||||
launcherStarted = true
|
||||
refreshSecondScreenDisplays()
|
||||
@@ -1791,6 +1819,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
com.droiddeck.launcher.stores.StoresState.libraryListener = null
|
||||
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
|
||||
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
|
||||
com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener)
|
||||
getSystemService(android.hardware.input.InputManager::class.java)?.unregisterInputDeviceListener(secondScreenTouchListener)
|
||||
launcherStarted = false
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
|
||||
@@ -1829,10 +1858,10 @@ class FrontEndActivity : ComponentActivity() {
|
||||
dualScreenMode = SessionPrefs.dualScreenMode(this)
|
||||
secondScreenDisplays = SecondScreenDisplays.available(displayManager, ownDisplayId)
|
||||
dualScreenDevice = com.droiddeck.launcher.input.DualScreen.anyDisplay(displayManager, ownDisplayId) != null
|
||||
dualScreenLauncher = SessionPrefs.dualScreenLauncher(this)
|
||||
dualScreenSessions = SessionPrefs.dualScreenSessionMode(this)
|
||||
dualScreenControls = SessionPrefs.dualScreenSessionControls(this)
|
||||
val target = com.droiddeck.launcher.input.DualScreen.display(this, displayManager, ownDisplayId)
|
||||
dualDisplayId = if (dualScreenLauncher) target?.displayId ?: -1 else -1
|
||||
dualDisplayId = target?.displayId ?: -1
|
||||
syncDualPanel()
|
||||
}
|
||||
|
||||
@@ -2147,6 +2176,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null,
|
||||
storageOptions = storageOptions,
|
||||
steamLibraries = steamLibraries,
|
||||
foundSteamLibraries = foundSteamLibraries,
|
||||
allFilesAccessMissing = allFilesAccessMissing,
|
||||
storageDiagnostics = mode == SessionService.MODE_STEAM && storageDiagnostics,
|
||||
fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null,
|
||||
forceSsbs = forceSsbs,
|
||||
@@ -2157,7 +2188,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
steamRepairQueued = steamRepairQueued,
|
||||
mangoapp = mangoapp,
|
||||
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
|
||||
runSteamAtStartup = mode == SessionService.MODE_STEAM && runSteamAtStartup,
|
||||
startupSession = startupSession,
|
||||
bootMovie = if (mode == SessionService.MODE_STEAM) bootMovie else null,
|
||||
bootMovieSound = bootMovieSound,
|
||||
bootMovieCustomName = bootMovieCustomName,
|
||||
@@ -2214,6 +2245,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
onAddSteamLibrary = {
|
||||
pickSteamLibrary.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.libraries_pick), null))
|
||||
},
|
||||
onAddFoundSteamLibrary = { path -> addSteamLibrary(path) },
|
||||
onAllowAllFilesAccess = { com.droiddeck.launcher.files.AllFilesAccess.open(this) },
|
||||
onRenameSteamLibrary = { id, label ->
|
||||
SteamLibraries.rename(this, id, label)
|
||||
steamLibraries = SteamLibraries.list(this)
|
||||
@@ -2223,6 +2256,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
SteamLibraries.remove(this, id)
|
||||
steamLibraries = SteamLibraries.list(this)
|
||||
refresh()
|
||||
refreshFoundSteamLibraries()
|
||||
},
|
||||
onStorageDiagnostics = { on ->
|
||||
SessionPrefs.setStorageDiagnosticsEnabled(this, on)
|
||||
@@ -2247,9 +2281,9 @@ class FrontEndActivity : ComponentActivity() {
|
||||
onReturnAfterGame = { on -> SessionPrefs.setReturnAfterGame(this, on); returnAfterGame = on },
|
||||
onShaderPrecache = { on -> SessionPrefs.setShaderPrecache(this, on); shaderPrecache = on },
|
||||
onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id },
|
||||
onRunSteamAtStartup = { on ->
|
||||
SessionPrefs.setRunSteamAtStartup(this, on)
|
||||
runSteamAtStartup = on
|
||||
onStartupSession = { id ->
|
||||
SessionPrefs.setStartupSession(this, id)
|
||||
startupSession = id
|
||||
},
|
||||
onBootMovie = { id -> com.droiddeck.launcher.session.BootMovie.select(this, id); loadBootMovie() },
|
||||
onBootMovieSound = { on -> SessionPrefs.setBootMovieSound(this, on); bootMovieSound = on },
|
||||
@@ -2440,7 +2474,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
returnAfterGame = SessionPrefs.returnAfterGame(this)
|
||||
loadShaderPrecache(mode)
|
||||
steamController = SessionPrefs.steamController(this)
|
||||
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
|
||||
startupSession = SessionPrefs.startupSession(this)
|
||||
loadBootMovie()
|
||||
hdrOn = SessionPrefs.hdr(this, mode)
|
||||
upscaler = SessionPrefs.upscaler(this)
|
||||
@@ -2459,6 +2493,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
refreshWifiDiscovery()
|
||||
gameStorage = SessionPrefs.gameStorage(this)
|
||||
steamLibraries = SteamLibraries.list(this)
|
||||
if (mode == SessionService.MODE_STEAM) refreshFoundSteamLibraries()
|
||||
storageDiagnostics = SessionPrefs.storageDiagnosticsEnabled(this)
|
||||
settingsMode = mode
|
||||
Thread({
|
||||
@@ -2489,6 +2524,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
SessionPrefs.setGameStorage(this, path, label)
|
||||
gameStorage = path
|
||||
checkUsbLink()
|
||||
if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries()
|
||||
}
|
||||
|
||||
private fun checkUsbLink() {
|
||||
|
||||
@@ -37,6 +37,7 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.withFrameNanos
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -294,9 +295,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun alignCursorToGuest(): Boolean {
|
||||
if (pointerLocked || !CompositorHost.isStarted) return false
|
||||
if (!WaylandCompositor.nativeCursorInputPos(cursorPosBuf)) return false
|
||||
if (surfaceView.width <= 0 || surfaceView.height <= 0) return false
|
||||
val x = cursorPosBuf[0] / InputSpace.WIDTH.toFloat() * surfaceView.width
|
||||
val y = cursorPosBuf[1] / InputSpace.HEIGHT.toFloat() * surfaceView.height
|
||||
if (outputView().width <= 0 || outputView().height <= 0) return false
|
||||
val x = cursorPosBuf[0] / InputSpace.WIDTH.toFloat() * outputView().width
|
||||
val y = cursorPosBuf[1] / InputSpace.HEIGHT.toFloat() * outputView().height
|
||||
if (kotlin.math.abs(x - cursorPos.x) < 0.75f && kotlin.math.abs(y - cursorPos.y) < 0.75f) return false
|
||||
cursorPos = androidx.compose.ui.geometry.Offset(x, y)
|
||||
return true
|
||||
@@ -421,6 +422,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var glassesSettings by mutableStateOf(Glasses.settings.value)
|
||||
private var glassesScreen: GlassesScreen? = null
|
||||
private var glassesOutputActive by mutableStateOf(false)
|
||||
private var bottomGame: com.droiddeck.launcher.ui.BottomGameScreen? = null
|
||||
private var bottomOutputActive by mutableStateOf(false)
|
||||
private val topDesktopKeys = mutableSetOf<Pair<Int, Int>>()
|
||||
private var bottomRecoveries = 0
|
||||
private var gameOnBottom by mutableStateOf(SessionState.gameOnBottom)
|
||||
private var bottomSwapAvailable by mutableStateOf(false)
|
||||
private var pausedFrame by mutableStateOf<com.droiddeck.launcher.ui.PausedFrame?>(null)
|
||||
private var pausedFrameWanted = false
|
||||
private var pauseAnimated by mutableStateOf(false)
|
||||
@@ -475,6 +482,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var sessionActivityDisplayId = Display.DEFAULT_DISPLAY
|
||||
private lateinit var displayManager: DisplayManager
|
||||
private var secondScreenPresentation: SecondScreenPresentation? = null
|
||||
private val bottomScreenListener: () -> Unit = {
|
||||
if (secondScreenPresentation?.display?.displayId?.let(com.droiddeck.launcher.input.DualScreen::taken) == true) closeSecondScreen(reset = false)
|
||||
updateBottomGame()
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
|
||||
private val displayListener = object : DisplayManager.DisplayListener {
|
||||
override fun onDisplayAdded(displayId: Int) {
|
||||
notifyActivityDisplayStateChanged(displayId)
|
||||
@@ -489,6 +502,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
override fun onDisplayChanged(displayId: Int) {
|
||||
notifyActivityDisplayStateChanged(displayId)
|
||||
followPanelRefresh(displayId)
|
||||
updateBottomGame()
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
}
|
||||
@@ -520,7 +534,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
private fun followPanelRefresh(displayId: Int) {
|
||||
if (!CompositorHost.isStarted) return
|
||||
val output = glassesScreen?.display
|
||||
val output = bottomGame?.takeIf { bottomOutputActive }?.display ?: glassesScreen?.display
|
||||
?: (if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay) ?: return
|
||||
if (output.displayId != displayId) return
|
||||
applyOutputPacing()
|
||||
@@ -580,6 +594,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
SessionEvents.begin(this, mode, SessionPaths.label(mode, intent.getStringExtra(SessionService.EXTRA_PROGRAM)))
|
||||
SessionState.secondScreenAutoOpened = false
|
||||
SessionState.secondScreenProvisional = false
|
||||
SessionState.gameOnBottom = false
|
||||
gameOnBottom = false
|
||||
}
|
||||
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
|
||||
SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
|
||||
@@ -839,9 +855,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
androidx.compose.runtime.DisposableEffect(Unit) {
|
||||
onDispose { com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity, false) }
|
||||
}
|
||||
androidx.compose.runtime.LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, pipUi) { updatePointerCapture() }
|
||||
androidx.compose.runtime.LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, pipUi, bottomOutputActive) { updatePointerCapture() }
|
||||
androidx.compose.runtime.LaunchedEffect(bottomOutputActive) { hud.setHidden(pipUi || bottomOutputActive) }
|
||||
androidx.compose.runtime.LaunchedEffect(pipUi) {
|
||||
hud.setHidden(pipUi)
|
||||
hud.setHidden(pipUi || bottomOutputActive)
|
||||
applyOutputPacing()
|
||||
if (pipUi != frameGenPip) {
|
||||
frameGenPip = pipUi
|
||||
@@ -877,10 +894,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
} else {
|
||||
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
|
||||
CursorOverlay({ cursorPos }, cursorVisible && !uiPointer,
|
||||
CursorOverlay({ cursorPos }, cursorVisible && !uiPointer && !bottomOutputActive,
|
||||
resources.displayMetrics.density,
|
||||
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
|
||||
if (memoryHud.text.isNotEmpty()) HudText(memoryHud.text, hudColor, hudOpacity)
|
||||
if (bottomOutputActive && !loading.visible) SwappedTopPanel()
|
||||
val phonePanel = glassesOutputActive && !loading.visible && !drawerOpen && !pcKeyboardOpen
|
||||
if (phonePanel) GlassesPhonePanel(glasses, steamVrStatus == SteamVr.Status.RUNNING, headTracking)
|
||||
if (trackingRecovery != null && !drawerOpen && !pcKeyboardOpen && !loading.visible) {
|
||||
@@ -1187,6 +1205,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
touchAuto = getString(if (usingTouchpad()) R.string.session_touch_auto_touchpad else R.string.session_touch_auto_direct),
|
||||
fexPreset = fexPreset,
|
||||
secondScreenMode = secondScreenMode,
|
||||
gameOnBottom = bottomOutputActive,
|
||||
gameSwapAvailable = bottomSwapAvailable,
|
||||
onGameOnBottom = { on -> drawerOpen = false; putGameOnBottom(on) },
|
||||
dashboardAvailable = bottomPages().isNotEmpty(),
|
||||
desktopAvailable = com.droiddeck.launcher.session.BottomDesktop.available(),
|
||||
secondScreenDisplays = secondScreenDisplays,
|
||||
@@ -2068,7 +2089,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
|
||||
val size = live ?: if (SessionState.running) previous else glassesOutputSize() ?: outputSize()
|
||||
SessionState.outputSize = size
|
||||
if (!SessionState.running) SessionState.refreshHz = refreshHz()
|
||||
if (!SessionState.running) SessionState.refreshHz = refreshHz(holder)
|
||||
val panel = panelBounds()
|
||||
SessionState.upscaleRatio = maxOf(panel.width(), panel.height()).toFloat() / maxOf(size.first, size.second).coerceAtLeast(1)
|
||||
Thread({
|
||||
@@ -2118,7 +2139,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
CompositorHost.startOrAttach(
|
||||
this, holder.surface, runtimeDir.path,
|
||||
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
|
||||
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(), outputFpsLimit(),
|
||||
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), outputFpsLimit(),
|
||||
)
|
||||
onOutputAttached(holder)
|
||||
if (SessionState.running && size != previous) {
|
||||
@@ -2160,6 +2181,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
private fun windowOutputSize(width: Int, height: Int): Pair<Int, Int>? {
|
||||
if (isInPictureInPictureMode || width <= 0 || height <= 0) return null
|
||||
if (bottomGame != null) return when {
|
||||
SessionState.followScreen ->
|
||||
com.droiddeck.launcher.session.SessionDisplay.followSize(width, height, false, SessionState.followScale)
|
||||
resolutionChoice() == com.droiddeck.launcher.session.SessionDisplay.MATCH_SCREEN ->
|
||||
(width and 1.inv()) to (height and 1.inv())
|
||||
else -> null
|
||||
}
|
||||
return if (SessionState.followScreen)
|
||||
com.droiddeck.launcher.session.SessionDisplay.followSize(width, height, controlsBelowWanted(), SessionState.followScale)
|
||||
else if (glassesScreen == null) outputSize() else null
|
||||
@@ -2206,12 +2234,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
||||
if (holder !== outputHolder()) return
|
||||
cancelTouchGestures()
|
||||
cancelOutputTouches()
|
||||
surfaceW = 0
|
||||
surfaceH = 0
|
||||
glassesOutputActive = false
|
||||
bottomOutputActive = false
|
||||
if (CompositorHost.isStarted) WaylandCompositor.nativeSetCursorComposite(false)
|
||||
CompositorHost.detach(holder.surface)
|
||||
bottomGame?.takeIf { it.holder === holder }?.let { screen -> uiHandler.post { recoverBottomOutput(screen) } }
|
||||
}
|
||||
|
||||
private fun cancelTouchGestures() {
|
||||
@@ -2234,19 +2264,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun displayMode(): String = SessionPrefs.displayMode(this,
|
||||
intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM, intent.getStringExtra(SessionService.EXTRA_PROGRAM))
|
||||
|
||||
private fun outputSize(): Pair<Int, Int> {
|
||||
private fun outputSize(): Pair<Int, Int> =
|
||||
com.droiddeck.launcher.session.SessionDisplay.resolveChoice(com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
|
||||
resolutionChoice(), SessionPrefs.portrait(this) && !controlsBelowWanted())
|
||||
|
||||
private fun resolutionChoice(): String {
|
||||
val mode = displayMode()
|
||||
val panel = com.droiddeck.launcher.session.SessionDisplay.panelSize(this)
|
||||
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
|
||||
val choice = if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
|
||||
return if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
|
||||
Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode))
|
||||
com.droiddeck.launcher.session.SessionDisplay.MATCH_SCREEN
|
||||
else SessionPrefs.resolutionChoice(this, mode, panel)
|
||||
return com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panel, choice,
|
||||
SessionPrefs.portrait(this) && !controlsBelowWanted())
|
||||
else SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
|
||||
}
|
||||
|
||||
private fun refreshHz(): Float {
|
||||
private fun refreshHz(): Float = refreshHz(null)
|
||||
|
||||
private fun refreshHz(holder: SurfaceHolder?): Float {
|
||||
bottomGame?.takeIf { if (holder != null) holder === it.holder else bottomOutputActive }
|
||||
?.hz?.takeIf { it > 1f }?.let { return minOf(it, PerfMode.peakRefreshCap(this)) }
|
||||
glassesScreen?.hz?.takeIf { it > 1f }?.let { return it }
|
||||
val display = if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay
|
||||
val wanted = window.attributes.preferredDisplayModeId
|
||||
@@ -2595,6 +2630,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
return true
|
||||
}
|
||||
if ((pcKeyboardOpen || achievementsOpen) && fromController) return super.dispatchKeyEvent(event)
|
||||
if (!fromController && event.keyCode != KeyEvent.KEYCODE_BACK && sendToTopDesktop(event)) return true
|
||||
if (joyConVr?.onKeyEvent(event) == true) return true
|
||||
if (fromController && event.keyCode != KeyEvent.KEYCODE_BACK && padMouseMode() && padMouse.onKey(event)) return true
|
||||
if (event.keyCode != KeyEvent.KEYCODE_BACK && padBridge?.onKeyEvent(event) == true) return true
|
||||
@@ -2606,6 +2642,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
|
||||
private fun sendToTopDesktop(event: KeyEvent): Boolean {
|
||||
val key = event.deviceId to event.keyCode
|
||||
val owned = if (event.action == KeyEvent.ACTION_UP) topDesktopKeys.remove(key) else topDesktopFocused()
|
||||
if (!owned || !super.dispatchKeyEvent(event)) return false
|
||||
if (event.action == KeyEvent.ACTION_DOWN) topDesktopKeys += key
|
||||
return true
|
||||
}
|
||||
|
||||
private fun topDesktopFocused(): Boolean {
|
||||
if (!bottomOutputActive) return false
|
||||
var view: View? = currentFocus
|
||||
while (view != null) {
|
||||
if (view is com.droiddeck.launcher.ui.BottomDesktopPanel) return true
|
||||
view = view.parent as? View
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
|
||||
if (pipUi) return true
|
||||
notePress(event)
|
||||
@@ -2745,16 +2799,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun focusDrawer(): Boolean = dockedMenu()?.focusMenu() ?: sessionOverlay.requestFocus()
|
||||
|
||||
private fun dockDrawer(): Boolean {
|
||||
if (pipUi || !started || glassesScreen != null || !::displayManager.isInitialized) return false
|
||||
if (!SessionPrefs.dualScreenLauncher(this)) return false
|
||||
val target = com.droiddeck.launcher.input.DualScreen.display(this, displayManager, shownOnDisplayId) ?: return false
|
||||
if (pipUi || !started || glassesScreen != null || bottomGame != null || !::displayManager.isInitialized) return false
|
||||
val target = com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId) ?: return false
|
||||
if (secondScreenDisplays.none { it.id == target.displayId }) return false
|
||||
val shown = secondScreenPresentation?.display?.displayId
|
||||
return shown == null || shown == target.displayId
|
||||
}
|
||||
|
||||
private fun openDockedMenu(): Boolean {
|
||||
val target = com.droiddeck.launcher.input.DualScreen.display(this, displayManager, shownOnDisplayId) ?: return false
|
||||
val target = com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId) ?: return false
|
||||
return try {
|
||||
val presentation = secondScreenPresentation ?: secondScreenPresentation(target).also {
|
||||
selectedSecondScreenDisplay = target.displayId
|
||||
@@ -2861,7 +2914,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val rect = drawnRect() ?: return
|
||||
val cx = x.coerceIn(rect.left, rect.right)
|
||||
val cy = y.coerceIn(rect.top, rect.bottom)
|
||||
WaylandCompositor.nativeSendPointer(1, InputSpace.x(cx, surfaceView.width), InputSpace.y(cy, surfaceView.height))
|
||||
WaylandCompositor.nativeSendPointer(1, InputSpace.x(cx, outputView().width), InputSpace.y(cy, outputView().height))
|
||||
cursorVisible = false
|
||||
}
|
||||
override fun onButton(button: Int, pressed: Boolean) {
|
||||
@@ -2889,7 +2942,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
scrollRestY = 0f
|
||||
val rect = drawnRect() ?: return
|
||||
val x = rect.left + rect.width() * PAD_SCROLL_POINTER_X
|
||||
WaylandCompositor.nativeSendPointer(1, InputSpace.x(x, surfaceView.width), InputSpace.y(rect.centerY(), surfaceView.height))
|
||||
WaylandCompositor.nativeSendPointer(1, InputSpace.x(x, outputView().width), InputSpace.y(rect.centerY(), outputView().height))
|
||||
cursorVisible = false
|
||||
}
|
||||
override fun onScroll(dx: Float, dy: Float) = scrollListener.onScroll(dx, dy)
|
||||
@@ -2937,10 +2990,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun placeTouchpadAtGuest(rect: android.graphics.RectF) {
|
||||
if (pointerLocked || !CompositorHost.isStarted || surfaceView.width <= 0 || surfaceView.height <= 0) return
|
||||
if (pointerLocked || !CompositorHost.isStarted || outputView().width <= 0 || outputView().height <= 0) return
|
||||
if (!WaylandCompositor.nativeCursorInputPos(cursorPosBuf)) return
|
||||
val x = cursorPosBuf[0] / InputSpace.WIDTH.toFloat() * surfaceView.width
|
||||
val y = cursorPosBuf[1] / InputSpace.HEIGHT.toFloat() * surfaceView.height
|
||||
val x = cursorPosBuf[0] / InputSpace.WIDTH.toFloat() * outputView().width
|
||||
val y = cursorPosBuf[1] / InputSpace.HEIGHT.toFloat() * outputView().height
|
||||
if (rect.contains(x, y)) touchpad.place(x, y)
|
||||
}
|
||||
|
||||
@@ -2956,7 +3009,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val rect = drawnRect() ?: return
|
||||
val cx = x.coerceIn(rect.left, rect.right)
|
||||
val cy = y.coerceIn(rect.top, rect.bottom)
|
||||
WaylandCompositor.nativeSendPointer(1, InputSpace.x(cx, surfaceView.width), InputSpace.y(cy, surfaceView.height))
|
||||
WaylandCompositor.nativeSendPointer(1, InputSpace.x(cx, outputView().width), InputSpace.y(cy, outputView().height))
|
||||
showCursor(cx, cy)
|
||||
}
|
||||
|
||||
@@ -3021,6 +3074,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
.filter { glassesScreen == null || it.id != glasses.displayId }
|
||||
val oldIds = secondScreenDisplays.map { it.id }.toSet()
|
||||
secondScreenDisplays = candidates
|
||||
bottomSwapAvailable = bottomGame != null || bottomGameDisplay() != null
|
||||
val newIds = candidates.map { it.id }.toSet()
|
||||
if (secondScreenMode != SecondScreenMode.NONE && oldIds.isNotEmpty() && selectedSecondScreenDisplay !in newIds) {
|
||||
closeSecondScreen(reset = true)
|
||||
@@ -3039,7 +3093,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun openDualScreenControls() {
|
||||
if (SessionState.secondScreenAutoOpened || secondScreenMode != SecondScreenMode.NONE || pipUi) return
|
||||
if (!SessionPrefs.dualScreenSessionControls(this)) return
|
||||
val target = com.droiddeck.launcher.input.DualScreen.display(this, displayManager, shownOnDisplayId) ?: return
|
||||
val target = com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId) ?: return
|
||||
if (secondScreenDisplays.none { it.id == target.displayId }) return
|
||||
SessionState.secondScreenAutoOpened = true
|
||||
selectedSecondScreenDisplay = target.displayId
|
||||
@@ -3087,6 +3141,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
closeSecondScreen(reset = false)
|
||||
return
|
||||
}
|
||||
if (com.droiddeck.launcher.input.DualScreen.taken(target.displayId) || bottomGame?.display?.displayId == target.displayId) {
|
||||
if (secondScreenPresentation != null) closeSecondScreen(reset = false)
|
||||
secondScreenMode = mode
|
||||
SessionState.secondScreenMode = mode
|
||||
return
|
||||
}
|
||||
var presentation = secondScreenPresentation
|
||||
if (presentation?.display?.displayId != target.displayId) {
|
||||
dropDockedDrawer()
|
||||
@@ -3123,6 +3183,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
menu = {
|
||||
DroidDeckTheme { SessionMenu(docked = true) }
|
||||
},
|
||||
onSwap = if (com.droiddeck.launcher.input.DualScreen.builtIn(target)) ({ putGameOnBottom(true) }) else null,
|
||||
dashboard = if (bottomPages().isEmpty()) null else ({
|
||||
DroidDeckTheme {
|
||||
BottomDashboard(
|
||||
@@ -3131,6 +3192,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
onPage = { com.droiddeck.launcher.ui.SessionBottomTab.pick(SessionState.sessionId, it) },
|
||||
onClose = { selectSecondScreenMode(SecondScreenMode.NONE) },
|
||||
onMenu = if (dockDrawer()) ({ drawerOpen = true }) else null,
|
||||
onSwap = if (bottomSwapAvailable && com.droiddeck.launcher.input.DualScreen.builtIn(target)) ({ putGameOnBottom(true) }) else null,
|
||||
strip = { pageId ->
|
||||
com.droiddeck.launcher.ui.SessionBottomStrip(pageId) { if (::hud.isInitialized) hud.liveFps else null }
|
||||
},
|
||||
@@ -3147,7 +3209,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
))
|
||||
|
||||
private fun openSettingsBelow(intent: android.content.Intent, done: () -> Boolean) {
|
||||
val presentation = secondScreenPresentation ?: return
|
||||
val presentation = secondScreenPresentation
|
||||
if (presentation == null) {
|
||||
if (!bottomOutputActive) return
|
||||
listOf(intent, android.content.Intent(android.provider.Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)).any {
|
||||
runCatching { startActivity(android.content.Intent(it)) }
|
||||
.onFailure { e -> Log.w(TAG, "could not open ${it.action}", e) }
|
||||
.isSuccess
|
||||
}
|
||||
return
|
||||
}
|
||||
val options = android.app.ActivityOptions.makeBasic().setLaunchDisplayId(presentation.display.displayId)
|
||||
val opened = listOf(intent, android.content.Intent(android.provider.Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)).any {
|
||||
runCatching { startActivity(android.content.Intent(it).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK), options.toBundle()) }
|
||||
@@ -3178,7 +3249,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun captureScreenshot(onDone: (Boolean) -> Unit) {
|
||||
val source = if (glassesOutputActive) glassesScreen?.surfaceView else if (::surfaceView.isInitialized) surfaceView else null
|
||||
val source = if (glassesOutputActive) glassesScreen?.surfaceView else if (bottomOutputActive) bottomGame?.surfaceView
|
||||
else if (::surfaceView.isInitialized) surfaceView else null
|
||||
val width = source?.width ?: 0
|
||||
val height = source?.height ?: 0
|
||||
if (source == null || width <= 0 || height <= 0 || source.holder.surface?.isValid != true) {
|
||||
@@ -3242,7 +3314,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun controlsBelowWanted(): Boolean {
|
||||
if (!::sessionRoot.isInitialized || glassesScreen != null || cardboard.enabled) return false
|
||||
if (!::sessionRoot.isInitialized || glassesScreen != null || bottomGame != null || cardboard.enabled) return false
|
||||
return SessionPrefs.controlsBelowWanted(this, SessionState.mode, sessionRoot.width, sessionRoot.height,
|
||||
pipUi || isInPictureInPictureMode)
|
||||
}
|
||||
@@ -3288,14 +3360,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val rect = drawnRect() ?: return
|
||||
val px = rect.left + nx * rect.width()
|
||||
val py = rect.top + ny * rect.height()
|
||||
WaylandCompositor.nativeSendPointer(1, InputSpace.x(px, surfaceView.width), InputSpace.y(py, surfaceView.height))
|
||||
WaylandCompositor.nativeSendPointer(1, InputSpace.x(px, outputView().width), InputSpace.y(py, outputView().height))
|
||||
showCursor(px, py)
|
||||
}
|
||||
|
||||
private fun openBottomKeyboard() {
|
||||
if (!started) return
|
||||
if (secondScreenPresentation?.showsKeyboard != true && dockDrawer()) {
|
||||
val target = com.droiddeck.launcher.input.DualScreen.display(this, displayManager, shownOnDisplayId) ?: return
|
||||
val target = com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId) ?: return
|
||||
if (drawerOpen) drawerOpen = false
|
||||
typingReturnMode = secondScreenMode
|
||||
selectedSecondScreenDisplay = target.displayId
|
||||
@@ -3453,8 +3525,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun drawnRect(): android.graphics.RectF? {
|
||||
val width = surfaceView.width.takeIf { it > 0 } ?: return null
|
||||
val height = surfaceView.height.takeIf { it > 0 } ?: return null
|
||||
val width = outputView().width.takeIf { it > 0 } ?: return null
|
||||
val height = outputView().height.takeIf { it > 0 } ?: return null
|
||||
topPictureMapped = CompositorHost.isStarted && WaylandCompositor.nativeGamePictureRect(gamePictureBounds)
|
||||
if (topPictureMapped) return android.graphics.RectF(
|
||||
gamePictureBounds[0], gamePictureBounds[1], gamePictureBounds[2], gamePictureBounds[3])
|
||||
@@ -3550,7 +3622,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val cx = x.coerceIn(rect.left, rect.right)
|
||||
val cy = y.coerceIn(rect.top, rect.bottom)
|
||||
WaylandCompositor.nativeSendTouch(action, pointerId,
|
||||
InputSpace.x(cx, surfaceView.width), InputSpace.y(cy, surfaceView.height))
|
||||
InputSpace.x(cx, outputView().width), InputSpace.y(cy, outputView().height))
|
||||
showCursor(cx, cy)
|
||||
}
|
||||
|
||||
@@ -3614,7 +3686,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun updatePointerCapture() {
|
||||
if (!::surfaceView.isInitialized) return
|
||||
val view = window.decorView
|
||||
val want = pointerLocked && resumed && hasWindowFocus() && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !pipUi && mouseAttached()
|
||||
val want = pointerLocked && resumed && hasWindowFocus() && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !pipUi && !bottomOutputActive && mouseAttached()
|
||||
if (want == view.hasPointerCapture()) return
|
||||
if (want) view.requestPointerCapture() else view.releasePointerCapture()
|
||||
}
|
||||
@@ -3622,7 +3694,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var platformPointerShown: Boolean? = null
|
||||
|
||||
private fun appUiOwnsPointer(): Boolean =
|
||||
drawerOpen || pcKeyboardOpen || achievementsOpen || pipUi || glassesOutputActive
|
||||
drawerOpen || pcKeyboardOpen || achievementsOpen || pipUi || glassesOutputActive || bottomOutputActive
|
||||
|
||||
private fun applyPlatformPointer(shown: Boolean) {
|
||||
if (!::sessionRoot.isInitialized || !::surfaceView.isInitialized) return
|
||||
@@ -3845,7 +3917,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun capturePausedFrame(manual: Boolean = false) {
|
||||
if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive) return
|
||||
if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive || bottomOutputActive) return
|
||||
if (SessionState.suspended && pausedFrame != null) return
|
||||
if ((suspendPolicy == SessionPrefs.SUSPEND_NEVER && !manual && !SessionState.manualPause) || !::surfaceView.isInitialized) return
|
||||
if (surfaceView.holder.surface?.isValid != true) return
|
||||
@@ -3960,6 +4032,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (!inPip && surfaceW > 0) resizeOutputForWindow(surfaceW, surfaceH)
|
||||
applyUnfoldedControls()
|
||||
updateGlassesScreen()
|
||||
updateBottomGame()
|
||||
}
|
||||
|
||||
override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
|
||||
@@ -3977,6 +4050,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (::hud.isInitialized) hud.setBackgrounded(false)
|
||||
refreshActivityDisplayId()
|
||||
displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper()))
|
||||
com.droiddeck.launcher.input.DualScreen.watchTaken(bottomScreenListener)
|
||||
for (name in arrayOf("peak_refresh_rate", "min_refresh_rate")) {
|
||||
contentResolver.registerContentObserver(android.provider.Settings.System.getUriFor(name), false, refreshSettingObserver)
|
||||
}
|
||||
@@ -3988,6 +4062,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
SessionService.setActivityVisible(this, true, sessionActivityDisplayId)
|
||||
Glasses.rescan()
|
||||
updateGlassesScreen()
|
||||
updateBottomGame()
|
||||
updateHandCamera()
|
||||
}
|
||||
|
||||
@@ -3997,10 +4072,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (::hud.isInitialized) hud.setBackgrounded(true)
|
||||
updateHandCamera()
|
||||
displayManager.unregisterDisplayListener(displayListener)
|
||||
com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener)
|
||||
contentResolver.unregisterContentObserver(refreshSettingObserver)
|
||||
closeSecondScreen(reset = false)
|
||||
startedScreens = (startedScreens - 1).coerceAtLeast(0)
|
||||
updateGlassesScreen()
|
||||
updateBottomGame()
|
||||
if (startedScreens == 0) SessionService.setActivityVisible(this, false, sessionActivityDisplayId)
|
||||
super.onStop()
|
||||
}
|
||||
@@ -4310,15 +4387,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
glassesScreen?.trackingRecovery?.update(trackingRecovery, glasses.sbs)
|
||||
}
|
||||
|
||||
private fun outputHolder(): SurfaceHolder = glassesScreen?.holder ?: surfaceView.holder
|
||||
private fun outputHolder(): SurfaceHolder = glassesScreen?.holder ?: bottomGame?.holder ?: surfaceView.holder
|
||||
|
||||
private fun outputView(): SurfaceView = bottomGame?.takeIf { bottomOutputActive }?.surfaceView ?: surfaceView
|
||||
|
||||
private fun onOutputAttached(holder: SurfaceHolder) {
|
||||
if (holder !== outputHolder()) return
|
||||
glassesOutputActive = glassesScreen?.holder === holder
|
||||
if (CompositorHost.isStarted) WaylandCompositor.nativeSetCursorComposite(glassesOutputActive)
|
||||
surfaceView.visibility = if (glassesOutputActive) View.INVISIBLE else View.VISIBLE
|
||||
bottomOutputActive = bottomGame?.holder === holder
|
||||
if (bottomOutputActive) bottomRecoveries = 0
|
||||
if (CompositorHost.isStarted) WaylandCompositor.nativeSetCursorComposite(glassesOutputActive || bottomOutputActive)
|
||||
surfaceView.visibility = if (glassesOutputActive || bottomOutputActive) View.INVISIBLE else View.VISIBLE
|
||||
Log.i(TAG, "compositor output attached: " +
|
||||
if (glassesOutputActive) "glasses display ${glassesScreen?.display?.displayId}" else "phone")
|
||||
if (glassesOutputActive) "glasses display ${glassesScreen?.display?.displayId}"
|
||||
else if (bottomOutputActive) "bottom screen display ${bottomGame?.display?.displayId}" else "phone")
|
||||
if (pausedFrameWanted) uiHandler.postDelayed({
|
||||
if (pausedFrameWanted && pausedFrame == null && resumed) capturePausedFrame()
|
||||
}, PAUSED_FRAME_REDRAW_MS)
|
||||
@@ -4336,6 +4418,140 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (surfaceView.holder.surface?.isValid == true) surfaceCreated(surfaceView.holder)
|
||||
}
|
||||
|
||||
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) }
|
||||
}
|
||||
|
||||
private fun putGameOnBottom(on: Boolean) {
|
||||
if (on && bottomGame == null && bottomGameDisplay() == null) {
|
||||
android.widget.Toast.makeText(this, R.string.swap_screens_unavailable, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
SessionState.gameOnBottom = on
|
||||
gameOnBottom = on
|
||||
Log.i(TAG, "game screen: " + if (on) "bottom" else "top")
|
||||
updateBottomGame()
|
||||
}
|
||||
|
||||
private fun updateBottomGame() {
|
||||
if (!::surfaceView.isInitialized) return
|
||||
val target = bottomGameDisplay()
|
||||
val want = com.droiddeck.launcher.ui.GameScreenSwap.wanted(
|
||||
requested = gameOnBottom,
|
||||
activityStarted = started && !runtimeRemovalBlocked,
|
||||
sessionEnded = ended,
|
||||
inPip = pipUi || isInPictureInPictureMode,
|
||||
glassesOutput = glassesScreen != null,
|
||||
bottomScreenFree = target != null,
|
||||
)
|
||||
val shown = if (want) target else null
|
||||
val current = bottomGame
|
||||
if (current != null && current.display.displayId == shown?.displayId) return
|
||||
if (current != null || shown != null) cancelOutputTouches()
|
||||
if (current != null) {
|
||||
restoreTopOutput(current)
|
||||
runCatching { current.dismiss() }
|
||||
}
|
||||
if (shown != null) {
|
||||
closeSecondScreen(reset = false)
|
||||
val screen = com.droiddeck.launcher.ui.BottomGameScreen(this, shown, this, ::onBottomGameTouch)
|
||||
bottomGame = screen
|
||||
surfaceW = 0
|
||||
surfaceH = 0
|
||||
screen.setOnDismissListener {
|
||||
if (bottomGame === screen) {
|
||||
restoreTopOutput(screen)
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
}
|
||||
try {
|
||||
screen.show()
|
||||
} catch (e: Exception) {
|
||||
restoreTopOutput(screen)
|
||||
runCatching { screen.dismiss() }
|
||||
Log.w(TAG, "could not show the game on ${shown.name}", e)
|
||||
}
|
||||
if (bottomGame === screen) Log.i(TAG, "requested game output on the bottom screen (display ${shown.displayId})")
|
||||
}
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
|
||||
private fun cancelOutputTouches() {
|
||||
cancelTouchGestures()
|
||||
if (::directTouchHold.isInitialized) directTouchHold.cancel()
|
||||
if (::twoFingerGestures.isInitialized) twoFingerGestures.cancel()
|
||||
if (CompositorHost.isStarted && deliversTouches(routedTouchMode)) WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
|
||||
}
|
||||
|
||||
private fun recoverBottomOutput(screen: com.droiddeck.launcher.ui.BottomGameScreen) {
|
||||
if (bottomGame !== screen || bottomOutputActive || !started || screen.holder.surface?.isValid == true) return
|
||||
Log.i(TAG, "bottom screen surface gone - game back on the top screen")
|
||||
restoreTopOutput(screen)
|
||||
runCatching { screen.dismiss() }
|
||||
refreshSecondScreenDisplays()
|
||||
if (++bottomRecoveries <= BOTTOM_RECOVERY_TRIES) uiHandler.postDelayed({ updateBottomGame() }, BOTTOM_RECOVERY_MS)
|
||||
}
|
||||
|
||||
private fun restoreTopOutput(screen: com.droiddeck.launcher.ui.BottomGameScreen) {
|
||||
if (bottomGame !== screen) return
|
||||
bottomGame = null
|
||||
bottomOutputActive = false
|
||||
surfaceW = 0
|
||||
surfaceH = 0
|
||||
CompositorHost.detach(screen.holder.surface)
|
||||
if (glassesScreen != null) return
|
||||
surfaceView.visibility = View.VISIBLE
|
||||
applyOutputPacing()
|
||||
if (surfaceView.holder.surface?.isValid == true) surfaceCreated(surfaceView.holder)
|
||||
}
|
||||
|
||||
private fun onBottomGameTouch(event: MotionEvent): Boolean {
|
||||
if (pipUi) return true
|
||||
if (!event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) return false
|
||||
notePress(event)
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
|
||||
drawerControllerActive = false
|
||||
gestureTouchStreamGate.reset()
|
||||
}
|
||||
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SURFACE, event)) return false
|
||||
return onTouchEvent(event)
|
||||
}
|
||||
|
||||
@androidx.compose.runtime.Composable
|
||||
private fun SwappedTopPanel() {
|
||||
val pages = bottomPages()
|
||||
val swapBack = { putGameOnBottom(false) }
|
||||
androidx.compose.foundation.layout.Box(
|
||||
Modifier.fillMaxSize().background(androidx.compose.material3.MaterialTheme.colorScheme.background)
|
||||
.pointerInput(Unit) { awaitPointerEventScope { while (true) awaitPointerEvent() } },
|
||||
) {
|
||||
if (secondScreenMode == SecondScreenMode.DESKTOP && com.droiddeck.launcher.session.BottomDesktop.available()) {
|
||||
androidx.compose.ui.viewinterop.AndroidView(
|
||||
factory = { context ->
|
||||
com.droiddeck.launcher.ui.BottomDesktopPanel(context, null, { drawerOpen = true },
|
||||
(({ tapSteamButton() }) to ({ tapQam() })).takeIf { SessionState.mode == SessionService.MODE_STEAM }, swapBack,
|
||||
fullResolution = true)
|
||||
},
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
} else if (pages.isNotEmpty()) BottomDashboard(
|
||||
pages, com.droiddeck.launcher.ui.SessionBottomTab.picked(SessionState.sessionId),
|
||||
gameStarts = gameStarts,
|
||||
onPage = { com.droiddeck.launcher.ui.SessionBottomTab.pick(SessionState.sessionId, it) },
|
||||
onClose = null,
|
||||
onMenu = { drawerOpen = true },
|
||||
onSwap = swapBack,
|
||||
strip = { pageId ->
|
||||
com.droiddeck.launcher.ui.SessionBottomStrip(pageId) { if (::hud.isInitialized) hud.liveFps else null }
|
||||
},
|
||||
) else androidx.compose.material3.Button(onClick = swapBack, modifier = Modifier.align(androidx.compose.ui.Alignment.Center)) {
|
||||
androidx.compose.material3.Text(getString(R.string.swap_screens))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun glassesOutputSize(): Pair<Int, Int>? {
|
||||
if (glassesScreen == null || glasses.width <= 0 || glasses.height <= 0) return null
|
||||
val panel = (if (glasses.sbs) glasses.width / 2 else glasses.width) to glasses.height
|
||||
@@ -4393,6 +4609,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
runCatching { current.dismiss() }
|
||||
}
|
||||
if (target != null) {
|
||||
bottomGame?.let { restoreTopOutput(it); runCatching { it.dismiss() } }
|
||||
val screen = GlassesScreen(this, target, Glasses.outputHz(), this, Glasses.outputResolution())
|
||||
glassesScreen = screen
|
||||
applyOutputPacing()
|
||||
@@ -4418,6 +4635,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
applyOutputPacing()
|
||||
refreshSecondScreenDisplays()
|
||||
applyCardboard(cardboard)
|
||||
if (target == null) updateBottomGame()
|
||||
}
|
||||
|
||||
private fun onGlassesSteamVr(now: SteamVr.Status) {
|
||||
@@ -4529,6 +4747,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
closeSecondScreen(reset = false)
|
||||
glassesScope.cancel()
|
||||
glassesScreen?.let { screen -> glassesScreen = null; runCatching { screen.dismiss() } }
|
||||
bottomGame?.let { screen -> bottomGame = null; runCatching { screen.dismiss() } }
|
||||
headTracker?.stop()
|
||||
if (::hud.isInitialized) hud.stop()
|
||||
if (::memoryHud.isInitialized) memoryHud.stop()
|
||||
@@ -4614,6 +4833,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private const val PAUSED_FRAME_REDRAW_MS = 150L
|
||||
private const val SETTINGS_WATCH_MS = 1_000L
|
||||
private const val SETTINGS_WATCH_CHECKS = 600
|
||||
private const val BOTTOM_RECOVERY_MS = 1_000L
|
||||
private const val BOTTOM_RECOVERY_TRIES = 3
|
||||
private const val TAG = "SessionActivity"
|
||||
private var startedScreens = 0
|
||||
@Volatile private var activeInstallWorker: Any? = null
|
||||
|
||||
@@ -199,11 +199,15 @@ class DroidDeckHudHost(context: Context) {
|
||||
metrics.snapshot()
|
||||
Thread.sleep(500)
|
||||
val mango = metrics.snapshot()
|
||||
fun shown(value: Any?, unit: String) = if (value == null) "none" else "$value$unit"
|
||||
val readers = com.droiddeck.launcher.session.GpuStatsComponent.readerStatus()
|
||||
file.writeText(metrics.also { it.setMangoReadings(null) }.buildDiagnosticsReport(context) + "\n== As the HUD shows them (MangoHud's sources) ==\n" +
|
||||
"CPU ${mango.cpuPercent}% ${mango.cpuTempC}°C, GPU ${mango.gpuPercent}% ${mango.gpuClockMhz}MHz ${mango.gpuTempC}°C, " +
|
||||
"CPU ${shown(mango.cpuPercent, "%")} ${shown(mango.cpuTempC, "°C")}, GPU ${shown(mango.gpuPercent, "%")} " +
|
||||
"${shown(mango.gpuClockMhz, "MHz")} ${shown(mango.gpuTempC, "°C")}, " +
|
||||
"RAM ${mango.ramUsedText()}/${mango.ramTotalText()}, VRAM ${mango.vramText()}, battery ${mango.battery.percent}% " +
|
||||
"${mango.battery.watts}W charging=${mango.battery.charging}\n" +
|
||||
"GPU feeds: ${com.droiddeck.launcher.session.GpuStatsComponent.sources.ifEmpty { "none (no session, or kgsl absent)" }}\n" +
|
||||
(if (readers.isNotEmpty()) "GPU readers without root: $readers\n" else "") +
|
||||
"CPU temperature zones: ${LinuxRuntime.cpuTempZones().joinToString { it.name }}\n" +
|
||||
"Frames: ${if (feed.engine.isNotEmpty() || feed.pid > 0) "gamescope (pid ${feed.pid}, ${feed.engine})" else "compositor"}, " +
|
||||
"fps ${feed.stats.fps}\n")
|
||||
|
||||
@@ -125,6 +125,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
private var accent = 0xFF1A9FFF.toInt()
|
||||
private var surfaceRgb = 0x121417
|
||||
private var headerMark: RectF? = null
|
||||
private var headerWordmark: RectF? = null
|
||||
private var chipRect: RectF? = null
|
||||
|
||||
var dock = DroidDeckHudDock.NONE
|
||||
@@ -167,12 +168,9 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
color = colGraph
|
||||
}
|
||||
private val headerPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
|
||||
private val wordmarkPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
typeface = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD)
|
||||
}
|
||||
|
||||
private class Glyph(val x: Float, val baseline: Float, val text: String, val color: Int, val sizePx: Float, val sans: Boolean = false, val glow: Boolean = false) {
|
||||
fun moved(dx: Float, dy: Float) = Glyph(x + dx, baseline + dy, text, color, sizePx, sans, glow)
|
||||
private class Glyph(val x: Float, val baseline: Float, val text: String, val color: Int, val sizePx: Float, val glow: Boolean = false) {
|
||||
fun moved(dx: Float, dy: Float) = Glyph(x + dx, baseline + dy, text, color, sizePx, glow)
|
||||
}
|
||||
private class Span(val text: String, val color: Int, val sizePx: Float, val glow: Boolean = false)
|
||||
private class HudRow(val label: Span, val vals: List<Span>, val inline: Boolean = false)
|
||||
@@ -523,7 +521,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
|
||||
private fun rebuild() {
|
||||
glyphs.clear(); tileRects.clear(); graphRect = null
|
||||
headerMark = null; chipRect = null; dPanel = null; dDividerTop = -1f; tabRect = null; stripRect = null
|
||||
headerMark = null; headerWordmark = null; chipRect = null; dPanel = null; dDividerTop = -1f; tabRect = null; stripRect = null
|
||||
val s = snap
|
||||
if (s == null) { contentW = 0f; contentH = 0f; return }
|
||||
if (dock != DroidDeckHudDock.NONE) { buildDockTab(); return }
|
||||
@@ -576,24 +574,18 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
|
||||
private fun footerClock(): Boolean = showClockTime && size == DroidDeckHudSize.PILL
|
||||
|
||||
private fun measureSans(text: String, sizePx: Float): Float { wordmarkPaint.textSize = sizePx; return wordmarkPaint.measureText(text) }
|
||||
|
||||
private fun panelInset() = sp(8f)
|
||||
private fun panelLeft() = sp(13f)
|
||||
private fun contentLeft() = panelLeft() + sp(16f)
|
||||
|
||||
private fun addPanelHeader(left: Float, inner: Float): Pair<Float, Float> {
|
||||
val wordPx = sp(10f); val clockPx = sp(9.5f); val gapH = sp(7f)
|
||||
wordmarkPaint.textSize = wordPx
|
||||
val markH = wordmarkPaint.fontMetrics.let { it.descent - it.ascent } * 0.95f
|
||||
val clockPx = sp(9.5f); val gapH = sp(7f)
|
||||
val wordH = sp(12f)
|
||||
val markTop = inner + gapH
|
||||
val markLeft = left - DroidDeckMark.inkLeftFor(markH)
|
||||
headerMark = RectF(markLeft, markTop, markLeft + DroidDeckMark.widthFor(markH), markTop + markH)
|
||||
val midY = markTop + markH / 2f
|
||||
var x = markLeft + DroidDeckMark.inkRightFor(markH) + sp(6f)
|
||||
wordmarkPaint.getTextBounds("DroidDeck", 0, 9, inkRect)
|
||||
glyphs.add(Glyph(x, midY - inkRect.exactCenterY(), "DroidDeck", blend(colValue), wordPx, sans = true))
|
||||
x += measureSans("DroidDeck", wordPx)
|
||||
val wordW = WordmarkArt.widthFor(wordH)
|
||||
headerWordmark = RectF(left, markTop, left + wordW, markTop + wordH)
|
||||
val midY = markTop + wordH / 2f
|
||||
var x = left + wordW
|
||||
if (showClockTime) {
|
||||
measurePaint.textSize = clockPx
|
||||
measurePaint.getTextBounds("0", 0, 1, inkRect)
|
||||
@@ -605,7 +597,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
glyphs.add(Glyph(x, base, t, blend(colDim), clockPx))
|
||||
x += measure(t, clockPx)
|
||||
}
|
||||
dDividerTop = markTop + markH + gapH
|
||||
dDividerTop = markTop + wordH + gapH
|
||||
return Pair(dDividerTop + max(1f, density), x)
|
||||
}
|
||||
|
||||
@@ -647,7 +639,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
}
|
||||
var right = panel.right
|
||||
for (g in glyphs) {
|
||||
val paint = if (g.sans) wordmarkPaint else measurePaint
|
||||
val paint = measurePaint
|
||||
paint.textSize = g.sizePx
|
||||
paint.getTextBounds(g.text, 0, g.text.length, inkRect)
|
||||
if (inkRect.isEmpty) continue
|
||||
@@ -1323,7 +1315,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
stripRect?.let { drawStrip(canvas, it) }
|
||||
|
||||
for (g in glyphs) {
|
||||
val paint = if (g.sans) wordmarkPaint else drawPaint
|
||||
val paint = drawPaint
|
||||
paint.textSize = g.sizePx
|
||||
paint.color = g.color
|
||||
if (g.glow) paint.setShadowLayer(sp(6f), 0f, 0f, withAlpha(colGraph, 217))
|
||||
@@ -1331,6 +1323,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
if (g.glow) paint.clearShadowLayer()
|
||||
}
|
||||
headerMark?.let { DroidDeckMark.draw(canvas, it.left, it.top, it.height(), blend(colValue), accent) }
|
||||
headerWordmark?.let { WordmarkArt.draw(canvas, it.left, it.top, it.height(), blend(colValue), accent) }
|
||||
|
||||
graphRect?.let { drawGraph(canvas, it) }
|
||||
|
||||
@@ -1420,10 +1413,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
headerPaint.color = withAlpha(accent, 90)
|
||||
c.drawRect(panel.left, dDividerTop, roundEdgeX(panel, dDividerTop, stroke), dividerBottom, headerPaint)
|
||||
}
|
||||
val halfRound = dRadius >= panel.height() / 2f - 0.5f
|
||||
val wmH = if (halfRound) panel.height() * 0.92f else min(panel.height(), panel.width()) * 0.55f
|
||||
DroidDeckMark.draw(c, panel.right - DroidDeckMark.widthFor(wmH) - (if (halfRound) panel.height() * 0.02f else sp(10f)),
|
||||
panel.centerY() - wmH / 2f, wmH, Color.argb(20, 255, 255, 255), withAlpha(accent, 20))
|
||||
c.restore()
|
||||
if (stroke > 0f) {
|
||||
val h = stroke / 2f
|
||||
@@ -1487,10 +1476,10 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
internal val isDragging: Boolean get() = lockController.isDragging() || tabDragging
|
||||
|
||||
private companion object {
|
||||
const val TAB_NUM_SP = 10f
|
||||
const val TAB_LABEL_SP = 6f
|
||||
const val TAB_PAD_X_SP = 5f
|
||||
const val TAB_PAD_Y_SP = 4f
|
||||
const val TAB_NUM_SP = 15f
|
||||
const val TAB_LABEL_SP = 7.25f
|
||||
const val TAB_PAD_X_SP = 7f
|
||||
const val TAB_PAD_Y_SP = 5.5f
|
||||
const val REFRESH_MS = 500L
|
||||
private const val HUE_IDLE_MS = 500L
|
||||
const val MIN_SCALE = 0.5f
|
||||
|
||||
@@ -870,6 +870,9 @@ public class HudMetrics {
|
||||
|
||||
private long[] lastCoreTotal = null;
|
||||
private long[] lastCoreIdle = null;
|
||||
private static final int PER_CORE_STAT = 1, PER_CORE_ESTIMATE = 2;
|
||||
/** Sources of the last per-core reading: PER_CORE_STAT and/or PER_CORE_ESTIMATE (clock speed); 0 when no core was read. */
|
||||
private volatile int perCoreSources = 0;
|
||||
|
||||
public int[] readPerCorePercent() {
|
||||
int cores = Runtime.getRuntime().availableProcessors();
|
||||
@@ -909,13 +912,20 @@ public class HudMetrics {
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {}
|
||||
int sources = 0;
|
||||
for (int i = 0; i < out.length; i++) {
|
||||
if (out[i] >= 0) continue;
|
||||
if (out[i] >= 0) {
|
||||
sources |= PER_CORE_STAT;
|
||||
continue;
|
||||
}
|
||||
Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq");
|
||||
Long max = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/cpuinfo_max_freq");
|
||||
if (cur != null && max != null && max > 0L)
|
||||
if (cur != null && max != null && max > 0L) {
|
||||
out[i] = clampPercent((int) ((Math.max(0L, Math.min(cur, max)) * 100L) / max));
|
||||
sources |= PER_CORE_ESTIMATE;
|
||||
}
|
||||
}
|
||||
perCoreSources = sources;
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -1008,10 +1018,13 @@ public class HudMetrics {
|
||||
int v = s.perCorePercent[i];
|
||||
cores.append('c').append(i).append('=').append(v < 0 ? "?" : (v + "%"));
|
||||
}
|
||||
if (s.perCorePercent.length > 0)
|
||||
metricHit(sb, "Per-core %", cores.toString(), "/proc/stat (per-cpu lines)");
|
||||
int coreSources = perCoreSources;
|
||||
if (s.perCorePercent.length > 0 && coreSources != 0)
|
||||
metricHit(sb, "Per-core %", cores.toString(), coreSources == PER_CORE_STAT ? "/proc/stat (per-cpu lines)"
|
||||
: coreSources == PER_CORE_ESTIMATE ? "scaling_cur_freq / cpuinfo_max_freq (clock estimate)"
|
||||
: "/proc/stat (per-cpu lines); scaling_cur_freq / cpuinfo_max_freq (clock estimate) for the other cores");
|
||||
else
|
||||
metricMiss(sb, "Per-core %", "/proc/stat");
|
||||
metricMiss(sb, "Per-core %", "/proc/stat", "/sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq");
|
||||
|
||||
StringBuilder coreClk = new StringBuilder();
|
||||
for (int i = 0; i < s.perCoreClockMhz.length; i++) {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Path
|
||||
import androidx.compose.ui.graphics.asAndroidPath
|
||||
import androidx.compose.ui.graphics.vector.PathParser
|
||||
|
||||
internal object WordmarkArt {
|
||||
const val BOX_X = 239.135f
|
||||
const val BOX_Y = 120.02f
|
||||
const val BOX_W = 1040.7f - 239.135f
|
||||
const val BOX_H = 243.2f - 120.02f
|
||||
const val MARK_SCALE = 0.527445f
|
||||
|
||||
const val LEFT_HALF = "M-31.98 0H56.055V40.489A71.81 71.81 0 0 0 56.055 183.231V223.72H-31.98Z"
|
||||
const val RIGHT_HALF = "M71.885 0.28A111.86 111.86 0 0 1 71.885 223.44V183.234A71.81 71.81 0 0 0 71.885 40.486Z"
|
||||
const val LETTERS =
|
||||
"M361.45 241.36V160.13H387.02V241.36ZM387.02 196.73 376.32 188.38Q379.5 174.17 387.02 166.31Q394.54 158.46 407.91 158.46Q413.76 158.46 418.19 160.21Q422.62 161.97 425.96 165.65L410.75 184.87Q409.08 183.03 406.57 182.03Q404.07 181.02 400.89 181.02Q394.54 181.02 390.78 184.95Q387.02 188.88 387.02 196.73" +
|
||||
"ZM467.91 243.2Q455.38 243.2 445.27 237.6Q435.15 232 429.3 222.31Q423.45 212.61 423.45 200.58Q423.45 188.54 429.3 179.02Q435.15 169.49 445.18 163.89Q455.21 158.29 467.91 158.29Q480.62 158.29 490.64 163.81Q500.67 169.32 506.52 178.93Q512.37 188.54 512.37 200.58Q512.37 212.61 506.52 222.31Q500.67 232 490.64 237.6Q480.62 243.2 467.91 243.2" +
|
||||
"ZM467.91 219.97Q473.43 219.97 477.61 217.54Q481.79 215.12 484.04 210.69Q486.3 206.26 486.3 200.58Q486.3 194.9 483.96 190.63Q481.62 186.37 477.52 183.95Q473.43 181.52 467.91 181.52Q462.56 181.52 458.39 183.95Q454.21 186.37 451.87 190.72Q449.53 195.06 449.53 200.75Q449.53 206.26 451.87 210.69Q454.21 215.12 458.39 217.54Q462.56 219.97 467.91 219.97" +
|
||||
"ZM523.4 241.36V160.13H548.98V241.36ZM536.27 148.93Q530.26 148.93 526.33 144.84Q522.4 140.74 522.4 134.89Q522.4 128.88 526.33 124.86Q530.26 120.85 536.27 120.85Q542.29 120.85 546.13 124.86Q549.98 128.88 549.98 134.89Q549.98 140.74 546.13 144.84Q542.29 148.93 536.27 148.93ZM599.95 243.03Q588.42 243.03 579.48 237.52Q570.54 232 565.44 222.47Q560.34 212.95 560.34 200.75Q560.34 188.54 565.44 179.02Q570.54 169.49 579.48 163.97Q588.42 158.46 599.95 158.46Q608.31 158.46 615.08 161.63Q621.85 164.81 626.28 170.41Q630.71 176.01 631.21 183.2V217.46Q630.71 224.65 626.36 230.41Q622.02 236.18 615.16 239.61Q608.31 243.03 599.95 243.03" +
|
||||
"ZM604.47 219.97Q609.98 219.97 613.99 217.54Q618 215.12 620.34 210.77Q622.68 206.43 622.68 200.75Q622.68 195.06 620.43 190.8Q618.17 186.54 614.08 184.03Q609.98 181.52 604.63 181.52Q599.28 181.52 595.19 184.03Q591.09 186.54 588.67 190.88Q586.25 195.23 586.25 200.75Q586.25 206.26 588.59 210.61Q590.93 214.95 595.11 217.46Q599.28 219.97 604.47 219.97" +
|
||||
"ZM646.75 241.36H621.68V219.46L625.53 199.74L621.18 180.02V120.02H646.75ZM683.19 241.36V218.29H712.44Q723.13 218.29 731.16 214.03Q739.18 209.77 743.53 201.58Q747.87 193.39 747.87 182.19Q747.87 170.99 743.44 162.97Q739.01 154.95 731.07 150.6Q723.13 146.26 712.44 146.26H682.35V123.36H712.77Q726.14 123.36 737.42 127.62Q748.71 131.88 757.15 139.82Q765.59 147.76 770.18 158.54Q774.78 169.32 774.78 182.36Q774.78 195.23 770.18 206.09Q765.59 216.96 757.23 224.81Q748.87 232.67 737.59 237.01Q726.31 241.36 713.11 241.36" +
|
||||
"ZM665.47 241.36V123.36H691.71V241.36ZM827.6 243.2Q814.39 243.2 804.11 237.77Q793.83 232.33 787.98 222.64Q782.13 212.95 782.13 200.75Q782.13 188.54 787.9 178.93Q793.67 169.32 803.53 163.81Q813.39 158.29 825.76 158.29Q837.79 158.29 846.98 163.47Q856.18 168.65 861.44 177.85Q866.71 187.04 866.71 198.91Q866.71 201.08 866.46 203.5Q866.21 205.93 865.54 209.1L795.51 209.27V191.72L854.67 191.55L843.64 198.91Q843.47 191.89 841.47 187.29Q839.46 182.69 835.54 180.27Q831.61 177.85 825.92 177.85Q819.91 177.85 815.48 180.61Q811.05 183.36 808.63 188.38Q806.2 193.39 806.2 200.58Q806.2 207.77 808.79 212.86Q811.38 217.96 816.15 220.72Q820.91 223.48 827.43 223.48Q833.45 223.48 838.29 221.39Q843.14 219.3 846.82 215.12L860.86 229.16Q854.84 236.18 846.32 239.69Q837.79 243.2 827.6 243.2" +
|
||||
"ZM916.68 243.2Q904.15 243.2 893.95 237.68Q883.75 232.17 877.9 222.47Q872.05 212.78 872.05 200.75Q872.05 188.54 877.99 178.93Q883.92 169.32 894.12 163.81Q904.31 158.29 917.02 158.29Q926.54 158.29 934.48 161.55Q942.42 164.81 948.6 171.33L932.22 187.71Q929.38 184.53 925.62 183.03Q921.86 181.52 917.02 181.52Q911.5 181.52 907.24 183.95Q902.98 186.37 900.55 190.63Q898.13 194.9 898.13 200.58Q898.13 206.26 900.55 210.61Q902.98 214.95 907.32 217.46Q911.67 219.97 917.02 219.97Q922.03 219.97 925.96 218.21Q929.88 216.46 932.73 213.28L948.94 229.66Q942.59 236.35 934.56 239.77Q926.54 243.2 916.68 243.2" +
|
||||
"ZM1010.61 241.36 982.2 199.24 1010.45 160.13H1039.03L1004.93 204.09L1005.77 193.56L1040.7 241.36ZM958.63 241.36V120.02H984.21V241.36Z"
|
||||
|
||||
private fun parse(d: String): Path = PathParser().parsePathString(d).toPath().asAndroidPath()
|
||||
private val letters by lazy { parse(LETTERS) }
|
||||
private val leftHalf by lazy { parse(LEFT_HALF) }
|
||||
private val rightHalf by lazy { parse(RIGHT_HALF) }
|
||||
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
|
||||
|
||||
fun widthFor(height: Float): Float = height * BOX_W / BOX_H
|
||||
|
||||
fun draw(canvas: Canvas, left: Float, top: Float, height: Float, inkColor: Int, ballColor: Int) {
|
||||
val k = height / BOX_H
|
||||
canvas.save()
|
||||
canvas.translate(left, top)
|
||||
canvas.scale(k, k)
|
||||
canvas.translate(-BOX_X, -BOX_Y)
|
||||
paint.color = inkColor
|
||||
canvas.drawPath(letters, paint)
|
||||
canvas.translate(239.135f, 123.36f)
|
||||
canvas.scale(MARK_SCALE, MARK_SCALE)
|
||||
canvas.translate(31.98f, 0f)
|
||||
canvas.drawPath(leftHalf, paint)
|
||||
canvas.drawPath(rightHalf, paint)
|
||||
paint.color = ballColor
|
||||
canvas.drawCircle(63.98f, 111.86f, 55.98f, paint)
|
||||
canvas.restore()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.accessibilityservice.AccessibilityService
|
||||
import android.accessibilityservice.AccessibilityServiceInfo
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.graphics.Rect
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.util.Log
|
||||
import android.view.Display
|
||||
import android.view.accessibility.AccessibilityEvent
|
||||
import android.view.accessibility.AccessibilityWindowInfo
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
object BottomScreenGuests {
|
||||
enum class Top { HOME, GUEST, NONE }
|
||||
|
||||
internal const val MIN_COVER = 0.5f
|
||||
|
||||
internal fun classify(pkg: String?, homes: Set<String>): Top = when (pkg) {
|
||||
null -> Top.NONE
|
||||
in homes -> Top.HOME
|
||||
else -> Top.GUEST
|
||||
}
|
||||
|
||||
internal fun holder(topPkg: String?, arrival: String?, homes: Set<String>): String? = when {
|
||||
topPkg != null -> topPkg.takeIf { classify(it, homes) == Top.GUEST }
|
||||
arrival != null -> arrival.takeIf { classify(it, homes) == Top.GUEST }
|
||||
else -> null
|
||||
}
|
||||
|
||||
internal fun ignorable(type: Int): Boolean = type == AccessibilityWindowInfo.TYPE_INPUT_METHOD ||
|
||||
type == AccessibilityWindowInfo.TYPE_ACCESSIBILITY_OVERLAY ||
|
||||
type == AccessibilityWindowInfo.TYPE_SPLIT_SCREEN_DIVIDER ||
|
||||
type == AccessibilityWindowInfo.TYPE_MAGNIFICATION_OVERLAY
|
||||
|
||||
fun supported(model: String = Build.MODEL, sdk: Int = Build.VERSION.SDK_INT): Boolean =
|
||||
sdk >= 33 && DualScreen.yieldsBottom(model)
|
||||
}
|
||||
|
||||
class BottomScreenWatch(private val service: AccessibilityService) {
|
||||
private class Arrival(val pkg: String)
|
||||
|
||||
private val thread = HandlerThread("bottom-screen").apply { start() }
|
||||
private val handler = Handler(thread.looper)
|
||||
private val own = service.packageName
|
||||
private val arrivals = ConcurrentHashMap<Int, Arrival>()
|
||||
private var homes: Set<String> = emptySet()
|
||||
private var keyboards: Set<String> = emptySet()
|
||||
private var holders: Map<Int, String?> = emptyMap()
|
||||
private val check = Runnable { evaluate() }
|
||||
|
||||
fun start() {
|
||||
current = this
|
||||
service.serviceInfo = service.serviceInfo?.apply {
|
||||
eventTypes = eventTypes or AccessibilityEvent.TYPE_WINDOWS_CHANGED or AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
|
||||
flags = flags or AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS
|
||||
}
|
||||
handler.post {
|
||||
homes = homePackages()
|
||||
keyboards = keyboardPackages()
|
||||
evaluate()
|
||||
}
|
||||
}
|
||||
|
||||
fun onEvent(event: AccessibilityEvent) {
|
||||
when (event.eventType) {
|
||||
AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> {
|
||||
val pkg = event.packageName?.toString() ?: return
|
||||
if (event.displayId == Display.DEFAULT_DISPLAY || pkg == own || pkg == SYSTEM_UI) return
|
||||
arrivals[event.displayId] = Arrival(pkg)
|
||||
}
|
||||
AccessibilityEvent.TYPE_WINDOWS_CHANGED -> Unit
|
||||
else -> return
|
||||
}
|
||||
handler.removeCallbacks(check)
|
||||
handler.postDelayed(check, 150)
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
handler.removeCallbacksAndMessages(null)
|
||||
handler.post {
|
||||
if (current === this) {
|
||||
current = null
|
||||
DualScreen.setTaken(emptySet())
|
||||
}
|
||||
}
|
||||
thread.quitSafely()
|
||||
}
|
||||
|
||||
private fun evaluate() {
|
||||
val seen = HashMap(arrivals)
|
||||
val all = runCatching { service.windowsOnAllDisplays }.getOrNull() ?: return
|
||||
val displays = service.getSystemService(DisplayManager::class.java) ?: return
|
||||
val taken = mutableMapOf<Int, String?>()
|
||||
for (i in 0 until all.size()) {
|
||||
val id = all.keyAt(i)
|
||||
if (id == Display.DEFAULT_DISPLAY) continue
|
||||
val display = displays.getDisplay(id)?.takeIf(DualScreen::builtIn) ?: continue
|
||||
val windows = all.valueAt(i)
|
||||
val topPkg = windows.asSequence()
|
||||
.filter { !BottomScreenGuests.ignorable(it.type) && cover(it, display) >= BottomScreenGuests.MIN_COVER }
|
||||
.sortedByDescending { it.layer }
|
||||
.firstNotNullOfOrNull { packageOf(it)?.takeUnless { pkg -> pkg == own } }
|
||||
val arrival = seen[id]
|
||||
if (topPkg != null && arrival != null) arrivals.remove(id, arrival)
|
||||
BottomScreenGuests.holder(topPkg, arrival?.pkg?.takeUnless { it in keyboards }, homes)?.let { taken[id] = it }
|
||||
}
|
||||
if (current !== this) return
|
||||
if (taken != holders) Log.i(TAG, "bottom screen holders: $taken")
|
||||
holders = taken
|
||||
DualScreen.setTaken(taken.keys)
|
||||
}
|
||||
|
||||
private fun cover(window: AccessibilityWindowInfo, display: Display): Float {
|
||||
val bounds = Rect().also(window::getBoundsInScreen)
|
||||
val area = display.mode.physicalWidth.toFloat() * display.mode.physicalHeight
|
||||
return if (area <= 0f) 0f else bounds.width().toFloat() * bounds.height() / area
|
||||
}
|
||||
|
||||
private fun packageOf(window: AccessibilityWindowInfo): String? =
|
||||
runCatching { window.getRoot(0)?.packageName?.toString() }.getOrNull()
|
||||
|
||||
private fun homePackages(): Set<String> {
|
||||
val pm = service.packageManager
|
||||
return listOf(Intent.CATEGORY_HOME, Intent.CATEGORY_SECONDARY_HOME).flatMap { category ->
|
||||
runCatching {
|
||||
pm.queryIntentActivities(Intent(Intent.ACTION_MAIN).addCategory(category), PackageManager.MATCH_ALL)
|
||||
.filter { it.priority >= 0 }
|
||||
.mapNotNull { it.activityInfo?.packageName }
|
||||
}.getOrDefault(emptyList())
|
||||
}.toSet()
|
||||
}
|
||||
|
||||
private fun keyboardPackages(): Set<String> =
|
||||
runCatching {
|
||||
service.getSystemService(InputMethodManager::class.java)?.inputMethodList.orEmpty().map { it.packageName }.toSet()
|
||||
}.getOrDefault(emptySet())
|
||||
|
||||
private companion object {
|
||||
@Volatile var current: BottomScreenWatch? = null
|
||||
const val TAG = "BottomScreen"
|
||||
const val SYSTEM_UI = "com.android.systemui"
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,23 @@ object DualScreen {
|
||||
private const val TYPE_INTERNAL = 1
|
||||
private val knownModels = setOf("retroid pocket duo", "ayn thor")
|
||||
private val touchedDisplays = mutableSetOf<Int>()
|
||||
private val takenListeners = java.util.concurrent.CopyOnWriteArraySet<() -> Unit>()
|
||||
@Volatile private var takenDisplays: Set<Int> = emptySet()
|
||||
private val main by lazy { android.os.Handler(android.os.Looper.getMainLooper()) }
|
||||
|
||||
fun yieldsBottom(model: String): Boolean = model.trim().lowercase().let { m -> knownModels.any(m::startsWith) }
|
||||
|
||||
fun taken(displayId: Int): Boolean = displayId in takenDisplays
|
||||
|
||||
fun setTaken(ids: Set<Int>) {
|
||||
if (ids == takenDisplays) return
|
||||
takenDisplays = ids
|
||||
main.post { takenListeners.forEach { it() } }
|
||||
}
|
||||
|
||||
fun watchTaken(listener: () -> Unit) { takenListeners += listener }
|
||||
|
||||
fun unwatchTaken(listener: () -> Unit) { takenListeners -= listener }
|
||||
|
||||
fun builtInDisplay(displayManager: DisplayManager, primaryDisplayId: Int): Display? {
|
||||
val primary = displayManager.getDisplay(primaryDisplayId)
|
||||
@@ -61,20 +78,25 @@ object DualScreen {
|
||||
(x.max - x.min + 1f).roundToInt() to (y.max - y.min + 1f).roundToInt()
|
||||
}
|
||||
|
||||
fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int): Display? =
|
||||
when (SessionPrefs.dualScreenMode(context)) {
|
||||
fun sessionDisplay(context: Context, displayManager: DisplayManager, primaryDisplayId: Int): Display? =
|
||||
display(context, displayManager, primaryDisplayId, SessionPrefs.dualScreenSessionMode(context))
|
||||
|
||||
fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, mode: String = SessionPrefs.dualScreenMode(context)): Display? =
|
||||
when (mode) {
|
||||
MODE_OFF -> null
|
||||
MODE_ON -> internalDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
|
||||
else -> builtInDisplay(displayManager, primaryDisplayId)
|
||||
}
|
||||
}?.takeUnless { taken(it.displayId) }
|
||||
|
||||
fun anyDisplay(displayManager: DisplayManager, primaryDisplayId: Int): Display? =
|
||||
displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION).firstOrNull {
|
||||
it.isValid && it.displayId != primaryDisplayId && (it.flags and Display.FLAG_PRESENTATION) != 0
|
||||
}
|
||||
|
||||
fun builtIn(display: Display): Boolean = isBuiltIn(displayType(display), Build.MODEL)
|
||||
|
||||
internal fun isBuiltIn(type: Int?, model: String): Boolean =
|
||||
if (type != null) type == TYPE_INTERNAL else model.trim().lowercase() in knownModels
|
||||
if (type != null) type == TYPE_INTERNAL else yieldsBottom(model)
|
||||
|
||||
private fun displayType(display: Display): Int? =
|
||||
runCatching { Display::class.java.getMethod("getType").invoke(display) as Int }.getOrNull()
|
||||
|
||||
@@ -46,12 +46,20 @@ object HomeButtonShortcuts {
|
||||
}
|
||||
|
||||
class HomeButtonService : AccessibilityService(), InputManager.InputDeviceListener {
|
||||
private var bottomScreen: BottomScreenWatch? = null
|
||||
|
||||
override fun onServiceConnected() {
|
||||
getSystemService(InputManager::class.java).registerInputDeviceListener(this, Handler(Looper.getMainLooper()))
|
||||
if (bottomScreen == null && BottomScreenGuests.supported()) bottomScreen = BottomScreenWatch(this).also { it.start() }
|
||||
}
|
||||
|
||||
private fun stopBottomScreen() {
|
||||
bottomScreen?.stop()
|
||||
bottomScreen = null
|
||||
}
|
||||
|
||||
override fun onKeyEvent(event: KeyEvent) = HomeButtonShortcuts.onKeyEvent(this, event)
|
||||
override fun onAccessibilityEvent(event: AccessibilityEvent?) {}
|
||||
override fun onAccessibilityEvent(event: AccessibilityEvent?) { event?.let { bottomScreen?.onEvent(it) } }
|
||||
override fun onInterrupt() { HomeButtonShortcuts.release() }
|
||||
override fun onInputDeviceAdded(deviceId: Int) {}
|
||||
override fun onInputDeviceChanged(deviceId: Int) {}
|
||||
@@ -59,12 +67,14 @@ class HomeButtonService : AccessibilityService(), InputManager.InputDeviceListen
|
||||
|
||||
override fun onUnbind(intent: Intent?): Boolean {
|
||||
HomeButtonShortcuts.release()
|
||||
stopBottomScreen()
|
||||
com.droiddeck.launcher.core.SteamIntegration.syncShortcutsListing(this)
|
||||
return super.onUnbind(intent)
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
HomeButtonShortcuts.release()
|
||||
stopBottomScreen()
|
||||
getSystemService(InputManager::class.java).unregisterInputDeviceListener(this)
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@@ -17,13 +17,14 @@ object BattleNet {
|
||||
|
||||
const val PROGRAM = "/usr/local/bin/droiddeck-battlenet"
|
||||
|
||||
class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null, val product: String? = null)
|
||||
class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null, val product: String? = null, val flavor: String? = null)
|
||||
|
||||
internal val TITLES = listOf(
|
||||
Title("wow", "World of Warcraft", "WoW", shop = "world-of-warcraft-midnight", product = "wow"),
|
||||
Title("wow_classic", "World of Warcraft Classic", "WoWC", shop = "world-of-warcraft-burning-crusade-classic-anniversary-edition-upgrades", product = "wow_classic"),
|
||||
Title("wow_classic_era", "World of Warcraft Classic", "WoWC", product = "wow_classic_era"),
|
||||
Title("wow_classic_anniversary", "World of Warcraft Classic", "WoWC", product = "wow_anniversary"),
|
||||
Title("wow", "World of Warcraft", "WoW", shop = "world-of-warcraft-midnight", product = "wow", flavor = "_retail_"),
|
||||
Title("wow_classic", "World of Warcraft Classic", "WoWC", shop = "world-of-warcraft-burning-crusade-classic-anniversary-edition-upgrades", product = "wow_classic", flavor = "_classic_"),
|
||||
Title("wow_classic_era", "World of Warcraft Classic", "WoWC", product = "wow_classic_era", flavor = "_classic_era_"),
|
||||
Title("wow_classic_anniversary", "World of Warcraft Classic", "WoWC", product = "wow_anniversary", flavor = "_anniversary_"),
|
||||
Title("wow_forever", "World of Warcraft: Forever", "WoWF", shop = "world-of-warcraft-forever", product = "wowf", flavor = "_forever_"),
|
||||
Title("diablo3", "Diablo III", "D3", shop = "diablo-iii", product = "d3"),
|
||||
Title("d3cn", "Diablo III", "D3CN", shop = "diablo-iii"),
|
||||
Title("s2", "StarCraft II", "S2", shop = "starcraft-ii", product = "s2"),
|
||||
@@ -58,7 +59,7 @@ object BattleNet {
|
||||
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"),
|
||||
)
|
||||
|
||||
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" }
|
||||
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" && it.code != "WoWF" }
|
||||
|
||||
fun notInstalled(title: Title, installedIds: Collection<String?>) =
|
||||
installedIds.mapNotNull { id -> id?.let(::title)?.code }.none { it == title.code }
|
||||
@@ -159,24 +160,56 @@ object BattleNet {
|
||||
return if (base.isNotEmpty() && id.substringAfterLast('_') in LOCALES) TITLES.firstOrNull { it.uid == base } else null
|
||||
}
|
||||
|
||||
internal fun titleForProduct(product: String): Title? {
|
||||
val code = product.trim()
|
||||
if (code.isEmpty()) return null
|
||||
return TITLES.firstOrNull { it.product.equals(code, ignoreCase = true) } ?: TITLES.firstOrNull { it.code.equals(code, ignoreCase = true) }
|
||||
}
|
||||
|
||||
fun games(context: Context): List<Game> {
|
||||
val pfx = File(prefix(context), "pfx")
|
||||
val agent = runCatching { productDbInstalls(File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").readBytes()) }.getOrNull()
|
||||
val entries = installs(
|
||||
runCatching { File(pfx, "system.reg").useLines { uninstallEntries(it) } }.getOrDefault(emptyList()),
|
||||
runCatching { productDbEntries(File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").readBytes()) }.getOrNull(),
|
||||
agent?.map { it.uid to it.path },
|
||||
)
|
||||
val found = LinkedHashMap<String, Game>()
|
||||
val products = agent.orEmpty().filter { it.product.isNotEmpty() }.associate { it.uid.lowercase() to it.product }
|
||||
val listed = LinkedHashMap<String, Triple<Title, String, File>>()
|
||||
for ((uid, path) in entries) {
|
||||
val title = title(uid)
|
||||
val title = title(uid) ?: products[uid.lowercase()]?.let(::titleForProduct)
|
||||
if (title == null) {
|
||||
if (uid.lowercase() !in NOT_GAMES) Log.i(TAG, "not listed: $uid (no launch code known)")
|
||||
continue
|
||||
}
|
||||
if (title.code in found) continue
|
||||
if (title.code in listed) continue
|
||||
val folder = hostFolder(context, path)?.takeIf { it.isDirectory } ?: continue
|
||||
found[title.code] = Game(title.uid, title.name, title.code, folder, uid)
|
||||
listed[title.code] = Triple(title, uid, folder)
|
||||
}
|
||||
return found.values.toList()
|
||||
val saved = listed.mapValues { (code, _) -> com.droiddeck.launcher.session.SessionPrefs.battleNetFolder(context, code) }
|
||||
val folders = ownFolders(listed.mapValues { it.value.first to it.value.third }, saved)
|
||||
return listed.map { (code, found) ->
|
||||
val folder = folders.getValue(code)
|
||||
if (saved[code] != folder.path) com.droiddeck.launcher.session.SessionPrefs.setBattleNetFolder(context, code, folder.path)
|
||||
Game(found.first.uid, found.first.name, code, folder, found.second)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun ownFolders(games: Map<String, Pair<Title, File>>, saved: Map<String, String?>): Map<String, File> {
|
||||
val out = HashMap<String, File>()
|
||||
val taken = HashSet<File>()
|
||||
fun options(title: Title, folder: File) = listOfNotNull(folder, title.flavor?.let { File(folder, it) }?.takeIf { it.isDirectory })
|
||||
for ((code, game) in games) {
|
||||
val keep = saved[code]?.let(::File)?.takeIf { it in options(game.first, game.second) && it !in taken } ?: continue
|
||||
out[code] = keep
|
||||
taken.add(keep)
|
||||
}
|
||||
for ((code, game) in games) {
|
||||
if (code in out) continue
|
||||
val pick = options(game.first, game.second).firstOrNull { it !in taken } ?: game.second
|
||||
out[code] = pick
|
||||
taken.add(pick)
|
||||
}
|
||||
return games.keys.associateWith { out.getValue(it) }
|
||||
}
|
||||
|
||||
internal fun installs(registry: List<Pair<String, String>>, agent: List<Pair<String, String>>?): List<Pair<String, String>> {
|
||||
@@ -250,17 +283,22 @@ object BattleNet {
|
||||
return out.toString()
|
||||
}
|
||||
|
||||
internal fun productDbEntries(bytes: ByteArray): List<Pair<String, String>>? {
|
||||
internal class AgentInstall(val uid: String, val path: String, val product: String)
|
||||
|
||||
internal fun productDbEntries(bytes: ByteArray): List<Pair<String, String>>? = productDbInstalls(bytes)?.map { it.uid to it.path }
|
||||
|
||||
internal fun productDbInstalls(bytes: ByteArray): List<AgentInstall>? {
|
||||
val installs = runCatching { fields(bytes, 0, bytes.size) }.getOrNull()?.filter { it.first == 1 }?.takeIf { it.isNotEmpty() } ?: return null
|
||||
return installs.map { (_, start, end) ->
|
||||
runCatching {
|
||||
val install = fields(bytes, start, end)
|
||||
val uid = install.firstOrNull { it.first == 1 }?.let { String(bytes, it.second, it.third - it.second) }
|
||||
val product = install.firstOrNull { it.first == 2 }?.let { String(bytes, it.second, it.third - it.second) }.orEmpty()
|
||||
val path = install.firstOrNull { it.first == 3 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } }
|
||||
?.let { String(bytes, it.second, it.third - it.second) }
|
||||
val installed = install.firstOrNull { it.first == 4 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } }
|
||||
?.let { s -> varints(bytes, s.second, s.third)[1] }
|
||||
if (uid.isNullOrEmpty() || path.isNullOrEmpty() || installed == 0L) null else uid to path
|
||||
if (uid.isNullOrEmpty() || path.isNullOrEmpty() || installed == 0L) null else AgentInstall(uid, path, product)
|
||||
}.getOrElse { return null }
|
||||
}.filterNotNull()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.core.Hashes
|
||||
import com.droiddeck.launcher.session.DesktopLocale
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
|
||||
object DesktopLanguage {
|
||||
private const val TAG = "DesktopLanguage"
|
||||
private const val INDEX = "desktop-kde.i18n.txt"
|
||||
private const val ABSENT = "absent"
|
||||
|
||||
class Pack(val locale: String, val sha256: String, val size: Long)
|
||||
|
||||
internal fun parseIndex(text: String): Map<String, Pack> = text.lineSequence().mapNotNull { line ->
|
||||
val parts = line.trim().split(' ')
|
||||
if (parts.size != 3 || !parts[0].matches(Regex("[A-Za-z_]+")) || !parts[1].matches(Regex("[0-9a-fA-F]{64}"))) return@mapNotNull null
|
||||
Pack(parts[0], parts[1], parts[2].toLongOrNull() ?: return@mapNotNull null)
|
||||
}.associateBy { it.locale }
|
||||
|
||||
/** KDE ships region packs (pt_BR, zh_TW) beside bare-language ones (pt, es). */
|
||||
internal fun candidates(locale: Locale): List<String> {
|
||||
val region = DesktopLocale.lang(locale).removeSuffix(".UTF-8")
|
||||
if (region == DesktopLocale.DEFAULT.removeSuffix(".UTF-8") || region.startsWith("en")) return emptyList()
|
||||
return listOfNotNull(region, "zh_TW".takeIf { region == "zh_HK" }, region.substringBefore('_')).distinct()
|
||||
}
|
||||
|
||||
internal fun baseUrl(desktopUrl: String) = desktopUrl.substringBeforeLast('/') + "/"
|
||||
|
||||
private fun marker(root: File, tag: String, name: String) = File(root, ".droiddeck-i18n-$tag-$name")
|
||||
|
||||
/** Installs the desktop's translations for [locale]; false when a download failed and is worth retrying. */
|
||||
@Synchronized
|
||||
fun ensure(context: Context, locale: Locale): Boolean {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
if (!DesktopCatalog.desktopInstalled(root)) return true
|
||||
val entry = DesktopCatalog.desktopEntry(context)
|
||||
val pending = candidates(locale).filterNot { marker(root, entry.version, it).isFile }
|
||||
if (pending.isEmpty()) return true
|
||||
val base = baseUrl(entry.url)
|
||||
val index = parseIndex(Downloader.downloadString(base + INDEX) ?: return false)
|
||||
var complete = true
|
||||
for (name in pending) {
|
||||
val pack = index[name]
|
||||
if (pack == null) {
|
||||
FileUtils.writeString(marker(root, entry.version, name), ABSENT)
|
||||
continue
|
||||
}
|
||||
val download = File(context.cacheDir, "i18n-$name-${pack.sha256.take(12)}.download")
|
||||
try {
|
||||
val ok = Downloader.downloadFile(
|
||||
base + "desktop-kde-i18n-$name.tar.zst", download, true, pack.sha256, java.util.function.Consumer<Float> { },
|
||||
) && pack.sha256.equals(Hashes.sha256(download), ignoreCase = true) &&
|
||||
LinuxRuntimeInstaller.extract(context, download, root, null)
|
||||
if (ok) FileUtils.writeString(marker(root, entry.version, name), pack.sha256) else complete = false
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "language pack $name: $e")
|
||||
complete = false
|
||||
} finally {
|
||||
download.delete()
|
||||
}
|
||||
}
|
||||
return complete
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,9 @@ object BottomDesktop {
|
||||
/** The proot to freeze with the session when it pauses. */
|
||||
val suspendPid: Int get() = guestPid
|
||||
private var guestGeneration = 0
|
||||
private var outputSize = 0 to 0
|
||||
var outputSize = 0 to 0
|
||||
private set
|
||||
private var attachedSurface: Surface? = null
|
||||
private var cursorShown = false
|
||||
/** The session generation whose launch the running compositor and guest belong to; -1 when none. */
|
||||
private var owner = -1
|
||||
@@ -97,16 +99,8 @@ object BottomDesktop {
|
||||
fun available(): Boolean =
|
||||
launch?.installed == true && SessionState.running && SessionState.mode != SessionService.MODE_DESKTOP
|
||||
|
||||
/**
|
||||
* The desktop renders below the panel's resolution: about 720 pixels on the short side keeps
|
||||
* Plasma's text big enough to touch and its software rendering cheap. A running desktop keeps its size.
|
||||
*/
|
||||
fun outputSizeFor(width: Int, height: Int): Pair<Int, Int> {
|
||||
if ((state == State.STARTING || state == State.RUNNING) && outputSize.first > 0) return outputSize
|
||||
if (width <= 0 || height <= 0) return 0 to 0
|
||||
val scale = maxOf(1f, Math.round(minOf(width, height) / TARGET_SHORT_SIDE * 2f) / 2f)
|
||||
return ((width / scale).toInt() and 1.inv()) to ((height / scale).toInt() and 1.inv())
|
||||
}
|
||||
fun outputSizeFor(width: Int, height: Int, fullResolution: Boolean = false): Pair<Int, Int> =
|
||||
desktopOutputSize(width, height, fullResolution, TARGET_SHORT_SIDE)
|
||||
|
||||
fun addListener(listener: () -> Unit) { listeners.add(listener) }
|
||||
|
||||
@@ -148,6 +142,7 @@ object BottomDesktop {
|
||||
appContext = context.applicationContext
|
||||
owner = current.generation
|
||||
outputSize = width to height
|
||||
attachedSurface = surface
|
||||
val dir = File(current.sessionDir, "bottom-desktop").apply { mkdirs() }
|
||||
val msg = Message.obtain(null, Comp.MSG_ATTACH).apply {
|
||||
arg1 = owner
|
||||
@@ -169,7 +164,19 @@ object BottomDesktop {
|
||||
}
|
||||
}
|
||||
|
||||
fun detach() {
|
||||
fun resize(surface: Surface, width: Int, height: Int) {
|
||||
if (surface !== attachedSurface || width <= 0 || height <= 0 || outputSize == (width to height)) return
|
||||
outputSize = width to height
|
||||
pendingAttach?.data?.apply {
|
||||
putInt(Comp.KEY_WIDTH, width)
|
||||
putInt(Comp.KEY_HEIGHT, height)
|
||||
}
|
||||
service?.let { send(it, Message.obtain(null, Comp.MSG_RESIZE, width, height)) }
|
||||
}
|
||||
|
||||
fun detach(surface: Surface? = null) {
|
||||
if (surface != null && attachedSurface != null && surface !== attachedSurface) return
|
||||
attachedSurface = null
|
||||
pendingAttach = null
|
||||
service?.let { send(it, Message.obtain(null, Comp.MSG_DETACH)) }
|
||||
}
|
||||
@@ -351,3 +358,9 @@ object BottomDesktop {
|
||||
}, "bottom-desktop-start").start()
|
||||
}
|
||||
}
|
||||
|
||||
internal fun desktopOutputSize(width: Int, height: Int, fullResolution: Boolean, targetShortSide: Float): Pair<Int, Int> {
|
||||
if (width <= 0 || height <= 0) return 0 to 0
|
||||
val scale = if (fullResolution) 1f else maxOf(1f, Math.round(minOf(width, height) / targetShortSide * 2f) / 2f)
|
||||
return ((width / scale).toInt() and 1.inv()) to ((height / scale).toInt() and 1.inv())
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.util.Locale
|
||||
|
||||
object DesktopLocale {
|
||||
const val DEFAULT = "C.UTF-8"
|
||||
|
||||
private val regions = mapOf(
|
||||
"en" to "US", "id" to "ID", "ms" to "MY", "cs" to "CZ", "da" to "DK", "de" to "DE",
|
||||
"es" to "ES", "fr" to "FR", "it" to "IT", "hu" to "HU", "nl" to "NL", "nb" to "NO",
|
||||
"pl" to "PL", "pt" to "PT", "ro" to "RO", "fi" to "FI", "sv" to "SE", "vi" to "VN",
|
||||
"tr" to "TR", "el" to "GR", "bg" to "BG", "ru" to "RU", "uk" to "UA", "ar" to "EG",
|
||||
"hi" to "IN", "th" to "TH", "ja" to "JP", "ko" to "KR", "zh" to "CN",
|
||||
)
|
||||
|
||||
private val systemRegions = mapOf(
|
||||
"en" to setOf("US", "GB", "AU", "CA", "IN", "NZ", "IE", "ZA", "SG"),
|
||||
"fr" to setOf("FR", "CA", "BE", "CH", "LU"),
|
||||
"de" to setOf("DE", "AT", "CH", "LU"),
|
||||
"it" to setOf("IT", "CH"),
|
||||
"nl" to setOf("NL", "BE"),
|
||||
"pt" to setOf("PT", "BR"),
|
||||
"sv" to setOf("SE", "FI"),
|
||||
"ar" to setOf("EG", "SA", "AE", "MA", "DZ", "TN", "JO", "KW", "IQ"),
|
||||
)
|
||||
|
||||
private val traditionalRegions = setOf("TW", "HK", "MO")
|
||||
|
||||
fun lang(locale: Locale): String {
|
||||
val language = when (locale.language) {
|
||||
"in" -> "id"
|
||||
"no", "nn" -> "nb"
|
||||
else -> locale.language
|
||||
}
|
||||
val region = when {
|
||||
language == "es" && SteamLanguage.forLocale(locale) == "latam" ->
|
||||
locale.country.takeIf { it.length == 2 && it != "US" } ?: "MX"
|
||||
language == "zh" -> chineseRegion(locale)
|
||||
locale.country in systemRegions[language].orEmpty() -> locale.country
|
||||
else -> regions[language] ?: return DEFAULT
|
||||
}
|
||||
return "${language}_$region.UTF-8"
|
||||
}
|
||||
|
||||
private fun chineseRegion(locale: Locale): String = when {
|
||||
locale.script == "Hans" -> "CN"
|
||||
locale.script == "Hant" -> if (locale.country == "HK") "HK" else "TW"
|
||||
locale.country == "HK" -> "HK"
|
||||
locale.country in traditionalRegions -> "TW"
|
||||
else -> "CN"
|
||||
}
|
||||
|
||||
fun language(locale: Locale): String? {
|
||||
val lang = lang(locale)
|
||||
if (lang == DEFAULT) return null
|
||||
val full = lang.removeSuffix(".UTF-8")
|
||||
val short = full.substringBefore('_')
|
||||
return when {
|
||||
short == "en" -> full
|
||||
full == "zh_HK" -> "zh_HK:zh_TW:zh"
|
||||
else -> "$full:$short"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,8 @@ class GpuStatsComponent(val dir: File, private val root: File) : SessionPart() {
|
||||
|
||||
fun prepare(): Boolean {
|
||||
sources = ""
|
||||
KgslBusy.status = "not tried"
|
||||
KgslClock.status = "not tried"
|
||||
if (!File(KGSL).exists()) return false
|
||||
val unreadable = MANGOHUD_FILES.any { File(KGSL, it).let { f -> f.exists() && !f.canRead() } }
|
||||
// Where SELinux hides the kgsl nodes completely (exists() is false too), the layer and cycle-counter feeds stand in.
|
||||
@@ -96,6 +98,7 @@ class GpuStatsComponent(val dir: File, private val root: File) : SessionPart() {
|
||||
if (load.failed) {
|
||||
memstore?.close()
|
||||
memstore = null
|
||||
KgslBusy.status += ", but the stamps never moved"
|
||||
Log.i(TAG, "hud: kgsl memstore timestamps never moved; GPU load from Vulkan timing")
|
||||
} else if (load.working) {
|
||||
Log.i(TAG, "hud: GPU load from the kgsl memstore (all GPU work)")
|
||||
@@ -114,7 +117,9 @@ class GpuStatsComponent(val dir: File, private val root: File) : SessionPart() {
|
||||
}
|
||||
|
||||
private fun memstoreSource(): String = when {
|
||||
memstoreLoad?.working == true -> "kgsl memstore ringbuffer timestamps (all GPU work)"
|
||||
memstoreLoad?.working == true ->
|
||||
if (memstore?.mode == KgslBusy.MODE_CONTEXTS) "kgsl memstore per-context timestamps (all GPU work)"
|
||||
else "kgsl memstore ringbuffer timestamps (all GPU work)"
|
||||
memstoreLoad?.failed == true -> LAYER_SOURCE
|
||||
else -> "kgsl memstore once its timestamps move; until then $LAYER_SOURCE"
|
||||
}
|
||||
@@ -339,6 +344,12 @@ class GpuStatsComponent(val dir: File, private val root: File) : SessionPart() {
|
||||
|
||||
/** Where the running session's GPU feeds come from, for the HUD diagnostics export. */
|
||||
@Volatile var sources = ""
|
||||
|
||||
/** Why the no-root GPU readers work or not, for the HUD diagnostics export; empty where they were not needed. */
|
||||
fun readerStatus(): String =
|
||||
if (KgslBusy.status == "not tried" && KgslClock.status == "not tried") ""
|
||||
else "kgsl memstore ${KgslBusy.status}; GPU cycle counter ${KgslClock.status}"
|
||||
|
||||
private const val STALE_MS = 30_000L
|
||||
|
||||
fun guestLoadDir(root: File) = File(root, GUEST_LOAD_DIR.removePrefix("/"))
|
||||
|
||||
@@ -10,6 +10,7 @@ object KgslBusy {
|
||||
private const val TAG = "SessionService"
|
||||
|
||||
@JvmStatic private external fun nativeOpen(error: IntArray): Long
|
||||
@JvmStatic private external fun nativeMode(handle: Long): Int
|
||||
@JvmStatic private external fun nativeRun(handle: Long, on: Boolean)
|
||||
@JvmStatic private external fun nativeRead(handle: Long, out: LongArray): Boolean
|
||||
@JvmStatic private external fun nativeClose(handle: Long)
|
||||
@@ -24,7 +25,10 @@ object KgslBusy {
|
||||
if (handle != 0L) nativeRun(handle, on)
|
||||
}
|
||||
|
||||
/** Running totals: busy samples, samples, samples in which a ringbuffer started new work. */
|
||||
/** Which memstore entries are watched: [MODE_RINGBUFFER] or [MODE_CONTEXTS] (hardware-scheduled kernels). */
|
||||
val mode: Int = if (handle != 0L) runCatching { nativeMode(handle) }.getOrDefault(0) else 0
|
||||
|
||||
/** Running totals: busy samples, samples, samples in which a ringbuffer or context started new work. */
|
||||
@Synchronized fun counts(): LongArray? {
|
||||
if (handle == 0L) return null
|
||||
val out = LongArray(3)
|
||||
@@ -37,14 +41,27 @@ object KgslBusy {
|
||||
}
|
||||
}
|
||||
|
||||
const val MODE_RINGBUFFER = 1
|
||||
const val MODE_CONTEXTS = 2
|
||||
|
||||
/** What the last [open] found, for the HUD diagnostics export. */
|
||||
@Volatile var status = "not tried"
|
||||
|
||||
fun open(): Reader? {
|
||||
if (!loaded) return null
|
||||
if (!loaded) {
|
||||
status = "gpuclock library did not load"
|
||||
return null
|
||||
}
|
||||
val error = IntArray(1)
|
||||
val handle = runCatching { nativeOpen(error) }.getOrDefault(0L)
|
||||
if (handle == 0L) {
|
||||
status = "open failed: ${KgslErrors.describe(error[0])}"
|
||||
Log.i(TAG, "hud: no GPU load from the kgsl memstore (open error ${error[0]})")
|
||||
return null
|
||||
}
|
||||
return Reader(handle)
|
||||
val reader = Reader(handle)
|
||||
status = if (reader.mode == MODE_CONTEXTS) "per-context stamps (hardware-scheduled kernel)" else "ringbuffer stamps"
|
||||
Log.i(TAG, "hud: kgsl memstore reader uses $status")
|
||||
return reader
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,10 @@ object KgslClock {
|
||||
|
||||
class Sampler internal constructor(private var handle: Long) : AutoCloseable {
|
||||
/** MHz, or null when this sample was refused or failed its checks. */
|
||||
@Synchronized fun mhz(): Int? = if (handle == 0L) null else nativeSample(handle).takeIf { it > 0 }
|
||||
@Synchronized fun mhz(): Int? = sample().takeIf { it > 0 }
|
||||
|
||||
/** MHz, or a negative native code: -errno from kgsl or [RANGE_CHECK_FAILED]. */
|
||||
@Synchronized fun sample(): Int = if (handle == 0L) CLOSED else nativeSample(handle)
|
||||
|
||||
@Synchronized override fun close() {
|
||||
if (handle != 0L) nativeClose(handle)
|
||||
@@ -28,22 +31,41 @@ object KgslClock {
|
||||
}
|
||||
}
|
||||
|
||||
/** A sampler that already produced one good reading, or null (the reason goes to the log). */
|
||||
/** -EBADF, what the native side also returns for a closed handle. */
|
||||
private const val CLOSED = -9
|
||||
|
||||
/** The native sample code for a reading that failed its range checks (kgsl_clock.c sampler_mhz). */
|
||||
const val RANGE_CHECK_FAILED = -1000
|
||||
|
||||
/** What the last [open] found, for the HUD diagnostics export. */
|
||||
@Volatile var status = "not tried"
|
||||
|
||||
/** A sampler that already produced one good reading, or null (the reason goes to the log and [status]). */
|
||||
fun open(): Sampler? {
|
||||
if (!loaded) return null
|
||||
if (!loaded) {
|
||||
status = "gpuclock library did not load"
|
||||
return null
|
||||
}
|
||||
val error = IntArray(1)
|
||||
val handle = runCatching { nativeOpen(error) }.getOrDefault(0L)
|
||||
if (handle == 0L) {
|
||||
status = "open failed: ${KgslErrors.describe(error[0])}"
|
||||
Log.i(TAG, "hud: no GPU clock from the cycle counter (open error ${error[0]})")
|
||||
return null
|
||||
}
|
||||
val sampler = Sampler(handle)
|
||||
val first = (0 until 3).firstNotNullOfOrNull { sampler.mhz() }
|
||||
var code = 0
|
||||
val first = (0 until 3).firstNotNullOfOrNull {
|
||||
code = sampler.sample()
|
||||
code.takeIf { it > 0 }
|
||||
}
|
||||
if (first == null) {
|
||||
Log.i(TAG, "hud: GPU cycle counter gave no usable reading")
|
||||
status = "no usable reading: ${KgslErrors.describe(code)}"
|
||||
Log.i(TAG, "hud: GPU cycle counter gave no usable reading ($code)")
|
||||
sampler.close()
|
||||
return null
|
||||
}
|
||||
status = "working ($first MHz at start)"
|
||||
Log.i(TAG, "hud: GPU clock from the cycle counter ($first MHz now)")
|
||||
return sampler
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
/** Readable text for the negative errno codes the gpuclock library returns. */
|
||||
internal object KgslErrors {
|
||||
fun describe(code: Int): String {
|
||||
if (code == 0) return "no error code"
|
||||
if (code == KgslClock.RANGE_CHECK_FAILED) return "sample out of range"
|
||||
val name = runCatching { android.system.OsConstants.errnoName(-code) }.getOrNull()
|
||||
return if (name != null) "$name ($code)" else "error $code"
|
||||
}
|
||||
}
|
||||
@@ -86,12 +86,26 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("animations", on).apply()
|
||||
}
|
||||
|
||||
fun dualScreenMode(context: Context): String =
|
||||
prefs(context).getString("dualScreenMode", null)?.takeIf { it in com.droiddeck.launcher.input.DualScreen.modes }
|
||||
?: com.droiddeck.launcher.input.DualScreen.MODE_AUTO
|
||||
private fun savedDualScreenMode(context: Context, key: String): String? =
|
||||
prefs(context).getString(key, null)?.takeIf { it in com.droiddeck.launcher.input.DualScreen.modes }
|
||||
|
||||
private fun legacyDualScreenMode(context: Context): String =
|
||||
if (!prefs(context).getBoolean("dualScreenLauncher", true)) com.droiddeck.launcher.input.DualScreen.MODE_OFF
|
||||
else savedDualScreenMode(context, "dualScreenMode") ?: com.droiddeck.launcher.input.DualScreen.MODE_AUTO
|
||||
|
||||
fun dualScreenMode(context: Context): String = legacyDualScreenMode(context)
|
||||
|
||||
fun setDualScreenMode(context: Context, mode: String) {
|
||||
prefs(context).edit().putString("dualScreenMode", mode).apply()
|
||||
val sessions = dualScreenSessionMode(context)
|
||||
prefs(context).edit().remove("dualScreenLauncher").putString("dualScreenMode", mode).putString("dualScreenSessionMode", sessions).apply()
|
||||
}
|
||||
|
||||
fun dualScreenSessionMode(context: Context): String =
|
||||
savedDualScreenMode(context, "dualScreenSessionMode") ?: legacyDualScreenMode(context)
|
||||
|
||||
fun setDualScreenSessionMode(context: Context, mode: String) {
|
||||
val launcher = dualScreenMode(context)
|
||||
prefs(context).edit().remove("dualScreenLauncher").putString("dualScreenMode", launcher).putString("dualScreenSessionMode", mode).apply()
|
||||
}
|
||||
|
||||
fun secondScreenPanel(context: Context): String? = prefs(context).getString("secondScreenPanel", null)
|
||||
@@ -162,12 +176,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putStringSet("telemetryOff", keys.toSet()).apply()
|
||||
}
|
||||
|
||||
fun dualScreenLauncher(context: Context): Boolean = prefs(context).getBoolean("dualScreenLauncher", true)
|
||||
|
||||
fun setDualScreenLauncher(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("dualScreenLauncher", on).apply()
|
||||
}
|
||||
|
||||
fun dualScreenSessionControls(context: Context): Boolean = prefs(context).getBoolean("dualScreenSessionControls", true)
|
||||
|
||||
fun setDualScreenSessionControls(context: Context, on: Boolean) {
|
||||
@@ -856,6 +864,9 @@ object SessionPrefs {
|
||||
fun battleNetNoSteamSet(context: Context): Boolean = prefs(context).getBoolean("battleNetNoSteamSet", false)
|
||||
fun setBattleNetNoSteamSet(context: Context) { prefs(context).edit().putBoolean("battleNetNoSteamSet", true).apply() }
|
||||
|
||||
fun battleNetFolder(context: Context, code: String): String? = prefs(context).getString("battleNetFolder:$code", null)
|
||||
fun setBattleNetFolder(context: Context, code: String, path: String) { prefs(context).edit().putString("battleNetFolder:$code", path).apply() }
|
||||
|
||||
fun clearCachedApps(context: Context): Boolean = prefs(context).getBoolean("clearCachedApps", false)
|
||||
fun setClearCachedApps(context: Context, on: Boolean) { prefs(context).edit().putBoolean("clearCachedApps", on).apply() }
|
||||
|
||||
@@ -975,10 +986,17 @@ object SessionPrefs {
|
||||
prefs(context).edit().apply { if (name == null) remove("bootMovieCustomName") else putString("bootMovieCustomName", name) }.apply()
|
||||
}
|
||||
|
||||
fun runSteamAtStartup(context: Context): Boolean = prefs(context).getBoolean("runSteamAtStartup", false)
|
||||
const val STARTUP_OFF = ""
|
||||
const val STARTUP_STEAM = "steam"
|
||||
const val STARTUP_DESKTOP = "desktop"
|
||||
|
||||
fun setRunSteamAtStartup(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("runSteamAtStartup", on).apply()
|
||||
fun startupSession(context: Context): String {
|
||||
val p = prefs(context)
|
||||
return p.getString("startupSession", null) ?: if (p.getBoolean("runSteamAtStartup", false)) STARTUP_STEAM else STARTUP_OFF
|
||||
}
|
||||
|
||||
fun setStartupSession(context: Context, id: String) {
|
||||
prefs(context).edit().putString("startupSession", id).remove("runSteamAtStartup").apply()
|
||||
}
|
||||
|
||||
fun addedGamesDirs(context: Context): List<String> {
|
||||
|
||||
@@ -70,6 +70,7 @@ class SessionService : Service() {
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
private var suspendController: SessionSuspendController? = null
|
||||
private val steamDownloadMonitor = SteamDownloadMonitor()
|
||||
private val downloadMonitorExecutor = java.util.concurrent.Executors.newSingleThreadExecutor { Thread(it, "steam-download-monitor").apply { isDaemon = true } }
|
||||
private var downloadMonitorTask: Runnable? = null
|
||||
private var downloadActive = false
|
||||
private var clientInstallActive = false
|
||||
@@ -346,7 +347,7 @@ class SessionService : Service() {
|
||||
screenOn = readScreenOn()
|
||||
manualPauseRequested = false
|
||||
suspendDownloadNow = false
|
||||
steamDownloadMonitor.reset()
|
||||
runOnDownloadMonitor { steamDownloadMonitor.reset() }
|
||||
downloadActive = false
|
||||
clientInstallActive = false
|
||||
steamSleepToken = null
|
||||
@@ -649,6 +650,10 @@ class SessionService : Service() {
|
||||
}
|
||||
|
||||
if (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) OfflineMode.apply(this, root)
|
||||
if (SessionState.mode == MODE_DESKTOP) {
|
||||
runCatching { com.droiddeck.launcher.runtime.DesktopLanguage.ensure(this, com.droiddeck.launcher.core.AppLanguage.effective(this)) }
|
||||
.onFailure { Log.w(TAG, "desktop language pack: $it") }
|
||||
}
|
||||
|
||||
val networkLink = LinuxNetworkLinkComponent(this, root)
|
||||
networkLink.attach(this)
|
||||
@@ -778,7 +783,13 @@ class SessionService : Service() {
|
||||
guest.add("USER=root")
|
||||
guest.add("PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games")
|
||||
guest.add("TERM=xterm-256color")
|
||||
guest.add("LANG=C.UTF-8")
|
||||
if (SessionState.mode == MODE_DESKTOP) {
|
||||
val appLocale = com.droiddeck.launcher.core.AppLanguage.effective(this)
|
||||
guest.add("LANG=" + DesktopLocale.lang(appLocale))
|
||||
DesktopLocale.language(appLocale)?.let { guest.add("LANGUAGE=$it") }
|
||||
} else {
|
||||
guest.add("LANG=C.UTF-8")
|
||||
}
|
||||
guest.add("BL_STEAM_LANGUAGE=" + SteamLanguage.forLocale(
|
||||
com.droiddeck.launcher.core.AppLanguage.effective(this),
|
||||
com.droiddeck.launcher.core.AppLanguage.system(this).country,
|
||||
@@ -1991,6 +2002,9 @@ class SessionService : Service() {
|
||||
(getSystemService(Context.DISPLAY_SERVICE) as? DisplayManager)?.unregisterDisplayListener(displayListener)
|
||||
displayListenerRegistered = false
|
||||
}
|
||||
downloadMonitorTask?.let(mainHandler::removeCallbacks)
|
||||
downloadMonitorTask = null
|
||||
downloadMonitorExecutor.shutdown()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@@ -2114,12 +2128,20 @@ class SessionService : Service() {
|
||||
SessionState.running && SessionState.mode == MODE_STEAM && suspendPolicy != SessionPrefs.SUSPEND_NEVER &&
|
||||
(steamDownloadsInBackground || !SessionState.firstFrameSeen)
|
||||
|
||||
private fun runOnDownloadMonitor(task: () -> Unit) {
|
||||
try {
|
||||
downloadMonitorExecutor.execute(task)
|
||||
} catch (e: java.util.concurrent.RejectedExecutionException) {
|
||||
Log.d(TAG, "download monitor already shut down")
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateDownloadMonitoring() {
|
||||
if (!downloadWatchWanted()) {
|
||||
val wasActive = downloadActive
|
||||
downloadMonitorTask?.let(mainHandler::removeCallbacks)
|
||||
downloadMonitorTask = null
|
||||
steamDownloadMonitor.reset()
|
||||
runOnDownloadMonitor { steamDownloadMonitor.reset() }
|
||||
downloadActive = false
|
||||
if (clientInstallActive) SessionEvents.record("steam.client_download", mapOf("active" to false))
|
||||
clientInstallActive = false
|
||||
@@ -2141,18 +2163,30 @@ class SessionService : Service() {
|
||||
val wasInstalling = clientInstallActive
|
||||
clientInstallActive = !SessionState.firstFrameSeen &&
|
||||
(clientInstallActive || SteamDownloadMonitor.clientInstallPending(root))
|
||||
downloadActive = clientInstallActive || steamDownloadsInBackground && steamDownloadMonitor.poll(
|
||||
root,
|
||||
receivedBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid()),
|
||||
client = SessionState.steamClientArch,
|
||||
mounts = steamLibraryMounts,
|
||||
)
|
||||
if (wasInstalling != clientInstallActive) {
|
||||
SessionEvents.record("steam.client_download", mapOf("active" to clientInstallActive))
|
||||
val receivedBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid())
|
||||
val client = SessionState.steamClientArch
|
||||
val mounts = steamLibraryMounts
|
||||
val self = this
|
||||
val finish = { monitored: Boolean ->
|
||||
if (downloadMonitorTask === self) {
|
||||
downloadActive = clientInstallActive || monitored
|
||||
if (wasInstalling != clientInstallActive) {
|
||||
SessionEvents.record("steam.client_download", mapOf("active" to clientInstallActive))
|
||||
}
|
||||
if (wasActive != downloadActive) refreshNotification()
|
||||
updateSuspendPolicy()
|
||||
mainHandler.postDelayed(self, DOWNLOAD_POLL_MS)
|
||||
}
|
||||
}
|
||||
if (clientInstallActive || !steamDownloadsInBackground) {
|
||||
finish(false)
|
||||
return
|
||||
}
|
||||
runOnDownloadMonitor {
|
||||
val monitored = runCatching { steamDownloadMonitor.poll(root, receivedBytes = receivedBytes, client = client, mounts = mounts) }
|
||||
.getOrDefault(false)
|
||||
mainHandler.post { finish(monitored) }
|
||||
}
|
||||
if (wasActive != downloadActive) refreshNotification()
|
||||
updateSuspendPolicy()
|
||||
mainHandler.postDelayed(this, DOWNLOAD_POLL_MS)
|
||||
}
|
||||
}
|
||||
downloadMonitorTask = poll
|
||||
|
||||
@@ -93,6 +93,7 @@ object SessionState {
|
||||
@Volatile var secondScreenDisplay = -1
|
||||
@Volatile var secondScreenAutoOpened = false
|
||||
@Volatile var secondScreenProvisional = false
|
||||
@Volatile var gameOnBottom = false
|
||||
|
||||
@Volatile var steamLibraryMounts: Map<String, java.io.File> = emptyMap()
|
||||
|
||||
|
||||
@@ -11,8 +11,8 @@ object SettingsReset {
|
||||
private const val TAG = "SettingsReset"
|
||||
|
||||
internal val SESSION_KEYS = setOf(
|
||||
"orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "addedGamesArt",
|
||||
"dualScreenMode", "dualScreenLauncher", "dualScreenSessionControls",
|
||||
"orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
|
||||
"dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls",
|
||||
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
|
||||
"storesInstallLanguage",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.session
|
||||
import android.content.Context
|
||||
import android.os.storage.StorageManager
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.files.StorageRoots
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import java.io.File
|
||||
import org.json.JSONArray
|
||||
@@ -49,15 +50,12 @@ object SteamLibraries {
|
||||
class Refused(val reason: String) : AddResult()
|
||||
}
|
||||
|
||||
fun add(context: Context, path: String, label: String = defaultLabel(context, File(path))): AddResult {
|
||||
fun add(context: Context, picked: String, label: String? = null): AddResult {
|
||||
val entries = list(context)
|
||||
if (entries.size >= MAX) return AddResult.Refused(context.getString(R.string.libraries_full, MAX))
|
||||
val path = innerLibrary(File(picked))?.path ?: picked
|
||||
val host = canonical(File(path))
|
||||
val taken = entries.map { canonical(it.host) } + listOfNotNull(
|
||||
GameStorage.effective(context)?.let { canonical(File(it.path)) },
|
||||
canonical(SessionPrefs.steamRoot(context, "arm64")),
|
||||
)
|
||||
if (taken.any { overlaps(it, host) }) return AddResult.Refused(context.getString(R.string.libraries_overlap))
|
||||
if (taken(context, entries).any { overlaps(it, host) }) return AddResult.Refused(context.getString(R.string.libraries_overlap))
|
||||
// Adding a Games folder itself is fine; a child of one would make it overlap and hide the rest of that folder.
|
||||
if (AddedGames.roots(context).any { host.startsWith(canonical(it.host) + "/") }) return AddResult.Refused(context.getString(R.string.libraries_overlap))
|
||||
GameStorage.prepare(context, path)?.let { return AddResult.Refused(it) }
|
||||
@@ -67,13 +65,70 @@ object SteamLibraries {
|
||||
if (current.any { overlaps(canonical(it.host), host) }) return AddResult.Refused(context.getString(R.string.libraries_overlap))
|
||||
// A removed library's mount stays registered with Steam until its next session, so ids are never reused.
|
||||
val next = maxOf(SessionPrefs.steamLibraryNextId(context), (current.maxOfOrNull { it.id.toInt() } ?: 0) + 1)
|
||||
val entry = Entry(next.toString(), path, clean(label).ifEmpty { File(path).name })
|
||||
val entry = Entry(next.toString(), path, clean(label ?: defaultLabel(context, File(path))).ifEmpty { File(path).name })
|
||||
save(context, current + entry)
|
||||
SessionPrefs.setSteamLibraryNextId(context, next + 1)
|
||||
return AddResult.Added(entry)
|
||||
}
|
||||
}
|
||||
|
||||
private fun taken(context: Context, entries: List<Entry>): List<String> = entries.map { canonical(it.host) } + listOfNotNull(
|
||||
GameStorage.effective(context)?.let { canonical(File(it.path)) },
|
||||
canonical(SessionPrefs.steamRoot(context, "arm64")),
|
||||
)
|
||||
|
||||
class Found(val path: String, val shown: String, val label: String, val games: Int)
|
||||
|
||||
/** Reads storage; call off the main thread. */
|
||||
fun found(context: Context): List<Found> {
|
||||
val entries = list(context)
|
||||
val taken = taken(context, entries) + AddedGames.roots(context).map { canonical(it.host) }
|
||||
val hits = ArrayList<Pair<File, Int>>()
|
||||
for (root in StorageRoots.list(context)) {
|
||||
if (!root.readable) continue
|
||||
for (dir in candidates(rawView(root.dir), SCAN_DEPTH)) {
|
||||
val games = gameCount(dir)
|
||||
if (games > 0 && File(dir, "steamapps").canWrite() && taken.none { overlaps(it, canonical(dir)) }) hits += dir to games
|
||||
}
|
||||
}
|
||||
val picked = ArrayList<Pair<File, Int>>()
|
||||
for (hit in hits.sortedByDescending { it.second }) {
|
||||
if (picked.none { overlaps(canonical(it.first), canonical(hit.first)) }) picked += hit
|
||||
}
|
||||
return picked.map { (dir, games) ->
|
||||
val shown = File(storagePath(dir.path))
|
||||
Found(dir.path, shown.path, defaultLabel(context, shown), games)
|
||||
}
|
||||
}
|
||||
|
||||
/** The FUSE view under /storage hides files other apps wrote unless DroidDeck has all files access; the raw card mount does not. */
|
||||
private fun rawView(dir: File): File {
|
||||
if (!dir.path.startsWith("/storage/") || dir.path.startsWith("/storage/emulated")) return dir
|
||||
val raw = File("/mnt/media_rw/" + dir.path.removePrefix("/storage/"))
|
||||
return if (raw.canRead() && raw.list() != null) raw else dir
|
||||
}
|
||||
|
||||
internal fun innerLibrary(picked: File): File? {
|
||||
if (gameCount(picked) > 0) return null
|
||||
return candidates(picked, 1).filter { it != picked && gameCount(it) > 0 }.singleOrNull()
|
||||
}
|
||||
|
||||
internal fun candidates(root: File, depth: Int): List<File> {
|
||||
val out = arrayListOf(root)
|
||||
var level = listOf(root)
|
||||
repeat(depth) {
|
||||
level = level.flatMap { dir ->
|
||||
dir.listFiles { f -> f.isDirectory && !f.name.startsWith(".") && f.name != "steamapps" && !(dir == root && f.name == "Android") }
|
||||
.orEmpty().sortedBy { it.name }
|
||||
}.take(SCAN_LIMIT - out.size)
|
||||
out += level
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
internal fun gameCount(library: File): Int =
|
||||
File(library, "steamapps").list()?.count { it.startsWith("appmanifest_") && it.endsWith(".acf") } ?: 0
|
||||
|
||||
fun rename(context: Context, id: String, label: String) {
|
||||
val name = clean(label).takeIf { it.isNotEmpty() } ?: return
|
||||
synchronized(lock) { save(context, list(context).map { if (it.id == id) Entry(it.id, it.path, name) else it }) }
|
||||
@@ -84,17 +139,27 @@ object SteamLibraries {
|
||||
synchronized(lock) { save(context, list(context).filterNot { it.id == id }) }
|
||||
}
|
||||
|
||||
fun defaultLabel(context: Context, folder: File): String {
|
||||
fun defaultLabel(context: Context, picked: File): String {
|
||||
val folder = File(storagePath(picked.path))
|
||||
val volume = try {
|
||||
context.getSystemService(StorageManager::class.java)?.getStorageVolume(folder)?.getDescription(context)
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
val name = folder.name.ifEmpty { context.getString(R.string.gstore_folder) }
|
||||
val parent = folder.parentFile
|
||||
val named = if (folder.name.equals("Steam", true) && parent != null && !volumeRoot(parent)) parent else folder
|
||||
val name = named.name.ifEmpty { context.getString(R.string.gstore_folder) }
|
||||
return clean(if (volume.isNullOrBlank()) name else context.getString(R.string.gstore_folder_on_volume, name, volume))
|
||||
}
|
||||
|
||||
private fun volumeRoot(dir: File): Boolean = dir.parent in setOf("/storage", "/mnt/media_rw", "/storage/emulated") || dir.parent == null
|
||||
|
||||
internal fun overlaps(a: String, b: String): Boolean = a == b || a.startsWith("$b/") || b.startsWith("$a/")
|
||||
|
||||
private fun canonical(file: File): String = runCatching { file.canonicalPath }.getOrDefault(file.absolutePath)
|
||||
private fun storagePath(path: String): String = if (path.startsWith("/mnt/media_rw/")) "/storage/" + path.removePrefix("/mnt/media_rw/") else path
|
||||
|
||||
private fun canonical(file: File): String = storagePath(runCatching { file.canonicalPath }.getOrDefault(file.absolutePath))
|
||||
|
||||
private const val SCAN_DEPTH = 2
|
||||
private const val SCAN_LIMIT = 4000
|
||||
}
|
||||
@@ -87,7 +87,7 @@ object CloudSaves {
|
||||
val item = sidecar.extra["catalogItemId"].orEmpty()
|
||||
if (ns.isEmpty() || item.isEmpty()) "" else EpicApiClient.getCustomAttribute(token, ns, item, "CloudSaveFolder")
|
||||
}
|
||||
Store.AMAZON, Store.ITCH, Store.XBOX, Store.BATTLENET -> ""
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET -> ""
|
||||
} ?: return null
|
||||
p.edit()
|
||||
.putString("cloud_template_$id", fetched.ifEmpty { TEMPLATE_NONE })
|
||||
@@ -148,7 +148,7 @@ object CloudSaves {
|
||||
val dir = when (store) {
|
||||
Store.GOG -> CloudSavePaths.gog(template, pfx, folder)
|
||||
Store.EPIC -> CloudSavePaths.epic(template, pfx, folder, EpicCredentialStore.load(context)?.accountId.orEmpty(), id)
|
||||
Store.AMAZON, Store.ITCH, Store.XBOX, Store.BATTLENET -> null
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET -> null
|
||||
}
|
||||
return dir to (if (dir == null) "unresolved" else "ok")
|
||||
}
|
||||
@@ -173,7 +173,7 @@ object CloudSaves {
|
||||
val account = EpicCredentialStore.load(context)?.accountId.orEmpty()
|
||||
if (token == null || account.isEmpty()) null else EpicCloud(account, id, token)
|
||||
}
|
||||
Store.AMAZON, Store.ITCH, Store.XBOX, Store.BATTLENET -> null
|
||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET -> null
|
||||
}
|
||||
|
||||
private fun gogScopedToken(context: Context, id: String, clientId: String): String? {
|
||||
|
||||
@@ -12,11 +12,13 @@ internal object LoginFlows {
|
||||
Store.GOG -> GogFlow(state, browserUserAgent)
|
||||
Store.EPIC -> epicFlow()
|
||||
Store.AMAZON -> amazonFlow()
|
||||
Store.GAMEJOLT -> gameJoltFlow(browserUserAgent)
|
||||
Store.ITCH, Store.XBOX, Store.BATTLENET -> null
|
||||
}
|
||||
|
||||
@Volatile var epicFlow: () -> StoreLoginActivity.Flow? = { null }
|
||||
@Volatile var amazonFlow: () -> StoreLoginActivity.Flow? = { null }
|
||||
@Volatile var gameJoltFlow: (String) -> StoreLoginActivity.Flow? = { null }
|
||||
|
||||
private class GogFlow(private val state: String, override val userAgent: String) : StoreLoginActivity.Flow {
|
||||
override val startUrl: String get() = GogAuth.authUrl(state)
|
||||
|
||||
@@ -5,9 +5,12 @@ enum class Store(val id: String, val label: String, val shortLabel: String) {
|
||||
EPIC("epic", "Epic Games", "Epic"),
|
||||
AMAZON("amazon", "Amazon Games", "Amazon"),
|
||||
XBOX("xbox", "Xbox", "Xbox"),
|
||||
ITCH("itch", "itch.io", "itch"),
|
||||
ITCH("itch", "Itch.io", "Itch.io"),
|
||||
GAMEJOLT("gamejolt", "Game Jolt", "Game Jolt"),
|
||||
BATTLENET("battlenet", "Battle.net", "Battle.net");
|
||||
|
||||
val folder: String get() = if (this == ITCH) "itch" else shortLabel
|
||||
|
||||
companion object {
|
||||
fun byId(id: String?): Store? = entries.firstOrNull { it.id == id }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.runtime.GuestCommand
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.itch.ItchArchives
|
||||
import org.apache.commons.compress.MemoryLimitException
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZFile
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
|
||||
import org.apache.commons.compress.archivers.zip.ZipFile
|
||||
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream
|
||||
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream
|
||||
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream
|
||||
import java.io.BufferedInputStream
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
import java.nio.file.Files
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal class StoreArchiveUnpacker(
|
||||
private val app: Context,
|
||||
private val cancelled: AtomicBoolean,
|
||||
private val label: String,
|
||||
private val unsupported: Int,
|
||||
private val extractFailed: Int,
|
||||
private val logName: String,
|
||||
) {
|
||||
var work: File = File("")
|
||||
|
||||
fun unpack(archive: File, filename: String, handle: DownloadQueue.JobHandle) {
|
||||
when (val kind = ItchArchives.kind(archive, filename)) {
|
||||
"zip" -> unzip(archive, handle)
|
||||
"7z" -> try {
|
||||
sevenZip(archive, handle)
|
||||
} catch (e: MemoryLimitException) {
|
||||
handle.log("$label: ${archive.name} needs more memory than the app has, unpacking it in the runtime")
|
||||
unrar(archive, handle, kind)
|
||||
}
|
||||
"rar" -> unrar(archive, handle, kind)
|
||||
"exe" -> copy(archive, File(work, filename.ifBlank { "game.exe" }))
|
||||
"tar" -> untar(archive, null, handle)
|
||||
"gz", "bz2", "xz" -> untar(archive, kind, handle) ?: single(archive, kind, handle)
|
||||
else -> copy(archive, File(work, filename.ifBlank { "game" }))
|
||||
}
|
||||
}
|
||||
|
||||
private fun target(name: String): File? {
|
||||
val file = File(work, name.replace('\\', '/'))
|
||||
val root = work.canonicalPath
|
||||
val path = file.canonicalPath
|
||||
return if (path == root || path.startsWith(root + File.separator)) file else null
|
||||
}
|
||||
|
||||
private fun unrar(archive: File, handle: DownloadQueue.JobHandle, kind: String) {
|
||||
if (!LinuxRuntime.isInstalled(app)) throw IllegalStateException(app.getString(unsupported, kind))
|
||||
val binds = if (listOf(app.filesDir, app.cacheDir).any { work.absolutePath.startsWith(it.absolutePath + "/") }) null
|
||||
else listOf(work.absolutePath)
|
||||
fun bsdtar(args: List<String>, onLine: (String) -> Unit) =
|
||||
GuestCommand.run(app, listOf("/usr/bin/bsdtar") + args, logName = logName, extraBinds = binds, fastPath = true, cancelled = cancelled) { line ->
|
||||
if (!line.startsWith("proot ")) onLine(line)
|
||||
}
|
||||
var entries = 0L
|
||||
bsdtar(listOf("-tf", archive.absolutePath)) { entries++ }
|
||||
var done = 0L
|
||||
val tail = ArrayDeque<String>()
|
||||
val code = bsdtar(listOf("-xvf", archive.absolutePath, "-C", work.absolutePath)) { line ->
|
||||
if (line.startsWith("x ")) handle.stageProgress(++done, entries) else {
|
||||
if (tail.size == 5) tail.removeFirst()
|
||||
tail.addLast(line)
|
||||
}
|
||||
}
|
||||
if (cancelled.get()) return
|
||||
if (code != 0) {
|
||||
handle.log("$label: bsdtar exited $code: ${tail.joinToString(" | ")}")
|
||||
throw IllegalStateException(app.getString(extractFailed, code))
|
||||
}
|
||||
}
|
||||
|
||||
private fun sevenZip(archive: File, handle: DownloadQueue.JobHandle) {
|
||||
val total = archive.length()
|
||||
var written = 0L
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
val limitKb = (Runtime.getRuntime().maxMemory() / 4 / 1024).coerceIn(32L * 1024, Int.MAX_VALUE.toLong()).toInt()
|
||||
Files.newByteChannel(archive.toPath()).use { channel ->
|
||||
SevenZFile.builder().setSeekableByteChannel(channel).setMaxMemoryLimitKb(limitKb).get().use { seven ->
|
||||
while (true) {
|
||||
if (cancelled.get()) return
|
||||
val entry = seven.nextEntry ?: break
|
||||
val file = target(entry.name)
|
||||
if (file == null) {
|
||||
handle.log("$label: skipped an entry outside the game folder")
|
||||
continue
|
||||
}
|
||||
if (entry.isDirectory) {
|
||||
file.mkdirs()
|
||||
continue
|
||||
}
|
||||
file.parentFile?.mkdirs()
|
||||
FileOutputStream(file).use { out ->
|
||||
while (true) {
|
||||
if (cancelled.get()) return
|
||||
val read = seven.read(buffer, 0, buffer.size)
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
written += read
|
||||
handle.stageProgress(written, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun untar(archive: File, codec: String?, handle: DownloadQueue.JobHandle): Unit? {
|
||||
val total = archive.length()
|
||||
var written = 0L
|
||||
var entries = 0
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
val opened = runCatching {
|
||||
FileInputStream(archive).use { raw ->
|
||||
val stream = when (codec) {
|
||||
"gz" -> GzipCompressorInputStream(BufferedInputStream(raw))
|
||||
"bz2" -> BZip2CompressorInputStream(BufferedInputStream(raw))
|
||||
"xz" -> XZCompressorInputStream(BufferedInputStream(raw))
|
||||
else -> BufferedInputStream(raw)
|
||||
}
|
||||
stream.use { input ->
|
||||
TarArchiveInputStream(input).use { tar ->
|
||||
while (true) {
|
||||
if (cancelled.get()) return null
|
||||
val entry = tar.nextEntry ?: break
|
||||
entries++
|
||||
val file = target(entry.name)
|
||||
if (file == null) {
|
||||
handle.log("$label: skipped an entry outside the game folder")
|
||||
continue
|
||||
}
|
||||
if (entry.isDirectory) {
|
||||
file.mkdirs()
|
||||
continue
|
||||
}
|
||||
file.parentFile?.mkdirs()
|
||||
FileOutputStream(file).use { out ->
|
||||
while (true) {
|
||||
if (cancelled.get()) return null
|
||||
val read = tar.read(buffer, 0, buffer.size)
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
written += read
|
||||
handle.stageProgress(written, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
if (opened.isSuccess && entries > 0) return Unit
|
||||
if (opened.isFailure && codec == null) throw opened.exceptionOrNull() ?: IllegalStateException("tar")
|
||||
return null
|
||||
}
|
||||
|
||||
private fun single(archive: File, codec: String, handle: DownloadQueue.JobHandle) {
|
||||
val name = archive.name.substringBeforeLast('.')
|
||||
val file = target(name.ifBlank { "game" }) ?: throw IllegalStateException("archive")
|
||||
file.parentFile?.mkdirs()
|
||||
val total = archive.length()
|
||||
var written = 0L
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
FileInputStream(archive).use { raw ->
|
||||
val stream = when (codec) {
|
||||
"bz2" -> BZip2CompressorInputStream(BufferedInputStream(raw))
|
||||
"xz" -> XZCompressorInputStream(BufferedInputStream(raw))
|
||||
else -> GzipCompressorInputStream(BufferedInputStream(raw))
|
||||
}
|
||||
stream.use { input ->
|
||||
FileOutputStream(file).use { out ->
|
||||
while (true) {
|
||||
if (cancelled.get()) return
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
written += read
|
||||
handle.stageProgress(written, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun copy(source: File, target: File) {
|
||||
target.parentFile?.mkdirs()
|
||||
FileInputStream(source).use { input -> FileOutputStream(target).use { out -> input.copyTo(out, 128 * 1024) } }
|
||||
}
|
||||
|
||||
private fun unzip(archive: File, handle: DownloadQueue.JobHandle) {
|
||||
val total = archive.length()
|
||||
var written = 0L
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
ZipFile.builder().setFile(archive).get().use { zip ->
|
||||
for (entry in zip.entries) {
|
||||
if (cancelled.get()) return
|
||||
val target = target(entry.name)
|
||||
if (target == null) {
|
||||
handle.log("$label: skipped an entry outside the game folder")
|
||||
continue
|
||||
}
|
||||
if (entry.isDirectory) {
|
||||
target.mkdirs()
|
||||
continue
|
||||
}
|
||||
target.parentFile?.mkdirs()
|
||||
zip.getInputStream(entry).use { input ->
|
||||
FileOutputStream(target).use { out ->
|
||||
while (true) {
|
||||
if (cancelled.get()) return
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
written += read
|
||||
handle.stageProgress(written, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -218,7 +218,7 @@ object StoreInstallRoot {
|
||||
|
||||
fun isRemovable(context: Context, folder: File): Boolean = !folder.absolutePath.startsWith(internalRoot(context).absolutePath + "/")
|
||||
|
||||
fun storeDir(root: File, store: Store): File = File(root, store.shortLabel)
|
||||
fun storeDir(root: File, store: Store): File = File(root, store.folder)
|
||||
|
||||
fun gameFolders(context: Context): List<File> = roots(context).flatMap { root ->
|
||||
Store.entries.flatMap { store ->
|
||||
@@ -246,7 +246,7 @@ object StoreInstallRoot {
|
||||
val sidecar = StoreGameSidecar.read(folder)
|
||||
when {
|
||||
sidecar == null -> Unfinished(store, null, folder)
|
||||
store == Store.GOG && sidecar.state == StoreGameSidecar.STATE_UPDATING -> null
|
||||
sidecar.state == StoreGameSidecar.STATE_UPDATING -> null
|
||||
!sidecar.isInstalled -> Unfinished(store, sidecar.id, folder)
|
||||
else -> null
|
||||
}
|
||||
|
||||
@@ -273,6 +273,10 @@ class StoreLoginActivity : ComponentActivity() {
|
||||
if (url != null && view != null && flow?.isRedirect(url) == true && flow?.readsPage != true) complete(view, url)
|
||||
}
|
||||
|
||||
override fun doUpdateVisitedHistory(view: WebView?, url: String?, isReload: Boolean) {
|
||||
if (!isPopup && store == Store.GAMEJOLT && url != null && view != null && flow?.isRedirect(url) == true && flow?.readsPage != true) complete(view, url)
|
||||
}
|
||||
|
||||
override fun onPageFinished(view: WebView?, url: String?) {
|
||||
if (url != null && view != null && flow?.readsPage == true && flow?.isRedirect(url) == true) complete(view, url)
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ object StoreSizes {
|
||||
when (item.store) {
|
||||
Store.EPIC -> EpicPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
|
||||
Store.AMAZON -> AmazonPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
|
||||
Store.ITCH -> {}
|
||||
Store.ITCH, Store.GAMEJOLT -> {}
|
||||
Store.GOG, Store.XBOX, Store.BATTLENET -> {}
|
||||
}
|
||||
}
|
||||
@@ -113,5 +113,6 @@ object StoreSizes {
|
||||
}
|
||||
Store.GOG, Store.XBOX, Store.BATTLENET -> 0L
|
||||
Store.ITCH -> com.droiddeck.launcher.stores.itch.ItchLibrary.size(context, item)
|
||||
Store.GAMEJOLT -> com.droiddeck.launcher.stores.gamejolt.GameJoltBuilds.size(context, item)
|
||||
} }
|
||||
}
|
||||
@@ -81,7 +81,7 @@ object StoresState {
|
||||
runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.syncAccount(app) }
|
||||
val found = Store.entries.mapNotNull { store -> StoreAccounts.displayName(app, store)?.let { store to it } }
|
||||
val onDisk = StoreInstallRoot.gameFolders(app).mapNotNull { folder ->
|
||||
StoreGameSidecar.read(folder)?.takeIf { it.isInstalled || it.store == Store.GOG && it.state == StoreGameSidecar.STATE_UPDATING }?.let { InstalledStoreGame(it, folder) }
|
||||
StoreGameSidecar.read(folder)?.takeIf { it.isInstalled || it.state == StoreGameSidecar.STATE_UPDATING }?.let { InstalledStoreGame(it, folder) }
|
||||
} + runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetBackend.installedGames(app) }.getOrDefault(emptyList())
|
||||
val partial = StoreInstallRoot.unfinished(app)
|
||||
val version = if (StoresNative.available) StoresNative.version ?: "" else ""
|
||||
@@ -131,7 +131,11 @@ object StoresState {
|
||||
|
||||
fun detailItem(store: Store, id: String): CatalogItem? = detailCatalogItem(
|
||||
store, id, library[store].orEmpty(),
|
||||
found[store].orEmpty() + if (store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchBrowseState.items + com.droiddeck.launcher.stores.itch.ItchCollections.items() else emptyList(),
|
||||
found[store].orEmpty() + when (store) {
|
||||
Store.ITCH -> com.droiddeck.launcher.stores.itch.ItchBrowseState.items + com.droiddeck.launcher.stores.itch.ItchCollections.items()
|
||||
Store.GAMEJOLT -> com.droiddeck.launcher.stores.gamejolt.GameJoltBrowseState.items + com.droiddeck.launcher.stores.gamejolt.GameJoltCollections.items()
|
||||
else -> emptyList()
|
||||
},
|
||||
shelves[store],
|
||||
)
|
||||
|
||||
@@ -191,6 +195,10 @@ 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)
|
||||
if (store == Store.GAMEJOLT) {
|
||||
com.droiddeck.launcher.stores.gamejolt.GameJoltCollections.clear()
|
||||
com.droiddeck.launcher.stores.gamejolt.GameJoltUpdates.clear(app)
|
||||
}
|
||||
if (store == Store.ITCH) {
|
||||
com.droiddeck.launcher.stores.itch.ItchCollections.clear()
|
||||
com.droiddeck.launcher.stores.itch.ItchUpdates.clear(app)
|
||||
@@ -218,10 +226,12 @@ object StoresState {
|
||||
|
||||
var pendingInstall by mutableStateOf<CatalogItem?>(null)
|
||||
var itchPicking by mutableStateOf<CatalogItem?>(null)
|
||||
var gameJoltPicking by mutableStateOf<CatalogItem?>(null)
|
||||
|
||||
fun requestInstall(context: Context, item: CatalogItem) {
|
||||
askForNotifications(context)
|
||||
if (item.store == Store.ITCH && item.extra["uploadId"].isNullOrEmpty()) { itchPicking = item; return }
|
||||
if (item.store == Store.GAMEJOLT && item.extra["buildId"].isNullOrEmpty()) { gameJoltPicking = item; return }
|
||||
if (isUnfinished(item)) { install(context, item); return }
|
||||
val targets = StoreInstallRoot.targets(context)
|
||||
val preferred = StoreInstallRoot.defaultTarget(context)
|
||||
@@ -285,6 +295,7 @@ object StoresState {
|
||||
installed = installed.filterNot { it.folder.absolutePath == game.folder.absolutePath }
|
||||
uninstalling.remove(key)
|
||||
if (game.sidecar.store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchUpdates.applied(app, key)
|
||||
if (game.sidecar.store == Store.GAMEJOLT) com.droiddeck.launcher.stores.gamejolt.GameJoltUpdates.applied(app, key)
|
||||
}
|
||||
})
|
||||
main.post(onDone)
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.droiddeck.launcher.stores.gamejolt
|
||||
|
||||
import com.droiddeck.launcher.stores.StoreNet
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
|
||||
internal class GameJoltAnswer(val code: Int, val json: JSONObject?) {
|
||||
val ok: Boolean get() = code in 200..299
|
||||
val payload: JSONObject? get() = json?.optJSONObject("payload")
|
||||
val user: JSONObject? get() = json?.optJSONObject("user")
|
||||
}
|
||||
|
||||
internal object GameJoltApi {
|
||||
const val SITE = "https://gamejolt.com"
|
||||
const val LOGIN = "$SITE/login"
|
||||
|
||||
private const val BASE = "$SITE/site-api"
|
||||
private const val MAX_BYTES = 6_000_000
|
||||
|
||||
fun get(path: String, cookies: String = ""): GameJoltAnswer = send("GET", path, cookies, null)
|
||||
|
||||
fun post(path: String, cookies: String = "", body: String = ""): GameJoltAnswer = send("POST", path, cookies, body)
|
||||
|
||||
fun overview(gameId: String, cookies: String): GameJoltAnswer = get("/web/discover/games/overview/$gameId", cookies)
|
||||
|
||||
fun search(query: String, page: Int, cookies: String): GameJoltAnswer =
|
||||
get("/web/search/games?q=${URLEncoder.encode(query, "UTF-8")}&page=$page", cookies)
|
||||
|
||||
fun browse(queryString: String, cookies: String): GameJoltAnswer = get("/web/discover/games?$queryString", cookies)
|
||||
|
||||
fun pageUrl(slug: String, id: String): String = "$SITE/games/$slug/$id"
|
||||
|
||||
private fun readBounded(input: java.io.InputStream): String {
|
||||
val out = java.io.ByteArrayOutputStream()
|
||||
val buffer = ByteArray(16 * 1024)
|
||||
while (out.size() < MAX_BYTES) {
|
||||
val read = input.read(buffer, 0, minOf(buffer.size, MAX_BYTES - out.size()))
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
}
|
||||
return out.toString(Charsets.UTF_8.name())
|
||||
}
|
||||
|
||||
private fun send(method: String, path: String, cookies: String, body: String?): GameJoltAnswer {
|
||||
var conn: HttpURLConnection? = null
|
||||
return try {
|
||||
conn = (URL(BASE + path).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 25_000
|
||||
readTimeout = 25_000
|
||||
requestMethod = method
|
||||
setRequestProperty("User-Agent", StoreNet.BROWSER_UA)
|
||||
setRequestProperty("Accept", "application/json")
|
||||
if (cookies.isNotBlank()) setRequestProperty("Cookie", cookies)
|
||||
if (body != null) {
|
||||
doOutput = true
|
||||
setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
}
|
||||
if (body != null) conn.outputStream.use { it.write(body.toByteArray()) }
|
||||
val code = conn.responseCode
|
||||
val stream = if (code in 200..399) conn.inputStream else conn.errorStream
|
||||
val text = stream?.use { readBounded(it) }.orEmpty()
|
||||
GameJoltAnswer(code, runCatching { JSONObject(text) }.getOrNull())
|
||||
} catch (e: Exception) {
|
||||
GameJoltAnswer(0, null)
|
||||
} finally {
|
||||
runCatching { conn?.disconnect() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.droiddeck.launcher.stores.gamejolt
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreAccounts
|
||||
import org.json.JSONObject
|
||||
|
||||
internal object GameJoltAuth {
|
||||
fun cookies(context: Context): String = StoreAccounts.read(context.applicationContext, Store.GAMEJOLT)?.optString("access_token").orEmpty()
|
||||
|
||||
fun save(context: Context, cookies: String, user: JSONObject) {
|
||||
val name = user.optString("display_name").ifBlank { user.optString("username") }
|
||||
StoreAccounts.write(
|
||||
context.applicationContext, Store.GAMEJOLT,
|
||||
JSONObject().put("access_token", cookies).put("user_id", user.optLong("id").toString()).put("username", user.optString("username")).put("display_name", name),
|
||||
)
|
||||
}
|
||||
|
||||
fun username(context: Context): String = StoreAccounts.read(context.applicationContext, Store.GAMEJOLT)?.optString("username").orEmpty()
|
||||
|
||||
fun userId(context: Context): String = StoreAccounts.read(context.applicationContext, Store.GAMEJOLT)?.optString("user_id").orEmpty()
|
||||
|
||||
fun clear(context: Context) = StoreAccounts.clear(context.applicationContext, Store.GAMEJOLT)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.droiddeck.launcher.stores.gamejolt
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.LoginFlows
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreBackend
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreLoginActivity
|
||||
import com.droiddeck.launcher.stores.StoreShelves
|
||||
import com.droiddeck.launcher.stores.StoreSizes
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import java.io.File
|
||||
|
||||
object GameJoltBackend : StoreBackend {
|
||||
override val store: Store = Store.GAMEJOLT
|
||||
|
||||
init {
|
||||
LoginFlows.gameJoltFlow = { agent -> GameJoltLogin(agent) }
|
||||
}
|
||||
|
||||
override fun signIn(context: Context) {
|
||||
context.startActivity(
|
||||
Intent(context, StoreLoginActivity::class.java)
|
||||
.putExtra(StoreLoginActivity.EXTRA_STORE, store.id)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
}
|
||||
|
||||
override fun signOut(context: Context) {
|
||||
val app = context.applicationContext
|
||||
GameJoltPrefs.get(app).edit().clear().apply()
|
||||
GameJoltAuth.clear(app)
|
||||
GameJoltLibrary.reset()
|
||||
StoresState.post {
|
||||
StoresState.library.remove(store)
|
||||
StoresState.shelves.remove(store)
|
||||
StoresState.found.remove(store)
|
||||
StoresState.problems.remove(store)
|
||||
StoresState.status.remove(store)
|
||||
}
|
||||
}
|
||||
|
||||
override fun syncLibrary(context: Context, force: Boolean) {
|
||||
val app = context.applicationContext
|
||||
if (force) GameJoltLibrary.reset()
|
||||
Thread({ GameJoltLibrary.sync(app, force) }, "gamejolt-sync").start()
|
||||
}
|
||||
|
||||
override fun loadShelves(context: Context, force: Boolean) {
|
||||
StoresState.post { StoresState.shelves[store] = StoreShelves() }
|
||||
}
|
||||
|
||||
override fun search(context: Context, query: String): List<CatalogItem> {
|
||||
val cookies = GameJoltAuth.cookies(context)
|
||||
val items = ArrayList<CatalogItem>()
|
||||
for (page in 1..2) {
|
||||
val answer = GameJoltApi.search(query, page, cookies)
|
||||
val found = if (answer.ok) GameJoltCatalog.items(answer.payload?.optJSONArray("games")) else emptyList()
|
||||
if (found.isEmpty()) break
|
||||
items.addAll(found)
|
||||
}
|
||||
StoresState.logLine("Game Jolt search: \"$query\" returned ${items.size} games")
|
||||
return items.distinctBy { it.id }
|
||||
}
|
||||
|
||||
override fun install(context: Context, item: CatalogItem, root: File) {
|
||||
val app = context.applicationContext
|
||||
if (!item.isFree && !item.owned) {
|
||||
StoresState.logLine("Game Jolt: \"${item.title}\" is a paid game, opening its page instead")
|
||||
return
|
||||
}
|
||||
val folder = StoreInstallRoot.folderFor(app, Store.GAMEJOLT, item.id, item.title, root)
|
||||
val entry = DownloadEntry(
|
||||
Store.GAMEJOLT, item.id, item.title, cover = item.imageUrl, bytesTotal = StoreSizes.size(item),
|
||||
location = StoreInstallRoot.labelFor(app, folder),
|
||||
)
|
||||
DownloadQueue.enqueue(app, entry) { GameJoltInstaller(app, item, folder) }
|
||||
}
|
||||
|
||||
override fun uninstall(context: Context, game: InstalledStoreGame) {}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package com.droiddeck.launcher.stores.gamejolt
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import java.net.URLEncoder
|
||||
|
||||
internal data class GameJoltQuery(
|
||||
val section: String = GameJoltBrowse.SECTION_FEATURED,
|
||||
val price: String = GameJoltBrowse.PRICE_ANY,
|
||||
val os: Set<String> = emptySet(),
|
||||
val browser: Set<String> = emptySet(),
|
||||
val maturity: Set<String> = emptySet(),
|
||||
val status: Set<String> = emptySet(),
|
||||
val partners: Boolean = false,
|
||||
val tags: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
internal object GameJoltBrowse {
|
||||
const val SECTION_FEATURED = "featured"
|
||||
const val SECTION_HOT = "hot"
|
||||
const val SECTION_BEST = "best"
|
||||
const val SECTION_NEW = "new"
|
||||
val sections = listOf(SECTION_FEATURED, SECTION_HOT, SECTION_BEST, SECTION_NEW)
|
||||
|
||||
const val PRICE_ANY = "any"
|
||||
const val PRICE_FREE = "free"
|
||||
const val PRICE_SALE = "sale"
|
||||
const val PRICE_PAID = "paid"
|
||||
const val PRICE_UNDER_5 = "5-less"
|
||||
const val PRICE_UNDER_15 = "15-less"
|
||||
const val PRICE_UNDER_30 = "30-less"
|
||||
val prices = listOf(PRICE_ANY, PRICE_FREE, PRICE_SALE, PRICE_PAID, PRICE_UNDER_5, PRICE_UNDER_15, PRICE_UNDER_30)
|
||||
|
||||
val systems = listOf("windows", "mac", "linux", "other")
|
||||
val browsers = listOf("html", "flash", "unity")
|
||||
val maturities = listOf("everyone", "teen", "adult")
|
||||
val statuses = listOf("complete", "wip")
|
||||
|
||||
fun tagSlug(tag: String): String = tag.trim().lowercase().replace(Regex("[^a-z0-9]+"), "-").trim('-')
|
||||
|
||||
fun queryString(query: GameJoltQuery, page: Int): String {
|
||||
val parts = ArrayList<String>()
|
||||
parts.add("section=${query.section.takeIf { it in sections } ?: SECTION_FEATURED}")
|
||||
query.tags.forEach { parts.add("tag=" + enc(tagSlug(it))) }
|
||||
if (query.price != PRICE_ANY && query.price in prices) parts.add("f_price=${query.price}")
|
||||
systems.filter { it in query.os }.forEach { parts.add("f_os%5B%5D=$it") }
|
||||
browsers.filter { it in query.browser }.forEach { parts.add("f_browser%5B%5D=$it") }
|
||||
maturities.filter { it in query.maturity }.forEach { parts.add("f_maturity%5B%5D=$it") }
|
||||
statuses.filter { it in query.status }.forEach { parts.add("f_status%5B%5D=$it") }
|
||||
if (query.partners) parts.add("f_partners%5B%5D=partners")
|
||||
if (page > 1) parts.add("page=$page")
|
||||
return parts.joinToString("&")
|
||||
}
|
||||
|
||||
private fun enc(value: String): String = URLEncoder.encode(value, "UTF-8")
|
||||
|
||||
class Page(val items: List<CatalogItem>, val code: Int, val rawIds: List<String>)
|
||||
|
||||
fun effective(query: GameJoltQuery, showMature: Boolean): GameJoltQuery {
|
||||
val playable = query.copy(status = query.status.filterTo(HashSet()) { it in statuses }.ifEmpty { statuses.toSet() })
|
||||
if (showMature) return playable
|
||||
val allowed = playable.maturity - "adult"
|
||||
return playable.copy(maturity = allowed.ifEmpty { setOf("everyone", "teen") })
|
||||
}
|
||||
|
||||
fun page(context: Context, query: GameJoltQuery, page: Int, showMature: Boolean): Page {
|
||||
val cookies = GameJoltAuth.cookies(context)
|
||||
val asked = effective(query, showMature)
|
||||
val answer = fetch(queryString(asked, page), cookies)
|
||||
val all = if (answer.ok) GameJoltCatalog.items(answer.payload?.optJSONArray("games")) else emptyList()
|
||||
return Page(all, answer.code, all.map { it.id })
|
||||
}
|
||||
|
||||
private fun fetch(qs: String, cookies: String): GameJoltAnswer {
|
||||
val answer = GameJoltApi.browse(qs, cookies)
|
||||
val games = if (answer.ok) answer.payload?.optJSONArray("games") else null
|
||||
StoresState.logLine("Game Jolt browse: ?$qs answered ${answer.code} with ${games?.length() ?: 0} games")
|
||||
return answer
|
||||
}
|
||||
}
|
||||
|
||||
internal object GameJoltBrowseState {
|
||||
var query by mutableStateOf(GameJoltQuery())
|
||||
private set
|
||||
var items by mutableStateOf<List<CatalogItem>>(emptyList())
|
||||
private set
|
||||
var loading by mutableStateOf(false)
|
||||
private set
|
||||
var ended by mutableStateOf(false)
|
||||
private set
|
||||
var failed by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
private var next = 1
|
||||
private var generation = 0
|
||||
private var loadedMature: Boolean? = null
|
||||
private val seenRaw = HashSet<String>()
|
||||
|
||||
fun sync(context: Context, showMature: Boolean) {
|
||||
if (!showMature && "adult" in query.maturity) {
|
||||
reset()
|
||||
query = query.copy(maturity = query.maturity - "adult")
|
||||
more(context)
|
||||
return
|
||||
}
|
||||
val before = loadedMature ?: return
|
||||
if (before != showMature) more(context)
|
||||
}
|
||||
|
||||
private fun reset() {
|
||||
generation++
|
||||
items = emptyList()
|
||||
ended = false
|
||||
failed = false
|
||||
loading = false
|
||||
next = 1
|
||||
seenRaw.clear()
|
||||
}
|
||||
|
||||
fun choose(context: Context, wanted: GameJoltQuery) {
|
||||
if (wanted == query) return
|
||||
reset()
|
||||
query = wanted
|
||||
more(context)
|
||||
}
|
||||
|
||||
fun more(context: Context, retry: Boolean = false) {
|
||||
val app = context.applicationContext
|
||||
val mature = SessionPrefs.storesShowMature(app)
|
||||
if (loadedMature != null && loadedMature != mature) reset()
|
||||
if (loading || ended || (failed && !retry)) return
|
||||
loading = true
|
||||
failed = false
|
||||
val mine = generation
|
||||
val asked = query
|
||||
val page = next
|
||||
loadedMature = mature
|
||||
Thread({
|
||||
val answer = runCatching { GameJoltBrowse.page(app, asked, page, mature) }.getOrNull()
|
||||
StoresState.post {
|
||||
if (mine != generation) return@post
|
||||
loading = false
|
||||
if (answer == null || answer.code !in 200..299) {
|
||||
failed = true
|
||||
return@post
|
||||
}
|
||||
if (answer.rawIds.filter { seenRaw.add(it) }.isEmpty()) {
|
||||
ended = true
|
||||
return@post
|
||||
}
|
||||
next = page + 1
|
||||
val known = items.mapTo(HashSet()) { it.id }
|
||||
val fresh = answer.items.filter { known.add(it.id) }
|
||||
if (fresh.isEmpty()) more(app) else items = items + fresh
|
||||
}
|
||||
}, "gamejolt-browse").start()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.droiddeck.launcher.stores.gamejolt
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
internal class GameJoltBuild(
|
||||
val id: String,
|
||||
val packageId: String,
|
||||
val packageTitle: String,
|
||||
val version: String,
|
||||
val filename: String,
|
||||
val size: Long,
|
||||
val stamp: String,
|
||||
val platforms: Set<String>,
|
||||
val folder: String,
|
||||
val executable: String,
|
||||
) {
|
||||
val installable: Boolean get() = "windows" in platforms
|
||||
}
|
||||
|
||||
internal object GameJoltBuilds {
|
||||
fun parse(payload: JSONObject?): List<GameJoltBuild> {
|
||||
if (payload == null) return emptyList()
|
||||
val packages = objects(payload.optJSONArray("packages")).associate { it.optLong("id") to it.optString("title") }
|
||||
val releases = objects(payload.optJSONArray("releases")).associateBy { it.optLong("id") }
|
||||
val launch = objects(payload.optJSONArray("launchOptions"))
|
||||
val builds = objects(payload.optJSONArray("builds")).filter { it.optJSONObject("primary_file") != null }
|
||||
val newest = builds.groupBy { it.optLong("game_package_id") }.mapValues { (_, list) ->
|
||||
list.maxOfOrNull { releaseRank(releases[it.optLong("game_release_id")], it.optLong("game_release_id")) }
|
||||
}
|
||||
return builds
|
||||
.filter { newest[it.optLong("game_package_id")] == releaseRank(releases[it.optLong("game_release_id")], it.optLong("game_release_id")) }
|
||||
.map { build ->
|
||||
val file = build.optJSONObject("primary_file")
|
||||
val release = releases[build.optLong("game_release_id")]
|
||||
val id = build.optLong("id")
|
||||
GameJoltBuild(
|
||||
id = id.toString(),
|
||||
packageId = build.optLong("game_package_id").toString(),
|
||||
packageTitle = packages[build.optLong("game_package_id")].orEmpty(),
|
||||
version = release?.optString("version_number").orEmpty(),
|
||||
filename = file?.optString("filename").orEmpty().substringAfterLast('/').substringAfterLast('\\'),
|
||||
size = file?.optLong("filesize") ?: 0L,
|
||||
stamp = release?.optLong("published_on")?.takeIf { it > 0L }?.toString().orEmpty(),
|
||||
platforms = platforms(build),
|
||||
folder = build.optString("folder"),
|
||||
executable = launch.firstOrNull { it.optLong("game_build_id") == id && it.optString("os").startsWith("windows") }?.optString("executable_path").orEmpty(),
|
||||
)
|
||||
}
|
||||
.sortedWith(compareByDescending<GameJoltBuild> { it.installable }.thenByDescending { it.stamp.toLongOrNull() ?: 0L }.thenByDescending { it.id.toLongOrNull() ?: 0L })
|
||||
}
|
||||
|
||||
fun platforms(build: JSONObject): Set<String> {
|
||||
val found = LinkedHashSet<String>()
|
||||
if (build.optBoolean("os_windows") || build.optBoolean("os_windows_64")) found.add("windows")
|
||||
if (build.optBoolean("os_linux") || build.optBoolean("os_linux_64")) found.add("linux")
|
||||
if (build.optBoolean("os_mac") || build.optBoolean("os_mac_64")) found.add("osx")
|
||||
if (build.optBoolean("os_other")) found.add("other")
|
||||
return if (found.isEmpty()) setOf("web") else found
|
||||
}
|
||||
|
||||
fun load(context: Context, gameId: String): List<GameJoltBuild>? {
|
||||
val answer = GameJoltApi.overview(gameId, GameJoltAuth.cookies(context))
|
||||
if (!answer.ok) return null
|
||||
return parse(answer.payload)
|
||||
}
|
||||
|
||||
fun byId(builds: List<GameJoltBuild>, id: String): GameJoltBuild? = builds.firstOrNull { it.id == id }
|
||||
|
||||
fun preferred(builds: List<GameJoltBuild>): GameJoltBuild? = builds.firstOrNull { it.installable }
|
||||
|
||||
fun size(context: Context, item: CatalogItem): Long {
|
||||
val gameId = item.extra["gameId"].orEmpty().ifEmpty { item.id }
|
||||
val builds = load(context, gameId) ?: return 0L
|
||||
val chosen = item.extra["buildId"]?.let { byId(builds, it) } ?: preferred(builds)
|
||||
return chosen?.size ?: 0L
|
||||
}
|
||||
|
||||
private fun releaseRank(release: JSONObject?, id: Long): Long = (release?.optLong("published_on") ?: 0L) * 1_000_000L + id
|
||||
|
||||
private fun objects(array: JSONArray?): List<JSONObject> =
|
||||
if (array == null) emptyList() else (0 until array.length()).mapNotNull { array.optJSONObject(it) }
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.droiddeck.launcher.stores.gamejolt
|
||||
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.cleanStoreText
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import java.util.TimeZone
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal object GameJoltCatalog {
|
||||
private const val PAID = "paid"
|
||||
private val sellableLogged = AtomicBoolean(false)
|
||||
|
||||
fun items(games: JSONArray?, owned: Boolean = false): List<CatalogItem> {
|
||||
if (games == null) return emptyList()
|
||||
return (0 until games.length()).mapNotNull { games.optJSONObject(it)?.let { game -> item(game, owned) } }.distinctBy { it.id }
|
||||
}
|
||||
|
||||
fun item(game: JSONObject, owned: Boolean = false): CatalogItem? {
|
||||
val id = game.optLong("id")
|
||||
if (id <= 0L) return null
|
||||
val slug = game.optString("slug")
|
||||
val sellable = game.optJSONObject("sellable")
|
||||
val paid = sellable?.optString("type") == PAID
|
||||
if (paid) noteSellable(sellable)
|
||||
val developer = game.optJSONObject("developer")
|
||||
val author = developer?.optString("display_name").orEmpty().ifBlank { developer?.optString("username").orEmpty() }
|
||||
val thumbnail = game.optJSONObject("thumbnail_media_item")?.optString("img_url").orEmpty().ifBlank { game.optString("img_thumbnail") }
|
||||
val header = game.optJSONObject("header_media_item")?.optString("img_url").orEmpty().ifBlank { game.optString("img_thumbnail") }
|
||||
val price = if (paid) GameJoltPricing.of(sellable) else null
|
||||
val compatibility = game.optJSONObject("compatibility")
|
||||
val tags = buildList {
|
||||
if (compatibility?.optBoolean("os_windows") == true) add("Windows")
|
||||
if (compatibility?.optBoolean("os_linux") == true) add("Linux")
|
||||
if (compatibility?.optBoolean("os_mac") == true) add("macOS")
|
||||
}.joinToString(", ")
|
||||
return CatalogItem(
|
||||
store = Store.GAMEJOLT,
|
||||
id = id.toString(),
|
||||
title = game.optString("title").ifBlank { "Game Jolt game $id" },
|
||||
imageUrl = header.ifBlank { null },
|
||||
tallImageUrl = thumbnail.ifBlank { null },
|
||||
tags = tags,
|
||||
isFree = !paid,
|
||||
hasPrice = paid,
|
||||
finalPrice = price?.final.orEmpty(),
|
||||
originalPrice = price?.original.orEmpty(),
|
||||
discountPercent = price?.discount ?: 0,
|
||||
owned = owned,
|
||||
storeUrl = GameJoltApi.pageUrl(slug.ifBlank { "game" }, id.toString()),
|
||||
developer = author,
|
||||
publisher = author,
|
||||
releaseDate = date(game.optLong("published_on")),
|
||||
description = cleanStoreText(game.optString("description")),
|
||||
mature = game.optBoolean("has_adult_content"),
|
||||
extra = mapOf("gameId" to id.toString(), "slug" to slug),
|
||||
)
|
||||
}
|
||||
|
||||
private fun noteSellable(sellable: JSONObject?) {
|
||||
if (sellable == null || !sellableLogged.compareAndSet(false, true)) return
|
||||
val pricing = sellable.optJSONArray("pricings")?.optJSONObject(0)
|
||||
StoresState.logLine("Game Jolt: a paid game carries sellable keys [${sellable.keys().asSequence().joinToString(",")}] and pricing keys [${pricing?.keys()?.asSequence()?.joinToString(",").orEmpty()}]")
|
||||
}
|
||||
|
||||
private fun date(stamp: Long): String {
|
||||
if (stamp <= 0L) return ""
|
||||
val millis = if (stamp > 100_000_000_000L) stamp else stamp * 1000L
|
||||
return SimpleDateFormat("yyyy-MM-dd", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }.format(Date(millis))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.droiddeck.launcher.stores.gamejolt
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.net.URLEncoder
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
internal class GameJoltCollection(val id: String, val title: String)
|
||||
|
||||
internal object GameJoltCollections {
|
||||
const val FOLLOWED = "followed"
|
||||
private const val PLAYLIST = "playlist:"
|
||||
|
||||
var list by mutableStateOf<List<GameJoltCollection>>(emptyList())
|
||||
private set
|
||||
var selected by mutableStateOf<String?>(null)
|
||||
private set
|
||||
private val games = mutableStateMapOf<String, List<CatalogItem>>()
|
||||
private val loading = ConcurrentHashMap.newKeySet<String>()
|
||||
@Volatile private var generation = 0
|
||||
|
||||
fun items(): List<CatalogItem> = games.values.flatten()
|
||||
|
||||
fun gamesOf(id: String): List<CatalogItem>? = games[id]
|
||||
|
||||
fun chosen(): GameJoltCollection? = list.firstOrNull { it.id == selected }
|
||||
|
||||
fun clear() {
|
||||
generation++
|
||||
StoresState.post {
|
||||
list = emptyList()
|
||||
selected = null
|
||||
games.clear()
|
||||
}
|
||||
}
|
||||
|
||||
fun load(context: Context) {
|
||||
val app = context.applicationContext
|
||||
val started = generation
|
||||
val guard = "$started:"
|
||||
if (!loading.add(guard)) return
|
||||
Thread({
|
||||
try {
|
||||
val cookies = GameJoltAuth.cookies(app)
|
||||
if (cookies.isBlank()) return@Thread
|
||||
val playlists = playlists(cookies) ?: return@Thread
|
||||
val parsed = listOf(GameJoltCollection(FOLLOWED, app.getString(R.string.stores_gamejolt_followed))) + parse(playlists)
|
||||
if (started != generation) return@Thread
|
||||
StoresState.post {
|
||||
if (started != generation) return@post
|
||||
list = parsed
|
||||
if (selected != null && parsed.none { it.id == selected }) selected = null
|
||||
}
|
||||
StoresState.logLine("Game Jolt: ${parsed.size} collections")
|
||||
selected?.let { fetchGames(app, it, started) }
|
||||
} finally {
|
||||
loading.remove(guard)
|
||||
}
|
||||
}, "gamejolt-collections").start()
|
||||
}
|
||||
|
||||
fun select(context: Context, id: String?) {
|
||||
selected = id
|
||||
if (id == null) return
|
||||
val app = context.applicationContext
|
||||
val started = generation
|
||||
Thread({ fetchGames(app, id, started) }, "gamejolt-collection-games").start()
|
||||
}
|
||||
|
||||
private fun playlists(cookies: String): JSONArray? {
|
||||
val library = GameJoltApi.get("/web/library", cookies)
|
||||
if (!library.ok) return null
|
||||
library.payload?.optJSONArray("playlists")?.let { return it }
|
||||
val nested = library.payload?.optJSONArray("collections")
|
||||
if (nested != null) {
|
||||
val out = JSONArray()
|
||||
for (i in 0 until nested.length()) nested.optJSONObject(i)?.optJSONObject("playlist")?.let { out.put(it) }
|
||||
if (out.length() > 0) return out
|
||||
}
|
||||
return GameJoltApi.get("/web/library/playlists", cookies).takeIf { it.ok }?.payload?.optJSONArray("playlists") ?: JSONArray()
|
||||
}
|
||||
|
||||
internal fun parse(playlists: JSONArray): List<GameJoltCollection> = (0 until playlists.length()).mapNotNull { i ->
|
||||
val playlist = playlists.optJSONObject(i) ?: return@mapNotNull null
|
||||
val id = playlist.optLong("id").takeIf { it > 0L } ?: return@mapNotNull null
|
||||
val title = playlist.optString("name").ifBlank { return@mapNotNull null }
|
||||
GameJoltCollection("$PLAYLIST$id", title)
|
||||
}
|
||||
|
||||
internal fun path(id: String, username: String): String? = when {
|
||||
id == FOLLOWED -> "/web/library/games/followed/@${URLEncoder.encode(username, "UTF-8")}"
|
||||
id.startsWith(PLAYLIST) -> id.removePrefix(PLAYLIST).toLongOrNull()?.let { "/web/library/games/playlist/$it" }
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun fetchGames(app: Context, id: String, started: Int) {
|
||||
val guard = "$started:$id"
|
||||
if (!loading.add(guard)) return
|
||||
try {
|
||||
val path = path(id, GameJoltAuth.username(app)) ?: return
|
||||
val found = GameJoltLibrary.games(app, path, false)
|
||||
if (found == null) {
|
||||
StoresState.logLine("Game Jolt: collection $id failed")
|
||||
return
|
||||
}
|
||||
StoresState.post { if (started == generation) games[id] = found }
|
||||
StoresState.logLine("Game Jolt: collection $id has ${found.size} games")
|
||||
} finally {
|
||||
loading.remove(guard)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package com.droiddeck.launcher.stores.gamejolt
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreArchiveUnpacker
|
||||
import com.droiddeck.launcher.stores.StoreExe
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreInstalls
|
||||
import com.droiddeck.launcher.stores.StoreNet
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import com.droiddeck.launcher.stores.itch.ItchArchives
|
||||
import com.droiddeck.launcher.stores.itch.ItchStaging
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal class GameJoltInstaller(
|
||||
private val app: Context,
|
||||
private val item: CatalogItem,
|
||||
private val folder: File,
|
||||
) : DownloadQueue.DownloadJob {
|
||||
private val cancelled = AtomicBoolean(false)
|
||||
private var work: File = folder
|
||||
private var updating = false
|
||||
private var previous: StoreGameSidecar? = null
|
||||
private val commit = Any()
|
||||
private val unpacker = StoreArchiveUnpacker(app, cancelled, "Game Jolt", R.string.stores_gamejolt_archive, R.string.stores_gamejolt_extract_failed, "gamejolt-unrar")
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
val cookies = GameJoltAuth.cookies(app)
|
||||
if (cookies.isBlank()) throw IllegalStateException(app.getString(R.string.stores_sync_sign_in))
|
||||
if (!item.isFree && !item.owned) throw IllegalStateException(app.getString(R.string.stores_gamejolt_not_owned))
|
||||
val gameId = item.extra["gameId"].orEmpty().ifEmpty { item.id }
|
||||
val before = StoreGameSidecar.read(folder)
|
||||
previous = before
|
||||
updating = before != null && (before.isInstalled || before.state == StoreGameSidecar.STATE_UPDATING)
|
||||
val resuming = before?.let { it.state == StoreGameSidecar.STATE_INSTALLING && it.id == item.id } == true
|
||||
StoreInstalls.begin(folder, Store.GAMEJOLT, item.id, item.title, item.imageUrl, item.imageUrl)
|
||||
handle.stage(DownloadStage.MANIFEST)
|
||||
val builds = GameJoltBuilds.load(app, gameId) ?: throw IllegalStateException(app.getString(R.string.stores_gamejolt_no_game))
|
||||
val chosen = item.extra["buildId"].orEmpty()
|
||||
val build = (if (chosen.isBlank()) GameJoltBuilds.preferred(builds) else GameJoltBuilds.byId(builds, chosen))?.takeIf { it.installable }
|
||||
?: throw IllegalStateException(app.getString(R.string.stores_gamejolt_no_build))
|
||||
handle.log("Game Jolt: installing build ${build.id} (${build.filename}, ${build.size} bytes, platforms ${build.platforms.joinToString(",")}, launch ${build.executable.ifBlank { "none" }})")
|
||||
val scratch = StoreInstallRoot.scratchDir(app, Store.GAMEJOLT, item.id)
|
||||
scratch.mkdirs()
|
||||
val filename = build.filename.trim().takeUnless { it.isBlank() || it == "." || it == ".." } ?: "download.bin"
|
||||
val archive = File(scratch, filename)
|
||||
val exe = try {
|
||||
handle.stage(DownloadStage.DOWNLOAD)
|
||||
download(build, archive, handle)
|
||||
if (cancelled.get()) return null
|
||||
handle.stage(DownloadStage.INSTALL)
|
||||
install(build, archive, filename, handle, resuming)
|
||||
} catch (t: Throwable) {
|
||||
if (!cancelled.get()) dropCaches(scratch)
|
||||
throw t
|
||||
}
|
||||
if (exe == null) {
|
||||
if (cancelled.get()) return null
|
||||
dropCaches(scratch)
|
||||
throw IllegalStateException(app.getString(R.string.stores_gamejolt_no_exe))
|
||||
}
|
||||
archive.delete()
|
||||
StoreInstalls.deleteTree(scratch)
|
||||
val sidecar = StoreGameSidecar(
|
||||
store = Store.GAMEJOLT,
|
||||
id = item.id,
|
||||
title = item.title,
|
||||
exe = exe,
|
||||
args = previous?.args.orEmpty(),
|
||||
env = previous?.env.orEmpty(),
|
||||
installVersion = build.stamp,
|
||||
installedAt = System.currentTimeMillis(),
|
||||
cover = item.imageUrl,
|
||||
hero = item.imageUrl,
|
||||
extra = mapOf("gameId" to gameId, "buildId" to build.id, "packageId" to build.packageId) + (if (item.isFree) emptyMap() else mapOf("paid" to "1")),
|
||||
cloud = false,
|
||||
)
|
||||
StoreInstalls.complete(app, folder, sidecar) { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) }
|
||||
GameJoltUpdates.applied(app, item.key)
|
||||
return folder.path
|
||||
}
|
||||
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
if (deleteFiles) dropCaches(StoreInstallRoot.scratchDir(app, Store.GAMEJOLT, item.id))
|
||||
}
|
||||
|
||||
private fun dropCaches(scratch: File) {
|
||||
if (!updating) {
|
||||
StoreInstalls.discard(app, folder, listOf(scratch))
|
||||
return
|
||||
}
|
||||
synchronized(commit) {
|
||||
StoreInstalls.deleteTree(scratch)
|
||||
ItchStaging.delete(File(folder, ItchStaging.DIR))
|
||||
}
|
||||
}
|
||||
|
||||
private fun download(build: GameJoltBuild, target: File, handle: DownloadQueue.JobHandle) {
|
||||
val origin = File(target.path + ".from")
|
||||
val stamp = "${build.id} ${build.stamp} ${build.size}"
|
||||
if (!target.isFile || runCatching { origin.readText() }.getOrNull() != stamp) {
|
||||
target.delete()
|
||||
origin.writeText(stamp)
|
||||
}
|
||||
val expected = build.size
|
||||
if (expected > 0 && target.length() == expected) {
|
||||
handle.progress(expected, expected)
|
||||
return
|
||||
}
|
||||
for (attempt in 0..1) {
|
||||
val have = target.length()
|
||||
val url = downloadLink(build)
|
||||
var conn: HttpURLConnection? = null
|
||||
try {
|
||||
conn = (URL(url).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = 30_000
|
||||
readTimeout = 60_000
|
||||
instanceFollowRedirects = true
|
||||
setRequestProperty("User-Agent", StoreNet.BROWSER_UA)
|
||||
setRequestProperty("Accept", "*/*")
|
||||
if (have > 0) setRequestProperty("Range", "bytes=$have-")
|
||||
}
|
||||
val code = conn.responseCode
|
||||
if (code == 416 && attempt == 0) {
|
||||
target.delete()
|
||||
continue
|
||||
}
|
||||
if (code !in 200..299) throw IllegalStateException(app.getString(R.string.stores_gamejolt_download_failed, code))
|
||||
val append = code == 206 && have > 0
|
||||
if (have > 0) handle.log(if (append) "Game Jolt: resuming at $have bytes" else "Game Jolt: server ignored the resume, starting over")
|
||||
var done = if (append) have else 0L
|
||||
val total = conn.contentLengthLong.takeIf { it > 0 }?.let { if (append) it + have else it } ?: expected
|
||||
handle.progress(done, total)
|
||||
val buffer = ByteArray(128 * 1024)
|
||||
conn.inputStream.use { input ->
|
||||
FileOutputStream(target, append).use { out ->
|
||||
while (true) {
|
||||
if (cancelled.get()) return
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
done += read
|
||||
handle.progress(done, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (total > 0 && done < total) throw IllegalStateException(app.getString(R.string.stores_gamejolt_download_failed, code))
|
||||
return
|
||||
} finally {
|
||||
runCatching { conn?.disconnect() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun downloadLink(build: GameJoltBuild): String {
|
||||
val answer = GameJoltApi.post("/web/discover/games/builds/get-download-url/${build.id}", GameJoltAuth.cookies(app))
|
||||
val url = answer.payload?.optString("url").orEmpty()
|
||||
if (url.startsWith("https://")) return url
|
||||
throw IllegalStateException(
|
||||
when {
|
||||
answer.code == 0 -> app.getString(R.string.stores_gamejolt_download_unreachable)
|
||||
answer.ok -> app.getString(R.string.stores_gamejolt_download_no_link)
|
||||
else -> app.getString(R.string.stores_gamejolt_download_failed, answer.code)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private fun clearPartialInstall() {
|
||||
folder.listFiles()?.forEach {
|
||||
if (it.name == StoreGameSidecar.FILE_NAME) return@forEach
|
||||
if (it.isDirectory) StoreInstalls.deleteTree(it) else it.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun install(build: GameJoltBuild, archive: File, filename: String, handle: DownloadQueue.JobHandle, resuming: Boolean): String? {
|
||||
work = if (updating) File(folder, ItchStaging.DIR) else folder
|
||||
if (updating) ItchStaging.delete(work)
|
||||
work.mkdirs()
|
||||
unpacker.work = work
|
||||
if (resuming) clearPartialInstall()
|
||||
val exe = try {
|
||||
val kind = ItchArchives.kind(archive, filename)
|
||||
if (kind == "exe") archive.copyTo(File(work, filename), overwrite = true) else unpacker.unpack(archive, filename, handle)
|
||||
var picked = pick(build, filename)
|
||||
var passes = 0
|
||||
while (picked.isBlank() && passes < 2 && !cancelled.get()) {
|
||||
val inner = ItchArchives.inner(work) ?: break
|
||||
handle.log("Game Jolt: no exe yet, unpacking ${inner.name}")
|
||||
unpacker.unpack(inner, inner.name, handle)
|
||||
if (cancelled.get()) break
|
||||
inner.delete()
|
||||
picked = pick(build, inner.name.substringBeforeLast('.').takeIf { it.endsWith(".exe", ignoreCase = true) })
|
||||
passes++
|
||||
}
|
||||
picked
|
||||
} catch (t: Throwable) {
|
||||
if (updating) ItchStaging.delete(work)
|
||||
throw t
|
||||
}
|
||||
if (exe.isBlank()) {
|
||||
handle.log("Game Jolt: no exe found in ${folder.name}")
|
||||
if (updating) ItchStaging.delete(work)
|
||||
return null
|
||||
}
|
||||
if (updating) synchronized(commit) {
|
||||
if (cancelled.get()) {
|
||||
ItchStaging.delete(work)
|
||||
return null
|
||||
}
|
||||
try {
|
||||
StoreInstalls.markUpdating(folder)
|
||||
} catch (t: Throwable) {
|
||||
ItchStaging.delete(work)
|
||||
throw t
|
||||
}
|
||||
ItchStaging.merge(work, folder)
|
||||
ItchStaging.delete(work)
|
||||
}
|
||||
return exe
|
||||
}
|
||||
|
||||
private fun pick(build: GameJoltBuild, hint: String?): String {
|
||||
if (build.executable.isNotBlank()) {
|
||||
val declared = File(work, build.executable.trimStart('/'))
|
||||
val inside = runCatching { declared.canonicalPath.startsWith(work.canonicalPath + File.separator) }.getOrDefault(false)
|
||||
if (inside && declared.isFile) return declared.relativeTo(work).path
|
||||
}
|
||||
return StoreExe.pick(work, hint?.ifBlank { null } ?: build.filename.substringBeforeLast('.').ifBlank { null }, item.title)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.droiddeck.launcher.stores.gamejolt
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.mergeItems
|
||||
import java.net.URLEncoder
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal object GameJoltLibrary {
|
||||
private const val MAX_PAGES = 20
|
||||
private const val THROTTLE_MS = 10 * 60 * 1000L
|
||||
|
||||
private val running = AtomicBoolean(false)
|
||||
@Volatile private var syncedAt = 0L
|
||||
|
||||
fun sync(context: Context, force: Boolean) {
|
||||
val app = context.applicationContext
|
||||
if (!running.compareAndSet(false, true)) return
|
||||
try {
|
||||
val cookies = GameJoltAuth.cookies(app)
|
||||
val name = GameJoltAuth.username(app)
|
||||
if (cookies.isBlank() || name.isBlank()) {
|
||||
StoresState.post {
|
||||
StoresState.status.remove(Store.GAMEJOLT)
|
||||
StoresState.problems[Store.GAMEJOLT] = app.getString(R.string.stores_sync_sign_in)
|
||||
}
|
||||
return
|
||||
}
|
||||
val have = StoresState.library[Store.GAMEJOLT].orEmpty()
|
||||
if (!force && have.isNotEmpty() && System.currentTimeMillis() - syncedAt < THROTTLE_MS) return
|
||||
if (have.isEmpty()) StoresState.post { StoresState.status[Store.GAMEJOLT] = app.getString(R.string.stores_sync_game_list) }
|
||||
val items = games(app, "/web/library/games/owned/@${URLEncoder.encode(name, "UTF-8")}", true)
|
||||
if (items == null) {
|
||||
StoresState.post {
|
||||
StoresState.status.remove(Store.GAMEJOLT)
|
||||
StoresState.problems[Store.GAMEJOLT] = app.getString(R.string.stores_sync_failed)
|
||||
}
|
||||
return
|
||||
}
|
||||
syncedAt = System.currentTimeMillis()
|
||||
StoresState.post {
|
||||
StoresState.status.remove(Store.GAMEJOLT)
|
||||
StoresState.problems.remove(Store.GAMEJOLT)
|
||||
StoresState.library[Store.GAMEJOLT] = mergeItems(StoresState.library[Store.GAMEJOLT], items)
|
||||
}
|
||||
StoresState.logLine("Game Jolt: ${items.size} owned games")
|
||||
} finally {
|
||||
running.set(false)
|
||||
}
|
||||
}
|
||||
|
||||
fun reset() {
|
||||
syncedAt = 0L
|
||||
}
|
||||
|
||||
fun games(context: Context, path: String, owned: Boolean): List<CatalogItem>? {
|
||||
val cookies = GameJoltAuth.cookies(context)
|
||||
val out = ArrayList<CatalogItem>()
|
||||
val seen = HashSet<String>()
|
||||
for (page in 1..MAX_PAGES) {
|
||||
val answer = GameJoltApi.get(if (page == 1) path else "$path?page=$page", cookies)
|
||||
if (!answer.ok) return if (page == 1) null else out
|
||||
val batch = GameJoltCatalog.items(answer.payload?.optJSONArray("games"), owned).filter { seen.add(it.id) }
|
||||
if (batch.isEmpty()) break
|
||||
out.addAll(batch)
|
||||
val total = answer.payload?.optInt("totalGamesCount") ?: 0
|
||||
if (total in 1..out.size) break
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.droiddeck.launcher.stores.gamejolt
|
||||
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import android.webkit.CookieManager
|
||||
import android.webkit.WebView
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.StoreLoginActivity
|
||||
import com.droiddeck.launcher.stores.WebCookies
|
||||
|
||||
internal class GameJoltLogin(override val userAgent: String) : StoreLoginActivity.Flow {
|
||||
override val startUrl: String get() = GameJoltApi.LOGIN
|
||||
|
||||
override fun isRedirect(url: String): Boolean {
|
||||
val uri = Uri.parse(url)
|
||||
if (uri.host != HOST && uri.host != "www.$HOST") return false
|
||||
val path = uri.path.orEmpty()
|
||||
return AUTH_PATHS.none { path == it || path.startsWith("$it/") }
|
||||
}
|
||||
|
||||
override fun forgetSignIn(done: () -> Unit) {
|
||||
runCatching { WebCookies.expire(listOf(GameJoltApi.SITE), HOST, listOf("/")) { done() } }
|
||||
.onFailure {
|
||||
Log.w(TAG, "could not clear the previous web sign-in: ${it.javaClass.simpleName}")
|
||||
done()
|
||||
}
|
||||
}
|
||||
|
||||
override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? {
|
||||
val manager = CookieManager.getInstance()
|
||||
manager.flush()
|
||||
val cookies = manager.getCookie(GameJoltApi.SITE).orEmpty()
|
||||
if (cookies.isBlank()) {
|
||||
Log.w(TAG, "no cookies after the sign-in redirect")
|
||||
return activity.getString(R.string.stores_login_error_verification)
|
||||
}
|
||||
val answer = GameJoltApi.get("/web/search/games?q=a", cookies)
|
||||
val user = answer.user
|
||||
Log.d(TAG, "verify: code=${answer.code} cookies=${cookies.split(';').joinToString(",") { it.substringBefore('=').trim() }} userKeys=${user?.keys()?.asSequence()?.joinToString(",").orEmpty()}")
|
||||
if (user == null || user.optLong("id") <= 0L) return activity.getString(R.string.stores_login_error_verification)
|
||||
return try {
|
||||
GameJoltAuth.save(activity, cookies, user)
|
||||
null
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "saving the sign-in failed: ${e.javaClass.simpleName}")
|
||||
activity.getString(R.string.stores_login_error_generic)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "GameJoltLogin"
|
||||
private const val HOST = "gamejolt.com"
|
||||
private val AUTH_PATHS = listOf("/login", "/join", "/auth", "/forgot", "/terms", "/privacy", "/help", "/legal", "/site-api", "/x", "/oauth")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.droiddeck.launcher.stores.gamejolt
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
|
||||
object GameJoltPrefs {
|
||||
const val FILE = "stores.gamejolt"
|
||||
|
||||
@JvmStatic
|
||||
fun get(context: Context): SharedPreferences = context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.droiddeck.launcher.stores.gamejolt
|
||||
|
||||
import org.json.JSONObject
|
||||
import java.util.Locale
|
||||
|
||||
internal object GameJoltPricing {
|
||||
class Price(val final: String, val original: String, val discount: Int)
|
||||
|
||||
fun of(sellable: JSONObject?): Price? {
|
||||
val list = sellable?.optJSONArray("pricings") ?: return null
|
||||
val entries = (0 until list.length()).mapNotNull { list.optJSONObject(it) }.filter { it.optLong("amount") > 0L }
|
||||
val sale = entries.firstOrNull { it.optBoolean("promotional") }
|
||||
val regular = entries.firstOrNull { !it.optBoolean("promotional") }
|
||||
val now = sale ?: regular ?: return null
|
||||
val was = if (sale != null && regular != null && regular.optLong("amount") > sale.optLong("amount")) regular else null
|
||||
val percent = if (was == null) 0 else {
|
||||
val before = was.optLong("amount")
|
||||
(((before - now.optLong("amount")) * 100 + before / 2) / before).toInt()
|
||||
}
|
||||
return Price(format(now), was?.let(::format).orEmpty(), percent)
|
||||
}
|
||||
|
||||
private fun format(pricing: JSONObject): String {
|
||||
val amount = String.format(Locale.US, "%.2f", pricing.optLong("amount") / 100.0)
|
||||
val currency = pricing.optString("currency_code").takeIf { it.isNotBlank() && it != "null" && !it.equals("USD", ignoreCase = true) }
|
||||
return if (currency == null) "$$amount" else "$amount $currency"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package com.droiddeck.launcher.stores.gamejolt
|
||||
|
||||
import android.content.Context
|
||||
import android.widget.Toast
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal class GameJoltUpdate(val buildId: String, val stamp: String, val filename: String, val replaced: Boolean)
|
||||
|
||||
internal object GameJoltUpdates {
|
||||
private const val KEY_AT = "updates_checked_at"
|
||||
private const val KEY_FOUND = "updates_found"
|
||||
private const val THROTTLE_MS = 6 * 60 * 60 * 1000L
|
||||
private const val GAP_MS = 1_000L
|
||||
|
||||
val available = mutableStateMapOf<String, GameJoltUpdate>()
|
||||
var checkingKey by mutableStateOf<String?>(null)
|
||||
private set
|
||||
|
||||
private val running = AtomicBoolean(false)
|
||||
private val restored = AtomicBoolean(false)
|
||||
@Volatile private var generation = 0
|
||||
|
||||
internal fun evaluate(builds: List<GameJoltBuild>?, buildId: String, packageId: String, version: String): GameJoltUpdate? {
|
||||
if (builds == null || buildId.isBlank()) return null
|
||||
val installable = builds.filter { it.installable }
|
||||
val samePackage = installable.filter { it.packageId == packageId }
|
||||
if (samePackage.isNotEmpty()) {
|
||||
if (samePackage.any { it.id == buildId }) return null
|
||||
val same = samePackage.firstOrNull { newer(it, buildId, version) } ?: return null
|
||||
return GameJoltUpdate(same.id, same.stamp, same.filename, false)
|
||||
}
|
||||
val next = installable.firstOrNull() ?: return null
|
||||
return if (next.id == buildId) null else GameJoltUpdate(next.id, next.stamp, next.filename, true)
|
||||
}
|
||||
|
||||
private fun newer(build: GameJoltBuild, buildId: String, version: String): Boolean {
|
||||
val stamp = build.stamp.toLongOrNull() ?: 0L
|
||||
val have = version.toLongOrNull() ?: 0L
|
||||
if (stamp != have) return stamp > have
|
||||
return (build.id.toLongOrNull() ?: 0L) > (buildId.toLongOrNull() ?: 0L)
|
||||
}
|
||||
|
||||
internal fun encode(found: Map<String, GameJoltUpdate>): String = JSONObject().also { out ->
|
||||
for ((key, u) in found) out.put(key, JSONObject().put("buildId", u.buildId).put("stamp", u.stamp).put("filename", u.filename).put("replaced", u.replaced))
|
||||
}.toString()
|
||||
|
||||
internal fun decode(raw: String?): Map<String, GameJoltUpdate> {
|
||||
val json = runCatching { JSONObject(raw.orEmpty()) }.getOrNull() ?: return emptyMap()
|
||||
val out = LinkedHashMap<String, GameJoltUpdate>()
|
||||
for (key in json.keys()) {
|
||||
val u = json.optJSONObject(key) ?: continue
|
||||
val id = u.optString("buildId")
|
||||
if (id.isBlank()) continue
|
||||
out[key] = GameJoltUpdate(id, u.optString("stamp"), u.optString("filename"), u.optBoolean("replaced"))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun restore(app: Context) {
|
||||
if (!restored.compareAndSet(false, true)) return
|
||||
val started = generation
|
||||
val saved = decode(GameJoltPrefs.get(app).getString(KEY_FOUND, null))
|
||||
StoresState.post {
|
||||
if (started != generation) return@post
|
||||
for ((k, v) in saved) if (k !in available) available[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
private fun save(app: Context) {
|
||||
GameJoltPrefs.get(app).edit().putString(KEY_FOUND, encode(available.toMap())).apply()
|
||||
}
|
||||
|
||||
private fun snapshot(game: InstalledStoreGame): Triple<String, String, String> =
|
||||
Triple(game.sidecar.installVersion, game.sidecar.extra["buildId"].orEmpty(), game.sidecar.extra["packageId"].orEmpty())
|
||||
|
||||
fun check(context: Context) {
|
||||
val app = context.applicationContext
|
||||
if (!running.compareAndSet(false, true)) return
|
||||
val started = generation
|
||||
Thread({
|
||||
try {
|
||||
restore(app)
|
||||
val prefs = GameJoltPrefs.get(app)
|
||||
if (System.currentTimeMillis() - prefs.getLong(KEY_AT, 0L) < THROTTLE_MS) return@Thread
|
||||
if (GameJoltAuth.cookies(app).isBlank()) return@Thread
|
||||
val games = StoresState.installed.toList().filter { it.sidecar.store == Store.GAMEJOLT && it.sidecar.isInstalled }
|
||||
val found = LinkedHashMap<String, GameJoltUpdate>()
|
||||
val answered = HashSet<String>()
|
||||
val seen = HashMap<String, Triple<String, String, String>>()
|
||||
var failed = false
|
||||
games.forEachIndexed { i, game ->
|
||||
if (i > 0) Thread.sleep(GAP_MS)
|
||||
val extra = game.sidecar.extra
|
||||
seen[game.key] = snapshot(game)
|
||||
val builds = GameJoltBuilds.load(app, extra["gameId"].orEmpty().ifEmpty { game.sidecar.id })
|
||||
if (builds == null) failed = true
|
||||
else {
|
||||
answered += game.key
|
||||
evaluate(builds, extra["buildId"].orEmpty(), extra["packageId"].orEmpty(), game.sidecar.installVersion)?.let { found[game.key] = it }
|
||||
}
|
||||
}
|
||||
if (started != generation) return@Thread
|
||||
StoresState.post {
|
||||
if (started != generation) return@post
|
||||
for (k in answered) {
|
||||
val now = StoresState.installed.firstOrNull { it.key == k } ?: continue
|
||||
if (seen[k] != snapshot(now)) continue
|
||||
val u = found[k]
|
||||
if (u != null) available[k] = u else available.remove(k)
|
||||
}
|
||||
save(app)
|
||||
}
|
||||
if (!failed && started == generation) prefs.edit().putLong(KEY_AT, System.currentTimeMillis()).apply()
|
||||
StoresState.logLine("Game Jolt: checked ${games.size} installed games, ${found.size} with updates")
|
||||
} finally {
|
||||
running.set(false)
|
||||
}
|
||||
}, "gamejolt-updates").start()
|
||||
}
|
||||
|
||||
fun checkGame(context: Context, game: InstalledStoreGame) {
|
||||
val app = context.applicationContext
|
||||
if (checkingKey != null) return
|
||||
checkingKey = game.key
|
||||
val started = generation
|
||||
val before = snapshot(game)
|
||||
Thread({
|
||||
try {
|
||||
val extra = game.sidecar.extra
|
||||
val builds = GameJoltBuilds.load(app, extra["gameId"].orEmpty().ifEmpty { game.sidecar.id })
|
||||
val found = evaluate(builds, before.second, before.third, before.first)
|
||||
StoresState.post {
|
||||
if (started != generation) return@post
|
||||
val now = StoresState.installed.firstOrNull { it.key == game.key }
|
||||
if (builds != null && now != null && snapshot(now) == before) {
|
||||
if (found != null) available[game.key] = found else available.remove(game.key)
|
||||
save(app)
|
||||
}
|
||||
val text = when {
|
||||
builds == null -> app.getString(R.string.stores_sync_failed)
|
||||
found != null -> app.getString(R.string.stores_itch_updates_found, 1)
|
||||
else -> app.getString(R.string.upd_current_status)
|
||||
}
|
||||
Toast.makeText(app, text, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
StoresState.logLine("Game Jolt: checked ${game.sidecar.title}, ${if (found != null) "update available" else "up to date"}")
|
||||
} finally {
|
||||
StoresState.post { checkingKey = null }
|
||||
}
|
||||
}, "gamejolt-update-check").start()
|
||||
}
|
||||
|
||||
fun start(context: Context, game: InstalledStoreGame, update: GameJoltUpdate) {
|
||||
val app = context.applicationContext
|
||||
if (StoresState.uninstalling.containsKey(game.key)) return
|
||||
val root = game.folder.parentFile?.parentFile ?: return
|
||||
val item = CatalogItem(
|
||||
Store.GAMEJOLT, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover,
|
||||
isFree = game.sidecar.extra["paid"] != "1", owned = true, extra = game.sidecar.extra + ("buildId" to update.buildId),
|
||||
)
|
||||
StoresState.install(app, item, root)
|
||||
}
|
||||
|
||||
fun applied(context: Context, key: String) {
|
||||
val app = context.applicationContext
|
||||
StoresState.post {
|
||||
available.remove(key)
|
||||
save(app)
|
||||
}
|
||||
}
|
||||
|
||||
fun clear(context: Context) {
|
||||
val app = context.applicationContext
|
||||
generation++
|
||||
GameJoltPrefs.get(app).edit().remove(KEY_AT).remove(KEY_FOUND).apply()
|
||||
StoresState.post { available.clear() }
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,9 @@ package com.droiddeck.launcher.stores.itch
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.GuestCommand
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreArchiveUnpacker
|
||||
import com.droiddeck.launcher.stores.StoreExe
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
@@ -13,20 +12,10 @@ import com.droiddeck.launcher.stores.StoreInstalls
|
||||
import com.droiddeck.launcher.stores.StoreNet
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import org.apache.commons.compress.MemoryLimitException
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZFile
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
|
||||
import org.apache.commons.compress.archivers.zip.ZipFile
|
||||
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream
|
||||
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream
|
||||
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream
|
||||
import java.io.BufferedInputStream
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.nio.file.Files
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal class ItchInstaller(
|
||||
@@ -39,6 +28,7 @@ internal class ItchInstaller(
|
||||
private var updating = false
|
||||
private var previous: StoreGameSidecar? = null
|
||||
private val commit = Any()
|
||||
private val unpacker = StoreArchiveUnpacker(app, cancelled, "itch.io", R.string.stores_itch_archive, R.string.stores_itch_extract_failed, "itch-unrar")
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
val key = ItchAuth.key(app)
|
||||
@@ -225,16 +215,17 @@ internal class ItchInstaller(
|
||||
work = if (updating) File(folder, ItchStaging.DIR) else folder
|
||||
if (updating && !patched) ItchStaging.delete(work)
|
||||
work.mkdirs()
|
||||
unpacker.work = work
|
||||
if (resuming) clearPartialInstall()
|
||||
val exe = try {
|
||||
if (!patched) unpack(archive, filename, handle)
|
||||
if (!patched) unpacker.unpack(archive, filename, handle)
|
||||
val hint = filename.substringBeforeLast('.')
|
||||
var picked = StoreExe.pick(work, hint.ifBlank { null }, item.title)
|
||||
var passes = 0
|
||||
while (picked.isBlank() && passes < 2 && !cancelled.get()) {
|
||||
val inner = ItchArchives.inner(work) ?: break
|
||||
handle.log("itch.io: no exe yet, unpacking ${inner.name}")
|
||||
unpack(inner, inner.name, handle)
|
||||
unpacker.unpack(inner, inner.name, handle)
|
||||
if (cancelled.get()) break
|
||||
inner.delete()
|
||||
picked = StoreExe.pick(work, inner.name.substringBeforeLast('.').takeIf { it.endsWith(".exe", ignoreCase = true) }, item.title)
|
||||
@@ -267,205 +258,5 @@ internal class ItchInstaller(
|
||||
return exe
|
||||
}
|
||||
|
||||
private fun unpack(archive: File, filename: String, handle: DownloadQueue.JobHandle) {
|
||||
when (val kind = ItchArchives.kind(archive, filename)) {
|
||||
"zip" -> unzip(archive, handle)
|
||||
"7z" -> try {
|
||||
sevenZip(archive, handle)
|
||||
} catch (e: MemoryLimitException) {
|
||||
handle.log("itch.io: ${archive.name} needs more memory than the app has, unpacking it in the runtime")
|
||||
unrar(archive, handle, kind)
|
||||
}
|
||||
"rar" -> unrar(archive, handle, kind)
|
||||
"exe" -> copy(archive, File(work, filename.ifBlank { "game.exe" }))
|
||||
"tar" -> untar(archive, null, handle)
|
||||
"gz", "bz2", "xz" -> untar(archive, kind, handle) ?: single(archive, kind, handle)
|
||||
else -> copy(archive, File(work, filename.ifBlank { "game" }))
|
||||
}
|
||||
}
|
||||
|
||||
private fun target(name: String): File? {
|
||||
val file = File(work, name.replace('\\', '/'))
|
||||
val root = work.canonicalPath
|
||||
val path = file.canonicalPath
|
||||
return if (path == root || path.startsWith(root + File.separator)) file else null
|
||||
}
|
||||
|
||||
private fun unrar(archive: File, handle: DownloadQueue.JobHandle, kind: String) {
|
||||
if (!LinuxRuntime.isInstalled(app)) throw IllegalStateException(app.getString(R.string.stores_itch_archive, kind))
|
||||
val binds = if (listOf(app.filesDir, app.cacheDir).any { work.absolutePath.startsWith(it.absolutePath + "/") }) null
|
||||
else listOf(work.absolutePath)
|
||||
fun bsdtar(args: List<String>, onLine: (String) -> Unit) =
|
||||
GuestCommand.run(app, listOf("/usr/bin/bsdtar") + args, logName = "itch-unrar", extraBinds = binds, fastPath = true, cancelled = cancelled) { line ->
|
||||
if (!line.startsWith("proot ")) onLine(line)
|
||||
}
|
||||
var entries = 0L
|
||||
bsdtar(listOf("-tf", archive.absolutePath)) { entries++ }
|
||||
var done = 0L
|
||||
val tail = ArrayDeque<String>()
|
||||
val code = bsdtar(listOf("-xvf", archive.absolutePath, "-C", work.absolutePath)) { line ->
|
||||
if (line.startsWith("x ")) handle.stageProgress(++done, entries) else {
|
||||
if (tail.size == 5) tail.removeFirst()
|
||||
tail.addLast(line)
|
||||
}
|
||||
}
|
||||
if (cancelled.get()) return
|
||||
if (code != 0) {
|
||||
handle.log("itch.io: bsdtar exited $code: ${tail.joinToString(" | ")}")
|
||||
throw IllegalStateException(app.getString(R.string.stores_itch_extract_failed, code))
|
||||
}
|
||||
}
|
||||
|
||||
private fun sevenZip(archive: File, handle: DownloadQueue.JobHandle) {
|
||||
val total = archive.length()
|
||||
var written = 0L
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
val limitKb = (Runtime.getRuntime().maxMemory() / 4 / 1024).coerceIn(32L * 1024, Int.MAX_VALUE.toLong()).toInt()
|
||||
Files.newByteChannel(archive.toPath()).use { channel ->
|
||||
SevenZFile.builder().setSeekableByteChannel(channel).setMaxMemoryLimitKb(limitKb).get().use { seven ->
|
||||
while (true) {
|
||||
if (cancelled.get()) return
|
||||
val entry = seven.nextEntry ?: break
|
||||
val file = target(entry.name)
|
||||
if (file == null) {
|
||||
handle.log("itch.io: skipped an entry outside the game folder")
|
||||
continue
|
||||
}
|
||||
if (entry.isDirectory) {
|
||||
file.mkdirs()
|
||||
continue
|
||||
}
|
||||
file.parentFile?.mkdirs()
|
||||
FileOutputStream(file).use { out ->
|
||||
while (true) {
|
||||
if (cancelled.get()) return
|
||||
val read = seven.read(buffer, 0, buffer.size)
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
written += read
|
||||
handle.stageProgress(written, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun untar(archive: File, codec: String?, handle: DownloadQueue.JobHandle): Unit? {
|
||||
val total = archive.length()
|
||||
var written = 0L
|
||||
var entries = 0
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
val opened = runCatching {
|
||||
FileInputStream(archive).use { raw ->
|
||||
val stream = when (codec) {
|
||||
"gz" -> GzipCompressorInputStream(BufferedInputStream(raw))
|
||||
"bz2" -> BZip2CompressorInputStream(BufferedInputStream(raw))
|
||||
"xz" -> XZCompressorInputStream(BufferedInputStream(raw))
|
||||
else -> BufferedInputStream(raw)
|
||||
}
|
||||
stream.use { input ->
|
||||
TarArchiveInputStream(input).use { tar ->
|
||||
while (true) {
|
||||
if (cancelled.get()) return null
|
||||
val entry = tar.nextEntry ?: break
|
||||
entries++
|
||||
val file = target(entry.name)
|
||||
if (file == null) {
|
||||
handle.log("itch.io: skipped an entry outside the game folder")
|
||||
continue
|
||||
}
|
||||
if (entry.isDirectory) {
|
||||
file.mkdirs()
|
||||
continue
|
||||
}
|
||||
file.parentFile?.mkdirs()
|
||||
FileOutputStream(file).use { out ->
|
||||
while (true) {
|
||||
if (cancelled.get()) return null
|
||||
val read = tar.read(buffer, 0, buffer.size)
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
written += read
|
||||
handle.stageProgress(written, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
if (opened.isSuccess && entries > 0) return Unit
|
||||
if (opened.isFailure && codec == null) throw opened.exceptionOrNull() ?: IllegalStateException("tar")
|
||||
return null
|
||||
}
|
||||
|
||||
private fun single(archive: File, codec: String, handle: DownloadQueue.JobHandle) {
|
||||
val name = archive.name.substringBeforeLast('.')
|
||||
val file = target(name.ifBlank { "game" }) ?: throw IllegalStateException("archive")
|
||||
file.parentFile?.mkdirs()
|
||||
val total = archive.length()
|
||||
var written = 0L
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
FileInputStream(archive).use { raw ->
|
||||
val stream = when (codec) {
|
||||
"bz2" -> BZip2CompressorInputStream(BufferedInputStream(raw))
|
||||
"xz" -> XZCompressorInputStream(BufferedInputStream(raw))
|
||||
else -> GzipCompressorInputStream(BufferedInputStream(raw))
|
||||
}
|
||||
stream.use { input ->
|
||||
FileOutputStream(file).use { out ->
|
||||
while (true) {
|
||||
if (cancelled.get()) return
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
written += read
|
||||
handle.stageProgress(written, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun copy(source: File, target: File) {
|
||||
target.parentFile?.mkdirs()
|
||||
FileInputStream(source).use { input -> FileOutputStream(target).use { out -> input.copyTo(out, 128 * 1024) } }
|
||||
}
|
||||
|
||||
private fun unzip(archive: File, handle: DownloadQueue.JobHandle) {
|
||||
val total = archive.length()
|
||||
var written = 0L
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
ZipFile.builder().setFile(archive).get().use { zip ->
|
||||
for (entry in zip.entries) {
|
||||
if (cancelled.get()) return
|
||||
val target = target(entry.name)
|
||||
if (target == null) {
|
||||
handle.log("itch.io: skipped an entry outside the game folder")
|
||||
continue
|
||||
}
|
||||
if (entry.isDirectory) {
|
||||
target.mkdirs()
|
||||
continue
|
||||
}
|
||||
target.parentFile?.mkdirs()
|
||||
zip.getInputStream(entry).use { input ->
|
||||
FileOutputStream(target).use { out ->
|
||||
while (true) {
|
||||
if (cancelled.get()) return
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
written += read
|
||||
handle.stageProgress(written, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private companion object
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Close
|
||||
import androidx.compose.material.icons.outlined.Menu
|
||||
import androidx.compose.material.icons.outlined.SwapVert
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
@@ -84,10 +85,11 @@ fun BottomDashboard(
|
||||
pages: List<BottomPage>,
|
||||
remembered: String?,
|
||||
onPage: (String) -> Unit,
|
||||
onClose: () -> Unit,
|
||||
onClose: (() -> Unit)?,
|
||||
onMenu: (() -> Unit)?,
|
||||
gameStarts: Int = 0,
|
||||
strip: (@Composable (String?) -> Unit)? = null,
|
||||
onSwap: (() -> Unit)? = null,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
var current by remember { mutableStateOf(pickBottomPage(remembered, pages.map { it.id })) }
|
||||
@@ -100,7 +102,7 @@ fun BottomDashboard(
|
||||
val labels = bottomTabsWithLabels(maxWidth.value, pages.size)
|
||||
Column(Modifier.fillMaxSize().padding(horizontal = 12.dp, vertical = 10.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Row(Modifier.fillMaxWidth().height(48.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
BarButton(Icons.Outlined.Close, stringResource(R.string.deck_close), "bottom-close", onClose)
|
||||
if (onClose != null) BarButton(Icons.Outlined.Close, stringResource(R.string.deck_close), "bottom-close", onClose)
|
||||
Row(Modifier.weight(1f).horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
pages.forEach { p ->
|
||||
PageTab(p, p.id == page?.id, labels) {
|
||||
@@ -109,6 +111,7 @@ fun BottomDashboard(
|
||||
}
|
||||
}
|
||||
}
|
||||
if (onSwap != null) BarButton(Icons.Outlined.SwapVert, stringResource(R.string.swap_screens), "bottom-swap", onSwap)
|
||||
if (onMenu != null) BarButton(Icons.Outlined.Menu, stringResource(R.string.touch_droiddeck_menu), "bottom-menu", onMenu)
|
||||
}
|
||||
strip?.invoke(page?.id)
|
||||
|
||||
@@ -4,6 +4,7 @@ import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.graphics.Color
|
||||
import android.os.Build
|
||||
import android.os.SystemClock
|
||||
import android.graphics.Typeface
|
||||
import android.view.Gravity
|
||||
@@ -13,6 +14,7 @@ import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
import android.view.View
|
||||
import android.view.ViewConfiguration
|
||||
import android.view.WindowInsets
|
||||
import android.graphics.RectF
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
@@ -33,9 +35,11 @@ import com.droiddeck.launcher.session.BottomDesktop
|
||||
@SuppressLint("ViewConstructor")
|
||||
class BottomDesktopPanel(
|
||||
context: Context,
|
||||
onClose: () -> Unit,
|
||||
onClose: (() -> Unit)?,
|
||||
onMenu: (() -> Unit)?,
|
||||
steamButtons: Pair<() -> Unit, () -> Unit>?,
|
||||
onSwap: (() -> Unit)? = null,
|
||||
private val fullResolution: Boolean = false,
|
||||
) : LinearLayout(context), SurfaceHolder.Callback {
|
||||
private lateinit var surfaceView: SurfaceView
|
||||
private val area = FrameLayout(context).apply { clipChildren = true }
|
||||
@@ -66,7 +70,7 @@ class BottomDesktopPanel(
|
||||
setBackgroundColor(Color.BLACK)
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
addView(bar(onClose, onMenu, steamButtons), LayoutParams(-1, -2))
|
||||
addView(bar(onClose, onMenu, steamButtons, onSwap), LayoutParams(-1, -2))
|
||||
area.addView(keyboardHost)
|
||||
addSurface()
|
||||
area.addView(status, FrameLayout.LayoutParams(-1, -1))
|
||||
@@ -83,7 +87,7 @@ class BottomDesktopPanel(
|
||||
area.addView(surfaceView, 1, FrameLayout.LayoutParams(fullWidth.takeIf { it > 0 } ?: -1, fullHeight.takeIf { it > 0 } ?: -1))
|
||||
}
|
||||
|
||||
private fun bar(onClose: () -> Unit, onMenu: (() -> Unit)?, steamButtons: Pair<() -> Unit, () -> Unit>?): View {
|
||||
private fun bar(onClose: (() -> Unit)?, onMenu: (() -> Unit)?, steamButtons: Pair<() -> Unit, () -> Unit>?, onSwap: (() -> Unit)?): View {
|
||||
val bar = LinearLayout(context).apply {
|
||||
orientation = HORIZONTAL
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
@@ -91,7 +95,7 @@ class BottomDesktopPanel(
|
||||
setBackgroundColor(Color.BLACK)
|
||||
}
|
||||
fun gap() = View(context).apply { layoutParams = LayoutParams(dp(6), 1) }
|
||||
bar.addView(DeckControlsPanel.roundButton(context, "×", context.getString(R.string.deck_close), onClose))
|
||||
onClose?.let { bar.addView(DeckControlsPanel.roundButton(context, "×", context.getString(R.string.deck_close), it)) }
|
||||
title = TextView(context).apply {
|
||||
textSize = 14f
|
||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
||||
@@ -106,6 +110,10 @@ class BottomDesktopPanel(
|
||||
bar.addView(gap())
|
||||
bar.addView(DeckControlsPanel.iconButton(context, R.drawable.ic_bottom_keyboard,
|
||||
context.getString(R.string.second_show_keyboard)) { keyboardHost.toggle() })
|
||||
onSwap?.let {
|
||||
bar.addView(gap())
|
||||
bar.addView(DeckControlsPanel.iconButton(context, R.drawable.ic_bottom_swap, context.getString(R.string.swap_screens), it))
|
||||
}
|
||||
onMenu?.let {
|
||||
bar.addView(gap())
|
||||
bar.addView(DeckControlsPanel.menuButton(context, it))
|
||||
@@ -187,7 +195,9 @@ class BottomDesktopPanel(
|
||||
addSurface()
|
||||
return
|
||||
}
|
||||
if (attached) attach(surfaceView.holder)
|
||||
if (!attached) return
|
||||
attached = false
|
||||
syncSurface(surfaceView.holder)
|
||||
}
|
||||
|
||||
private fun showState() {
|
||||
@@ -208,13 +218,28 @@ class BottomDesktopPanel(
|
||||
if (w != fullWidth || h > fullHeight || !keyboardHost.shown) {
|
||||
fullWidth = w
|
||||
fullHeight = h
|
||||
surfaceView.layoutParams = FrameLayout.LayoutParams(w, h)
|
||||
val (desktopW, desktopH) = BottomDesktop.outputSizeFor(w, h, fullResolution)
|
||||
val (fitW, fitH) = if (w - desktopW in 0..1 && h - desktopH in 0..1) desktopW to desktopH
|
||||
else fitDesktop(w, h, desktopW, desktopH)
|
||||
surfaceView.layoutParams = if (fitW == w && fitH == h) FrameLayout.LayoutParams(w, h)
|
||||
else FrameLayout.LayoutParams(fitW, fitH, Gravity.CENTER_HORIZONTAL).apply { topMargin = (h - fitH) / 2 }
|
||||
surfaceView.post { syncSurface(surfaceView.holder) }
|
||||
}
|
||||
pan()
|
||||
}
|
||||
|
||||
private fun imeOverlap(): Int {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return 0
|
||||
if (area.height < fullHeight) return 0
|
||||
val ime = rootWindowInsets?.getInsets(WindowInsets.Type.ime())?.bottom ?: return 0
|
||||
if (ime <= 0) return 0
|
||||
val at = IntArray(2)
|
||||
area.getLocationInWindow(at)
|
||||
return (at[1] + area.height - (rootView.height - ime)).coerceIn(0, area.height)
|
||||
}
|
||||
|
||||
private fun pan() {
|
||||
val visible = area.height
|
||||
val visible = area.height - imeOverlap()
|
||||
val hidden = (fullHeight - visible).coerceAtLeast(0)
|
||||
val anchor = if (directTouch) lastTouchY else trackpad.y
|
||||
surfaceView.translationY = if (hidden == 0 || !keyboardHost.shown) 0f
|
||||
@@ -223,24 +248,27 @@ class BottomDesktopPanel(
|
||||
|
||||
override fun surfaceCreated(holder: SurfaceHolder) = Unit
|
||||
|
||||
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
|
||||
if (!attached) attach(holder)
|
||||
}
|
||||
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = syncSurface(holder)
|
||||
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
||||
if (holder !== surfaceView.holder) return
|
||||
attached = false
|
||||
surfaceUsed = false
|
||||
BottomDesktop.detach()
|
||||
BottomDesktop.detach(holder.surface)
|
||||
}
|
||||
|
||||
private fun attach(holder: SurfaceHolder) {
|
||||
val frame = holder.surfaceFrame
|
||||
val (width, height) = BottomDesktop.outputSizeFor(fullWidth.takeIf { it > 0 } ?: frame.width(),
|
||||
fullHeight.takeIf { it > 0 } ?: frame.height())
|
||||
private fun syncSurface(holder: SurfaceHolder) {
|
||||
if (holder !== surfaceView.holder || fullWidth <= 0 || fullHeight <= 0 || !holder.surface.isValid) return
|
||||
val (width, height) = BottomDesktop.outputSizeFor(fullWidth, fullHeight, fullResolution)
|
||||
if (width <= 0 || height <= 0) return
|
||||
val frame = holder.surfaceFrame
|
||||
if (frame.width() != width || frame.height() != height) {
|
||||
holder.setFixedSize(width, height)
|
||||
val params = surfaceView.layoutParams
|
||||
if (params.width == width && params.height == height) holder.setSizeFromLayout() else holder.setFixedSize(width, height)
|
||||
return
|
||||
}
|
||||
if (attached) {
|
||||
BottomDesktop.resize(holder.surface, width, height)
|
||||
return
|
||||
}
|
||||
attached = true
|
||||
@@ -299,7 +327,7 @@ class BottomDesktopPanel(
|
||||
override fun onWheel(steps: Int) = BottomDesktop.sendScene(SCENE_WHEEL, steps)
|
||||
|
||||
override fun onScroll(dx: Float, dy: Float) {
|
||||
val (outW, outH) = BottomDesktop.outputSizeFor(surfaceView.width, surfaceView.height)
|
||||
val (outW, outH) = BottomDesktop.outputSize
|
||||
scrollRestX += dx * outW / surfaceView.width.coerceAtLeast(1) * AXIS_UNITS_PER_PIXEL
|
||||
scrollRestY += dy * outH / surfaceView.height.coerceAtLeast(1) * AXIS_UNITS_PER_PIXEL
|
||||
val h = scrollRestX.toInt()
|
||||
@@ -343,3 +371,11 @@ class BottomDesktopPanel(
|
||||
const val TEXT_FIELD_TAP_MS = 1_000L
|
||||
}
|
||||
}
|
||||
|
||||
internal fun fitDesktop(areaW: Int, areaH: Int, desktopW: Int, desktopH: Int): Pair<Int, Int> {
|
||||
if (areaW <= 0 || areaH <= 0 || desktopW <= 0 || desktopH <= 0) return areaW to areaH
|
||||
val widthLimited = areaW.toLong() * desktopH <= areaH.toLong() * desktopW
|
||||
val w = if (widthLimited) areaW else (desktopW.toLong() * areaH / desktopH).toInt()
|
||||
val h = if (widthLimited) (desktopH.toLong() * areaW / desktopW).toInt() else areaH
|
||||
return if (areaW - w <= 4 && areaH - h <= 4) areaW to areaH else w to h
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Presentation
|
||||
import android.graphics.Color
|
||||
import android.os.Bundle
|
||||
import android.view.Display
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.WindowManager
|
||||
import android.widget.FrameLayout
|
||||
|
||||
class BottomGameScreen(
|
||||
private val activity: Activity,
|
||||
display: Display,
|
||||
private val callback: SurfaceHolder.Callback,
|
||||
private val onTouch: (MotionEvent) -> Boolean,
|
||||
) : Presentation(activity, display) {
|
||||
val surfaceView = SurfaceView(getContext())
|
||||
val holder: SurfaceHolder get() = surfaceView.holder
|
||||
|
||||
val hz: Float get() = display.mode.refreshRate
|
||||
|
||||
init {
|
||||
setCancelable(false)
|
||||
setCanceledOnTouchOutside(false)
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val root = FrameLayout(context).apply { setBackgroundColor(Color.BLACK) }
|
||||
root.addView(surfaceView, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
|
||||
setContentView(root)
|
||||
window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
|
||||
@Suppress("DEPRECATION")
|
||||
window?.decorView?.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
|
||||
or View.SYSTEM_UI_FLAG_FULLSCREEN
|
||||
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
|
||||
surfaceView.setOnTouchListener { _, event -> onTouch(event) }
|
||||
surfaceView.holder.addCallback(callback)
|
||||
}
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean =
|
||||
activity.dispatchKeyEvent(event) || super.dispatchKeyEvent(event)
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean =
|
||||
activity.dispatchGenericMotionEvent(event) || super.dispatchGenericMotionEvent(event)
|
||||
}
|
||||
|
||||
object GameScreenSwap {
|
||||
fun wanted(
|
||||
requested: Boolean,
|
||||
activityStarted: Boolean,
|
||||
sessionEnded: Boolean,
|
||||
inPip: Boolean,
|
||||
glassesOutput: Boolean,
|
||||
bottomScreenFree: Boolean,
|
||||
): Boolean = requested && activityStarted && !sessionEnded && !inPip && !glassesOutput && bottomScreenFree
|
||||
}
|
||||
@@ -27,7 +27,7 @@ import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
|
||||
private const val STRIP_FRAME_MS = 100L
|
||||
private const val STRIP_FRAME_MS = 33L
|
||||
private const val STRIP_METRICS_MS = 500L
|
||||
private const val STRIP_TEMP_PLAIN = 0xFFF2F5F9.toInt()
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ private const val ELITE_MS = 1_000L
|
||||
private const val ELITE_SEARCH_MS = 10_000L
|
||||
private const val OUTPUT_SCAN_MS = 3_000L
|
||||
private const val PERF_N = 60
|
||||
private const val FRAME_MS = 100L
|
||||
private const val FRAME_MS = 33L
|
||||
private const val MINUTE_NS = 60_000_000_000L
|
||||
private const val TEMP_PLAIN = 0xFFF2F5F9.toInt()
|
||||
|
||||
@@ -132,7 +132,7 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }
|
||||
var unknown by remember { mutableStateOf<List<UnknownTraffic>>(emptyList()) }
|
||||
var strip by remember { mutableStateOf(StatsStrip.from(SessionPrefs.statsStrip(context))) }
|
||||
var dash by remember { mutableStateOf(StatsDash.from(SessionPrefs.statsDash(context))) }
|
||||
var speedUnit by remember { mutableStateOf(SpeedUnit.from(SessionPrefs.statsSpeedUnit(context))) }
|
||||
val speedUnit = SpeedUnit.from(SessionPrefs.statsSpeedUnit(context))
|
||||
val shownUnit = speedUnit.resolve(Resources.getSystem().configuration.locales[0].country)
|
||||
val fpsHistory = remember { History(PERF_N) }
|
||||
val cpuHistory = remember { History(PERF_N) }
|
||||
@@ -374,10 +374,6 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }
|
||||
))
|
||||
}
|
||||
}
|
||||
if (race == null && thunder.isEmpty() && elite == null && running == null) {
|
||||
Text(stringResource(R.string.bottom_telemetry_help),
|
||||
fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp))
|
||||
}
|
||||
if (outputs.isNotEmpty() || menuGames.isNotEmpty()) TelemetryCard(stringResource(R.string.bottom_telemetry_send_title)) {
|
||||
if (outputs.isNotEmpty()) SwitchRow(stringResource(R.string.bottom_telemetry_send_auto), stringResource(R.string.bottom_telemetry_send_auto_hint), auto, true) { want ->
|
||||
scope.launch {
|
||||
@@ -420,12 +416,6 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }
|
||||
Text(stringResource(R.string.bottom_telemetry_port_busy, busyPorts.sorted().joinToString()), fontSize = 13.sp,
|
||||
color = colors.error, modifier = Modifier.padding(horizontal = 4.dp))
|
||||
}
|
||||
ChoiceRow(stringResource(R.string.stats_speed_units),
|
||||
if (speedUnit == SpeedUnit.AUTO) stringResource(R.string.stats_speed_units_auto, shownUnit.label) else speedUnit.label) {
|
||||
speedUnit = speedUnit.next()
|
||||
SessionPrefs.setStatsSpeedUnit(context, speedUnit.id)
|
||||
}
|
||||
Text(stringResource(R.string.stats_tap_hint), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -465,19 +455,8 @@ private fun httpGet(url: String): String {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
internal fun steamClientLabel(arch: String): Int = if (arch == "x86_64") R.string.stats_steam_client_x86 else R.string.stats_steam_client_arm
|
||||
|
||||
@Composable
|
||||
private fun ChoiceRow(title: String, value: String, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Row(Modifier.fillMaxWidth().clickable(role = Role.Button, onClick = onClick).padding(horizontal = 4.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(title, fontSize = 15.sp, color = colors.onBackground, modifier = Modifier.weight(1f))
|
||||
Text(value, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = LocalPalette.current.primary)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SwitchRow(title: String, hint: String?, checked: Boolean, enabled: Boolean, onChange: (Boolean) -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
|
||||
@@ -110,13 +110,13 @@ private fun BottomStripSettings(host: MenuHost, track: (String) -> Modifier) {
|
||||
var hudOn by remember { mutableStateOf(SessionPrefs.bottomHud(context)) }
|
||||
var onTabs by remember { mutableStateOf(SessionPrefs.bottomStripOnTabs(context)) }
|
||||
var shown by remember { mutableStateOf(SessionPrefs.bottomStripMetrics(context)) }
|
||||
SettingsGroup(stringResource(R.string.bottom_hud_group), detail = stringResource(R.string.bottom_hud_group_detail)) {
|
||||
ToggleRow(host, "bottom-hud", stringResource(R.string.bottom_hud_group), stringResource(R.string.bottom_hud_hint), hudOn,
|
||||
SettingsGroup(stringResource(R.string.bottom_hud_group)) {
|
||||
ToggleRow(host, "bottom-hud", stringResource(R.string.bottom_hud_group), null, hudOn,
|
||||
chipModifier = track("bottom-hud")) { on ->
|
||||
hudOn = on
|
||||
SessionPrefs.setBottomHud(context, on)
|
||||
}
|
||||
ToggleRow(host, "bottom-strip-tabs", stringResource(R.string.bottom_strip_tabs), stringResource(R.string.bottom_strip_tabs_hint), onTabs,
|
||||
ToggleRow(host, "bottom-strip-tabs", stringResource(R.string.bottom_strip_tabs), null, onTabs,
|
||||
enabled = hudOn, chipModifier = track("bottom-strip-tabs")) { on ->
|
||||
onTabs = on
|
||||
SessionPrefs.setBottomStripOnTabs(context, on)
|
||||
|
||||
@@ -133,7 +133,7 @@ class FrontEndState(
|
||||
val dualScreen: Boolean = false,
|
||||
val dualScreenDevice: Boolean = false,
|
||||
val dualScreenMode: String = com.droiddeck.launcher.input.DualScreen.MODE_AUTO,
|
||||
val dualScreenLauncher: Boolean = true,
|
||||
val dualScreenSessions: String = com.droiddeck.launcher.input.DualScreen.MODE_AUTO,
|
||||
val dualScreenControls: Boolean = true,
|
||||
val packages: List<PackageRow>? = null,
|
||||
val packageCatalogLoading: Boolean = false,
|
||||
@@ -245,7 +245,7 @@ class FrontEndActions(
|
||||
val onLauncherFullscreen: (Boolean) -> Unit = {},
|
||||
val onAnimationsEnabled: (Boolean) -> Unit = {},
|
||||
val onDualScreenMode: (String) -> Unit = {},
|
||||
val onDualScreenLauncher: (Boolean) -> Unit = {},
|
||||
val onDualScreenSessions: (String) -> Unit = {},
|
||||
val onDualScreenControls: (Boolean) -> Unit = {},
|
||||
val onDownloadSource: (String) -> Unit = {},
|
||||
val onDownloadMirror: (String) -> Unit = {},
|
||||
@@ -708,6 +708,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
StoreTheme(com.droiddeck.launcher.stores.Store.XBOX) { XboxStoreDialogs() }
|
||||
com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } }
|
||||
com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } }
|
||||
com.droiddeck.launcher.stores.StoresState.gameJoltPicking?.let { item -> StoreTheme(item.store) { GameJoltBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.gameJoltPicking = null } } }
|
||||
StepsLayer(screenAt)
|
||||
|
||||
appToChooseDisplay?.let { app ->
|
||||
|
||||
@@ -467,21 +467,23 @@ internal fun SetupPanel(
|
||||
s.launcherFullscreen,
|
||||
) { a.onLauncherFullscreen(it) }
|
||||
if (s.dualScreenDevice) {
|
||||
ChoiceRow(
|
||||
host, "dual-screen", stringResource(R.string.setup_dual_screen), stringResource(R.string.setup_dual_screen_hint),
|
||||
listOf(
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_AUTO to stringResource(R.string.setup_dual_screen_auto),
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_ON to stringResource(R.string.setup_dual_screen_on),
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_OFF to stringResource(R.string.setup_dual_screen_off),
|
||||
),
|
||||
s.dualScreenMode, onPick = a.onDualScreenMode,
|
||||
val dualModes = listOf(
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_AUTO to stringResource(R.string.setup_dual_screen_auto),
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_ON to stringResource(R.string.setup_dual_screen_on),
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_OFF to stringResource(R.string.setup_dual_screen_off),
|
||||
)
|
||||
}
|
||||
if (s.dualScreenDevice && s.dualScreenMode != com.droiddeck.launcher.input.DualScreen.MODE_OFF) {
|
||||
ToggleRow(host, "dual-screen-menu", stringResource(R.string.setup_dual_screen_menu),
|
||||
stringResource(R.string.setup_dual_screen_menu_hint), s.dualScreenLauncher) { a.onDualScreenLauncher(it) }
|
||||
ToggleRow(host, "dual-screen-controls", stringResource(R.string.setup_dual_screen_controls),
|
||||
stringResource(R.string.setup_dual_screen_controls_hint), s.dualScreenControls) { a.onDualScreenControls(it) }
|
||||
ChoiceRow(
|
||||
host, "dual-screen", stringResource(R.string.setup_dual_screen_launcher), stringResource(R.string.setup_dual_screen_launcher_hint),
|
||||
dualModes, s.dualScreenMode, onPick = a.onDualScreenMode,
|
||||
)
|
||||
ChoiceRow(
|
||||
host, "dual-screen-sessions", stringResource(R.string.setup_dual_screen_sessions), stringResource(R.string.setup_dual_screen_sessions_hint),
|
||||
dualModes, s.dualScreenSessions, onPick = a.onDualScreenSessions,
|
||||
)
|
||||
if (s.dualScreenSessions != com.droiddeck.launcher.input.DualScreen.MODE_OFF) {
|
||||
ToggleRow(host, "dual-screen-controls", stringResource(R.string.setup_dual_screen_controls),
|
||||
stringResource(R.string.setup_dual_screen_controls_hint), s.dualScreenControls) { a.onDualScreenControls(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,6 +98,7 @@ import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreLanguage
|
||||
import com.droiddeck.launcher.stores.StoreSizes
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltApi
|
||||
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadState
|
||||
@@ -139,7 +140,7 @@ internal enum class GameTab { ABOUT, ACHIEVEMENTS, LAUNCH, SAVES, INSTALL }
|
||||
|
||||
@Composable
|
||||
internal fun GameDetail(
|
||||
key: String, s: FrontEndState, a: FrontEndActions, lead: FocusRequester, backLabel: String, hopRail: String?, onBack: () -> Unit,
|
||||
key: String, s: FrontEndState, a: FrontEndActions, lead: FocusRequester, backLabel: String, hopRail: String?, onBack: () -> Unit, inStore: Boolean = false,
|
||||
) {
|
||||
val narrow = LocalNarrowPane.current
|
||||
val stacked = narrow || LocalConfiguration.current.screenWidthDp < 700
|
||||
@@ -218,6 +219,7 @@ internal fun GameDetail(
|
||||
if (!s.shortcutPicker) CompositionLocalProvider(LocalPillButtons provides true) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (installed != null && installed.sidecar.store == Store.ITCH) ItchCheckButton(installed)
|
||||
if (installed != null && installed.sidecar.store == Store.GAMEJOLT) GameJoltCheckButton(installed)
|
||||
RemoveButton(title, game, installed, a)
|
||||
}
|
||||
}
|
||||
@@ -232,7 +234,7 @@ internal fun GameDetail(
|
||||
color = MaterialTheme.colorScheme.error, maxLines = 3, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
GameCapsule(scores) { GameActions(store, id, game, item, installed, s, a, Modifier.focusRequester(lead), compactMenu = stacked) }
|
||||
GameCapsule(scores) { GameActions(store, id, game, item, installed, s, a, Modifier.focusRequester(lead), compactMenu = stacked, inStore = inStore) }
|
||||
}
|
||||
}
|
||||
if (StoresMotion.heroLands) header() else Rise(1) { header() }
|
||||
@@ -382,7 +384,7 @@ private fun GameTitle(title: String, logo: Any?, titleSize: TextUnit) {
|
||||
@Composable
|
||||
internal fun GameActions(
|
||||
store: Store?, id: String?, game: Library.SteamGame?, item: CatalogItem?, installed: InstalledStoreGame?,
|
||||
s: FrontEndState, a: FrontEndActions, leadOn: Modifier, compactMenu: Boolean = false,
|
||||
s: FrontEndState, a: FrontEndActions, leadOn: Modifier, compactMenu: Boolean = false, inStore: Boolean = false,
|
||||
) {
|
||||
val ctx = LocalContext.current
|
||||
val storeKey = if (store != null && id != null) "${store.id}:$id" else null
|
||||
@@ -409,10 +411,16 @@ internal fun GameActions(
|
||||
if (compactMenu) GameMoreMenu(game, a) else {
|
||||
FileButtons(game, a)
|
||||
GameShortcutMenu(game, a)
|
||||
EditArtButton(game)
|
||||
}
|
||||
}
|
||||
if (store == Store.ITCH && installed != null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (store == Store.GAMEJOLT && installed != null) GameJoltUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (store == Store.GAMEJOLT && installed != null) GameJoltVersionButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (inStore && store == Store.GAMEJOLT && installed != null) {
|
||||
SecondaryButton(stringResource(R.string.stores_view_on, Store.GAMEJOLT.shortLabel)) {
|
||||
openUrl(ctx, item?.storeUrl.orEmpty().ifBlank { GameJoltApi.pageUrl("game", installed.sidecar.id) })
|
||||
}
|
||||
}
|
||||
if (store == Store.GOG && installed != null) GogMaintenanceActions(installed)
|
||||
if (store == Store.XBOX && id != null) XboxInstalledStream(id, game?.name ?: item?.title.orEmpty(), item)
|
||||
if (store == Store.XBOX && installed != null && id != null) {
|
||||
@@ -435,6 +443,7 @@ internal fun GameActions(
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
|
||||
}
|
||||
if (game != null && !compactMenu) EditArtButton(game)
|
||||
}
|
||||
download != null -> {
|
||||
ActionChip(downloadLabel(download), ok = false)
|
||||
@@ -482,7 +491,7 @@ internal fun GameActions(
|
||||
}
|
||||
if (!item.accessible) SecondaryButton(buyLabel(item)) { openStoreUrl(ctx, item) }
|
||||
}
|
||||
item != null && item.store == Store.ITCH && item.isFree -> {
|
||||
item != null && (item.store == Store.ITCH || item.store == Store.GAMEJOLT) && item.isFree -> {
|
||||
InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
|
||||
SecondaryButton(stringResource(R.string.stores_view_on, item.store.shortLabel)) { openStoreUrl(ctx, item) }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltBrowse
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltBrowseState
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltQuery
|
||||
|
||||
@Composable
|
||||
internal fun GameJoltBrowseBar(showMature: Boolean) {
|
||||
val ctx = LocalContext.current
|
||||
val query = GameJoltBrowseState.query
|
||||
var picking by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(Unit) { if (GameJoltBrowseState.items.isEmpty()) GameJoltBrowseState.more(ctx) }
|
||||
fun toggle(set: Set<String>, value: String): Set<String> = if (value in set) set - value else set + value
|
||||
Column(Modifier.fillMaxWidth().padding(top = 6.dp, bottom = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
ChipRow {
|
||||
BrowseDropdown(sectionLabel(query.section)) { first, close ->
|
||||
GameJoltBrowse.sections.forEachIndexed { index, section ->
|
||||
MenuItem(sectionLabel(section), query.section == section, focusRequester = if (index == 0) first else null) {
|
||||
GameJoltBrowseState.choose(ctx, query.copy(section = section))
|
||||
close()
|
||||
}
|
||||
}
|
||||
}
|
||||
BrowseDropdown(priceLabel(query.price)) { first, close ->
|
||||
GameJoltBrowse.prices.forEachIndexed { index, price ->
|
||||
MenuItem(priceLabel(price), query.price == price, focusRequester = if (index == 0) first else null) {
|
||||
GameJoltBrowseState.choose(ctx, query.copy(price = price))
|
||||
close()
|
||||
}
|
||||
}
|
||||
}
|
||||
val anyPlatform = stringResource(R.string.stores_itch_platform_any)
|
||||
BrowseDropdown(browseSummary(GameJoltBrowse.systems.filter { it in query.os }.map { systemLabel(it) }, anyPlatform)) { first, _ ->
|
||||
MenuItem(anyPlatform, query.os.isEmpty(), focusRequester = first) { GameJoltBrowseState.choose(ctx, query.copy(os = emptySet())) }
|
||||
for (os in GameJoltBrowse.systems) MenuItem(systemLabel(os), os in query.os) { GameJoltBrowseState.choose(ctx, query.copy(os = toggle(query.os, os))) }
|
||||
}
|
||||
BrowseDropdown(browseSummary(GameJoltBrowse.browsers.filter { it in query.browser }.map { browserLabel(it) }, stringResource(R.string.stores_gamejolt_filter_browser))) { first, _ ->
|
||||
GameJoltBrowse.browsers.forEachIndexed { index, browser ->
|
||||
MenuItem(browserLabel(browser), browser in query.browser, focusRequester = if (index == 0) first else null) { GameJoltBrowseState.choose(ctx, query.copy(browser = toggle(query.browser, browser))) }
|
||||
}
|
||||
}
|
||||
val maturities = GameJoltBrowse.maturities.filter { showMature || it != "adult" }
|
||||
BrowseDropdown(browseSummary(maturities.filter { it in query.maturity }.map { maturityLabel(it) }, stringResource(R.string.stores_gamejolt_filter_maturity))) { first, _ ->
|
||||
maturities.forEachIndexed { index, maturity ->
|
||||
MenuItem(maturityLabel(maturity), maturity in query.maturity, focusRequester = if (index == 0) first else null) { GameJoltBrowseState.choose(ctx, query.copy(maturity = toggle(query.maturity, maturity))) }
|
||||
}
|
||||
}
|
||||
BrowseDropdown(browseSummary(GameJoltBrowse.statuses.filter { it in query.status }.map { statusLabel(it) }, stringResource(R.string.stores_gamejolt_filter_status))) { first, _ ->
|
||||
GameJoltBrowse.statuses.forEachIndexed { index, status ->
|
||||
MenuItem(statusLabel(status), status in query.status, focusRequester = if (index == 0) first else null) { GameJoltBrowseState.choose(ctx, query.copy(status = toggle(query.status, status))) }
|
||||
}
|
||||
}
|
||||
val partners = stringResource(R.string.stores_gamejolt_partners)
|
||||
BrowseDropdown(if (query.partners) partners else stringResource(R.string.stores_gamejolt_filter_partners)) { first, _ ->
|
||||
MenuItem(partners, query.partners, focusRequester = first) { GameJoltBrowseState.choose(ctx, query.copy(partners = !query.partners)) }
|
||||
}
|
||||
}
|
||||
ChipRow {
|
||||
for (tag in query.tags) BrowseChip("$tag ✕", true) { GameJoltBrowseState.choose(ctx, query.copy(tags = query.tags - tag)) }
|
||||
BrowseChip(stringResource(R.string.stores_itch_tag_add), false) { picking = true }
|
||||
}
|
||||
}
|
||||
if (picking) TextEntryDialog(
|
||||
stringResource(R.string.stores_itch_tag_title), "", number = false, confirm = stringResource(R.string.common_ok),
|
||||
onSubmit = { value -> GameJoltBrowse.tagSlug(value).takeIf { it.isNotEmpty() }?.let { GameJoltBrowseState.choose(ctx, query.copy(tags = (query.tags + it).distinct())) } },
|
||||
onDismiss = { picking = false }, id = "gamejolt-tag",
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun GameJoltLoadMore() {
|
||||
val ctx = LocalContext.current
|
||||
val count = GameJoltBrowseState.items.size
|
||||
LaunchedEffect(Unit) { GameJoltBrowseState.more(ctx) }
|
||||
if (GameJoltBrowseState.loading) LinearProgressIndicator(Modifier.fillMaxWidth().padding(vertical = 12.dp))
|
||||
else if (GameJoltBrowseState.failed) Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {
|
||||
BrowseChip(stringResource(R.string.stores_dl_retry), false) { GameJoltBrowseState.more(ctx, retry = true) }
|
||||
}
|
||||
else if (!GameJoltBrowseState.ended && count > 0) Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {
|
||||
BrowseChip(stringResource(R.string.stores_itch_load_more), false) { GameJoltBrowseState.more(ctx) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun sectionLabel(section: String): String = stringResource(
|
||||
when (section) {
|
||||
GameJoltBrowse.SECTION_HOT -> R.string.stores_gamejolt_section_hot
|
||||
GameJoltBrowse.SECTION_BEST -> R.string.stores_gamejolt_section_best
|
||||
GameJoltBrowse.SECTION_NEW -> R.string.stores_gamejolt_section_new
|
||||
else -> R.string.stores_gamejolt_section_featured
|
||||
},
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun priceLabel(price: String): String = stringResource(
|
||||
when (price) {
|
||||
GameJoltBrowse.PRICE_FREE -> R.string.stores_itch_price_free
|
||||
GameJoltBrowse.PRICE_SALE -> R.string.stores_itch_price_sale
|
||||
GameJoltBrowse.PRICE_PAID -> R.string.stores_itch_price_paid
|
||||
GameJoltBrowse.PRICE_UNDER_5 -> R.string.stores_itch_price_under_5
|
||||
GameJoltBrowse.PRICE_UNDER_15 -> R.string.stores_itch_price_under_15
|
||||
GameJoltBrowse.PRICE_UNDER_30 -> R.string.stores_gamejolt_price_under_30
|
||||
else -> R.string.stores_itch_price_any
|
||||
},
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun systemLabel(os: String): String = stringResource(
|
||||
when (os) {
|
||||
"windows" -> R.string.stores_itch_platform_windows
|
||||
"mac" -> R.string.stores_itch_platform_macos
|
||||
"linux" -> R.string.stores_itch_platform_linux
|
||||
else -> R.string.stores_gamejolt_os_other
|
||||
},
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun browserLabel(browser: String): String = when (browser) {
|
||||
"html" -> "HTML"
|
||||
"flash" -> "Flash"
|
||||
else -> "Unity"
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun maturityLabel(maturity: String): String = stringResource(
|
||||
when (maturity) {
|
||||
"everyone" -> R.string.stores_gamejolt_maturity_everyone
|
||||
"teen" -> R.string.stores_gamejolt_maturity_teen
|
||||
else -> R.string.stores_gamejolt_maturity_adult
|
||||
},
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun statusLabel(status: String): String = stringResource(
|
||||
when (status) {
|
||||
"complete" -> R.string.stores_gamejolt_status_complete
|
||||
else -> R.string.stores_gamejolt_status_early
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltApi
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltBuild
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltBuilds
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
private const val CHOOSE = "choose"
|
||||
|
||||
@Composable
|
||||
internal fun GameJoltVersionButton(installed: InstalledStoreGame, enabled: Boolean) {
|
||||
SecondaryButton(stringResource(R.string.stores_itch_pick_title), enabled = enabled) {
|
||||
val sidecar = installed.sidecar
|
||||
val paid = sidecar.extra["paid"] == "1"
|
||||
StoresState.gameJoltPicking = CatalogItem(
|
||||
store = Store.GAMEJOLT, id = sidecar.id, title = sidecar.title, imageUrl = sidecar.cover, isFree = !paid,
|
||||
storeUrl = GameJoltApi.pageUrl("game", sidecar.id),
|
||||
extra = mapOf("gameId" to (sidecar.extra["gameId"] ?: sidecar.id), CHOOSE to "1"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun GameJoltBuildPicker(requested: CatalogItem, onDismiss: () -> Unit) {
|
||||
val item = requested.copy(owned = requested.owned || StoresState.library[Store.GAMEJOLT].orEmpty().any { it.id == requested.id && it.owned })
|
||||
val ctx = LocalContext.current
|
||||
val app = ctx.applicationContext
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
var loaded by remember(requested) { mutableStateOf<List<GameJoltBuild>?>(null) }
|
||||
var failed by remember(requested) { mutableStateOf(false) }
|
||||
|
||||
val install: (GameJoltBuild) -> Unit = install@{ build ->
|
||||
if (!shown.targetState) return@install
|
||||
val tagged = item.copy(
|
||||
extra = item.extra + mapOf("buildId" to build.id),
|
||||
sizeBytes = build.size.takeIf { it > 0 } ?: item.sizeBytes,
|
||||
)
|
||||
close()
|
||||
StoresState.requestInstall(ctx, tagged)
|
||||
}
|
||||
|
||||
LaunchedEffect(requested) {
|
||||
val gameId = item.extra["gameId"].orEmpty().ifEmpty { item.id }
|
||||
val result = withContext(Dispatchers.IO) { GameJoltBuilds.load(app, gameId) }
|
||||
if (result == null) { failed = true; return@LaunchedEffect }
|
||||
loaded = result
|
||||
if ((item.isFree || item.owned) && item.extra[CHOOSE] != "1" && shown.targetState) result.singleOrNull()?.takeIf { it.installable }?.let { install(it) }
|
||||
}
|
||||
|
||||
AppDialog(shown, close, "gameJoltBuilds", wide = false, maxWidth = 460.dp) {
|
||||
DialogTitleRow(stringResource(R.string.stores_itch_pick_title), close)
|
||||
Text(item.title, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
val list = loaded
|
||||
when {
|
||||
failed -> Text(stringResource(R.string.stores_gamejolt_pick_failed), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
list == null -> LinearProgressIndicator(Modifier.fillMaxWidth().padding(vertical = 8.dp))
|
||||
list.isEmpty() -> Text(stringResource(R.string.stores_itch_pick_none), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
else -> Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
for (build in list) key(build.id) { BuildRow(item, build) { install(build) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BuildRow(item: CatalogItem, build: GameJoltBuild, onInstall: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val linux = "linux" in build.platforms && !build.installable
|
||||
val canInstall = build.installable && (item.isFree || item.owned)
|
||||
val names = build.platforms.map { platformName(it) }
|
||||
val detail = listOfNotNull(
|
||||
names.joinToString(", "),
|
||||
build.size.takeIf { it > 0 }?.let { formatBytes(it) },
|
||||
build.version.takeIf { it.isNotBlank() },
|
||||
).joinToString(" · ")
|
||||
ListRow(enabled = !linux, onClick = { if (canInstall) onInstall() else openStoreUrl(ctx, item) }) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(build.filename.ifBlank { build.packageTitle.ifBlank { item.title } }, fontSize = 13.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(detail, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
val label = when {
|
||||
canInstall -> stringResource(R.string.stores_install)
|
||||
linux -> stringResource(R.string.stores_itch_build_linux_soon)
|
||||
else -> stringResource(R.string.stores_gamejolt_build_open)
|
||||
}
|
||||
Text(label, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun platformName(platform: String): String = stringResource(
|
||||
when (platform) {
|
||||
"windows" -> R.string.stores_itch_build_windows
|
||||
"linux" -> R.string.stores_itch_build_linux
|
||||
"osx" -> R.string.stores_itch_build_macos
|
||||
"other" -> R.string.stores_gamejolt_os_other
|
||||
else -> R.string.stores_itch_build_web
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltUpdate
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltUpdates
|
||||
|
||||
@Composable
|
||||
internal fun GameJoltCheckButton(installed: InstalledStoreGame) {
|
||||
val ctx = LocalContext.current
|
||||
IconAction(Icons.Filled.Refresh, stringResource(R.string.store_check_updates), "game:check-updates", enabled = GameJoltUpdates.checkingKey == null, frosted = true) {
|
||||
GameJoltUpdates.checkGame(ctx, installed)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun GameJoltUpdateButton(installed: InstalledStoreGame, enabled: Boolean) {
|
||||
val ctx = LocalContext.current
|
||||
val update = GameJoltUpdates.available[installed.key] ?: return
|
||||
var asking by remember { mutableStateOf(false) }
|
||||
SecondaryButton(stringResource(R.string.common_update), enabled = enabled) {
|
||||
if (update.replaced) asking = true else GameJoltUpdates.start(ctx, installed, update)
|
||||
}
|
||||
if (asking) GameJoltReplacedDialog(installed, update) { asking = false }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GameJoltReplacedDialog(installed: InstalledStoreGame, update: GameJoltUpdate, onDismiss: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
AppDialog(shown, close, "gameJoltUpdate", wide = false, maxWidth = 460.dp) {
|
||||
DialogTitleRow(installed.sidecar.title, close)
|
||||
Text(
|
||||
stringResource(R.string.stores_itch_update_replaced, update.filename.ifBlank { update.buildId }),
|
||||
fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
PrimaryButton(stringResource(R.string.common_update)) {
|
||||
close()
|
||||
GameJoltUpdates.start(ctx, installed, update)
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.common_cancel)) { close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
@@ -19,6 +20,7 @@ import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -27,6 +29,7 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
@@ -44,16 +47,29 @@ internal fun ItchBrowseBar() {
|
||||
var picking by remember { mutableStateOf(false) }
|
||||
Column(Modifier.fillMaxWidth().padding(top = 6.dp, bottom = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
ChipRow {
|
||||
for (sort in ItchBrowse.sorts) BrowseChip(sortLabel(sort), query.sort == sort) { ItchBrowseState.choose(ctx, query.copy(sort = sort)) }
|
||||
}
|
||||
ChipRow {
|
||||
for (price in ItchBrowse.prices) BrowseChip(priceLabel(price), query.price == price) { ItchBrowseState.choose(ctx, query.copy(price = price)) }
|
||||
}
|
||||
ChipRow {
|
||||
BrowseChip(stringResource(R.string.stores_itch_platform_any), query.platforms.isEmpty()) { ItchBrowseState.choose(ctx, query.copy(platforms = emptySet())) }
|
||||
for (platform in ItchBrowse.platformNames) {
|
||||
val on = platform in query.platforms
|
||||
BrowseChip(platformLabel(platform), on) { ItchBrowseState.choose(ctx, query.copy(platforms = if (on) query.platforms - platform else query.platforms + platform)) }
|
||||
BrowseDropdown(sortLabel(query.sort)) { first, close ->
|
||||
ItchBrowse.sorts.forEachIndexed { index, sort ->
|
||||
MenuItem(sortLabel(sort), query.sort == sort, focusRequester = if (index == 0) first else null) {
|
||||
ItchBrowseState.choose(ctx, query.copy(sort = sort))
|
||||
close()
|
||||
}
|
||||
}
|
||||
}
|
||||
BrowseDropdown(priceLabel(query.price)) { first, close ->
|
||||
ItchBrowse.prices.forEachIndexed { index, price ->
|
||||
MenuItem(priceLabel(price), query.price == price, focusRequester = if (index == 0) first else null) {
|
||||
ItchBrowseState.choose(ctx, query.copy(price = price))
|
||||
close()
|
||||
}
|
||||
}
|
||||
}
|
||||
val anyPlatform = stringResource(R.string.stores_itch_platform_any)
|
||||
BrowseDropdown(browseSummary(ItchBrowse.platformNames.filter { it in query.platforms }.map { platformLabel(it) }, anyPlatform)) { first, _ ->
|
||||
MenuItem(anyPlatform, query.platforms.isEmpty(), focusRequester = first) { ItchBrowseState.choose(ctx, query.copy(platforms = emptySet())) }
|
||||
for (platform in ItchBrowse.platformNames) {
|
||||
val on = platform in query.platforms
|
||||
MenuItem(platformLabel(platform), on) { ItchBrowseState.choose(ctx, query.copy(platforms = if (on) query.platforms - platform else query.platforms + platform)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
ChipRow {
|
||||
@@ -83,7 +99,7 @@ internal fun ItchLoadMore() {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChipRow(content: @Composable () -> Unit) {
|
||||
internal fun ChipRow(content: @Composable () -> Unit) {
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).selectableGroup(),
|
||||
@@ -91,7 +107,22 @@ private fun ChipRow(content: @Composable () -> Unit) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BrowseChip(label: String, selected: Boolean, onClick: () -> Unit) {
|
||||
internal fun BrowseDropdown(text: String, content: @Composable ColumnScope.(FocusRequester, () -> Unit) -> Unit) {
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
CompositionLocalProvider(LocalChipMinWidth provides 0.dp) { ValueChip(text, expanded) { expanded = !expanded } }
|
||||
AnchoredMenu(expanded, onDismiss = { expanded = false }, compact = true, minWidth = 160.dp) { first -> content(first) { expanded = false } }
|
||||
}
|
||||
}
|
||||
|
||||
internal fun browseSummary(labels: List<String>, empty: String): String = when (labels.size) {
|
||||
0 -> empty
|
||||
1, 2 -> labels.joinToString(", ")
|
||||
else -> "${labels.first()} +${labels.size - 1}"
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun BrowseChip(label: String, selected: Boolean, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val shape = RoundedCornerShape(8.dp)
|
||||
|
||||
@@ -102,7 +102,8 @@ import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import com.droiddeck.launcher.stores.download.DownloadState
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
import com.droiddeck.launcher.stores.itch.ItchCollection
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltCollections
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltUpdates
|
||||
import com.droiddeck.launcher.stores.itch.ItchCollections
|
||||
import com.droiddeck.launcher.stores.itch.ItchUpdates
|
||||
import com.droiddeck.launcher.stores.gog.GogMaintenance
|
||||
@@ -142,20 +143,20 @@ internal fun libraryEntries(
|
||||
return out.distinctBy { it.key }
|
||||
}
|
||||
|
||||
internal fun collectionEntries(all: List<LibraryEntry>, items: List<CatalogItem>): List<LibraryEntry> {
|
||||
internal fun collectionEntries(all: List<LibraryEntry>, items: List<CatalogItem>, store: Store = Store.ITCH): List<LibraryEntry> {
|
||||
val keys = items.map { it.key }.toSet()
|
||||
val itch = all.filter { it.source == Store.ITCH.id }
|
||||
val have = itch.mapNotNull { it.storeKey }.toSet()
|
||||
return itch.filter { it.storeKey in keys } +
|
||||
items.filter { it.key !in have }.map { LibraryEntry(GameRef.key(it), Store.ITCH.id, it.title, null, it, false) }
|
||||
val own = all.filter { it.source == store.id }
|
||||
val have = own.mapNotNull { it.storeKey }.toSet()
|
||||
return own.filter { it.storeKey in keys } +
|
||||
items.filter { it.key !in have }.map { LibraryEntry(GameRef.key(it), store.id, it.title, null, it, false) }
|
||||
}
|
||||
|
||||
internal fun installedFirst(entries: List<LibraryEntry>): List<LibraryEntry> = entries.partition { it.installed }.let { (on, off) -> on + off }
|
||||
|
||||
internal const val LIBRARY_ALL = "all"
|
||||
internal fun librarySources(entries: List<LibraryEntry>, order: List<String>): List<String> =
|
||||
internal fun librarySources(entries: List<LibraryEntry>, order: List<String>, always: Set<String> = emptySet()): List<String> =
|
||||
(listOf(Library.SOURCE_STEAM) + arrangeStoreTabs(order, emptySet()).map { it.store.id } + Library.ADDED)
|
||||
.filter { source -> entries.any { it.source == source } }
|
||||
.filter { source -> source in always || entries.any { it.source == source } }
|
||||
|
||||
internal object LibraryDisplay {
|
||||
val scales = listOf(0.75f, 0.875f, 1f, 1.2f, 1.45f)
|
||||
@@ -225,7 +226,11 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
var showUninstalled by remember(LibraryView.ownedRequest) { mutableStateOf(SessionPrefs.libraryShowUninstalled(ctx)) }
|
||||
var collectionShows by remember { mutableStateOf<Pair<String, Boolean>?>(null) }
|
||||
val setShowUninstalled = { show: Boolean ->
|
||||
val picked = ItchCollections.selected.takeIf { LibraryView.source == Store.ITCH.id }
|
||||
val picked = when (LibraryView.source) {
|
||||
Store.ITCH.id -> ItchCollections.selected
|
||||
Store.GAMEJOLT.id -> GameJoltCollections.selected
|
||||
else -> null
|
||||
}
|
||||
if (picked != null) collectionShows = picked to show
|
||||
else {
|
||||
showUninstalled = show
|
||||
@@ -233,21 +238,32 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
}
|
||||
}
|
||||
val itchSignedIn = owned.containsKey(Store.ITCH)
|
||||
val listed = librarySources(all, SessionPrefs.storesTabOrder(ctx))
|
||||
val sources = if (itchSignedIn && Store.ITCH.id !in listed) listed + Store.ITCH.id else listed
|
||||
val gameJoltSignedIn = owned.containsKey(Store.GAMEJOLT)
|
||||
val sources = librarySources(all, SessionPrefs.storesTabOrder(ctx), listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn }).toSet())
|
||||
val source = LibraryView.source.takeIf { it == LIBRARY_ALL || it in sources } ?: LIBRARY_ALL
|
||||
val q = LibraryView.query.trim().lowercase()
|
||||
val xboxFilter = if (source == Store.XBOX.id) XboxLibraryFilter.current else XboxLibraryFilter.ALL
|
||||
LaunchedEffect(source, itchSignedIn) { if (source == Store.ITCH.id && itchSignedIn) {
|
||||
ItchCollections.load(ctx)
|
||||
ItchUpdates.check(ctx)
|
||||
} }
|
||||
val collection = if (source == Store.ITCH.id) ItchCollections.chosen() else null
|
||||
val pool = if (collection == null) all else collectionEntries(all, ItchCollections.gamesOf(collection.id).orEmpty())
|
||||
LaunchedEffect(source, itchSignedIn, gameJoltSignedIn) {
|
||||
if (source == Store.ITCH.id && itchSignedIn) {
|
||||
ItchCollections.load(ctx)
|
||||
ItchUpdates.check(ctx)
|
||||
}
|
||||
if (source == Store.GAMEJOLT.id && gameJoltSignedIn) {
|
||||
GameJoltCollections.load(ctx)
|
||||
GameJoltUpdates.check(ctx)
|
||||
}
|
||||
}
|
||||
val collectionId = when (source) {
|
||||
Store.ITCH.id -> ItchCollections.chosen()?.id
|
||||
Store.GAMEJOLT.id -> GameJoltCollections.chosen()?.id
|
||||
else -> null
|
||||
}
|
||||
val collectionItems = collectionId?.let { if (source == Store.GAMEJOLT.id) GameJoltCollections.gamesOf(it) else ItchCollections.gamesOf(it) }
|
||||
val pool = if (collectionId == null) all else collectionEntries(all, collectionItems.orEmpty(), Store.byId(source) ?: Store.ITCH)
|
||||
val matching = pool.filter {
|
||||
(source == LIBRARY_ALL || it.source == source) && (q.isEmpty() || it.title.lowercase().contains(q)) && keepsXbox(xboxFilter, it)
|
||||
}
|
||||
val listUninstalled = if (collection == null) showUninstalled else collectionShows?.takeIf { it.first == collection.id }?.second ?: true
|
||||
val listUninstalled = if (collectionId == null) showUninstalled else collectionShows?.takeIf { it.first == collectionId }?.second ?: true
|
||||
val candidates = if (listUninstalled) matching else matching.filter { it.installed }
|
||||
val hiddenUninstalled = if (listUninstalled) 0 else matching.count { !it.installed }
|
||||
val sort = s.storesSort
|
||||
@@ -332,7 +348,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
kotlinx.coroutines.delay(Motion.ms(240).toLong())
|
||||
focusWithinFrames({ ff.last?.startsWith("card:") == true }) { if (ff.firstTileAttached > 0) ff.firstTile else FocusRequester.Default }
|
||||
}
|
||||
if (all.isEmpty() && open == null && !itchSignedIn) {
|
||||
if (all.isEmpty() && open == null && !itchSignedIn && !gameJoltSignedIn) {
|
||||
LibraryEmpty(s, a, modifier)
|
||||
return
|
||||
}
|
||||
@@ -453,7 +469,7 @@ private fun LibraryGrid(
|
||||
contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp),
|
||||
) {
|
||||
item(key = "header", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = source == Store.ITCH.id) }
|
||||
Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = Store.byId(source)?.takeIf { it == Store.ITCH || it == Store.GAMEJOLT }) }
|
||||
}
|
||||
item(key = "filters", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Rise(1) { LibraryFilters(sources, source, onSource) }
|
||||
@@ -514,7 +530,7 @@ private fun LazyGridScope.libraryGrid(entries: List<LibraryEntry>, empty: Int, t
|
||||
@Composable
|
||||
private fun LibraryHeader(
|
||||
s: FrontEndState, a: FrontEndActions, total: Int, searchCleared: Boolean, xbox: Boolean,
|
||||
showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, collections: Boolean,
|
||||
showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, collections: Store?,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val narrow = LocalNarrowPane.current
|
||||
@@ -532,7 +548,7 @@ private fun LibraryHeader(
|
||||
) {
|
||||
DisplayButton()
|
||||
if (showUninstalled != null || xbox) LibraryFilterButton(showUninstalled, onShowUninstalled, xbox)
|
||||
if (collections) CollectionsButton()
|
||||
if (collections != null) CollectionsButton(collections)
|
||||
SortButton(s, a)
|
||||
ViewButton(s, a)
|
||||
GameFileFolderActions(s, a)
|
||||
@@ -725,7 +741,7 @@ internal fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?, showDownlo
|
||||
}
|
||||
}
|
||||
|
||||
private fun libraryUpdateAvailable(e: LibraryEntry): Boolean = e.storeKey?.let { it in ItchUpdates.available } == true ||
|
||||
private fun libraryUpdateAvailable(e: LibraryEntry): Boolean = e.storeKey?.let { it in ItchUpdates.available || it in GameJoltUpdates.available } == true ||
|
||||
e.source == Store.GOG.id && (e.item?.id ?: e.game?.storeId)?.let { GogMaintenance.checks[it]?.state } == GogMaintenance.State.AVAILABLE
|
||||
|
||||
@Composable
|
||||
@@ -863,16 +879,21 @@ private fun LibraryFilterButton(showUninstalled: Boolean?, onShowUninstalled: (B
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CollectionsButton() {
|
||||
private fun CollectionsButton(store: Store) {
|
||||
val pal = LocalPalette.current
|
||||
val ctx = LocalContext.current
|
||||
val title = stringResource(R.string.itch_collections)
|
||||
val all = stringResource(R.string.stores_tab_all)
|
||||
var at by remember { mutableStateOf<Rect?>(null) }
|
||||
val gameJolt = store == Store.GAMEJOLT
|
||||
val chosenTitle = if (gameJolt) GameJoltCollections.chosen()?.title else ItchCollections.chosen()?.title
|
||||
val selectedId = if (gameJolt) GameJoltCollections.selected else ItchCollections.selected
|
||||
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) {
|
||||
HeaderIconButton(title + " · " + (ItchCollections.chosen()?.title ?: all), CollectionsIcon, "itch-collections") {
|
||||
HeaderIconButton(title + " · " + (chosenTitle ?: all), CollectionsIcon, "${store.id}-collections") {
|
||||
val from = at ?: return@HeaderIconButton
|
||||
val choices = listOf<ItchCollection?>(null) + ItchCollections.list
|
||||
val choices = listOf<Pair<String, String>?>(null) + if (gameJolt) GameJoltCollections.list.map { c ->
|
||||
c.id to (c.title + (GameJoltCollections.gamesOf(c.id)?.let { " (" + it.size + ")" }.orEmpty()))
|
||||
} else ItchCollections.list.map { c -> c.id to (c.title + " (" + c.count + ")") }
|
||||
Steps.ask(StepAsk(
|
||||
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = choices.size,
|
||||
handle = { Icon(CollectionsIcon, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
|
||||
@@ -880,12 +901,12 @@ private fun CollectionsButton() {
|
||||
StepTitle(title)
|
||||
StepList {
|
||||
choices.forEachIndexed { i, c ->
|
||||
val picked = c?.id == ItchCollections.selected
|
||||
val picked = c?.first == selectedId
|
||||
StepChoice(
|
||||
c?.let { it.title + " (" + it.count + ")" } ?: all, selected = picked, enabled = open,
|
||||
c?.second ?: all, selected = picked, enabled = open,
|
||||
modifier = Modifier.fillMaxWidth().stepItem(i).then(if (picked) Modifier.focusRequester(first) else Modifier),
|
||||
) {
|
||||
ItchCollections.select(ctx, c?.id)
|
||||
if (gameJolt) GameJoltCollections.select(ctx, c?.first) else ItchCollections.select(ctx, c?.first)
|
||||
Steps.fold()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -460,7 +460,7 @@ internal fun LiftHero(
|
||||
scrim { sink.value }
|
||||
if (shown || open) Box(
|
||||
Modifier.fillMaxSize()
|
||||
.graphicsLayer { alpha = sink.value }.background(Color.Black.copy(alpha = 0.42f))
|
||||
.overhang().graphicsLayer { alpha = sink.value }.background(Color.Black.copy(alpha = 0.42f))
|
||||
.focusProperties { canFocus = false }
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, enabled = open && !launching) { close() },
|
||||
)
|
||||
|
||||
@@ -75,6 +75,8 @@ class ModeSettings(
|
||||
val gameStorage: String? = null,
|
||||
val storageOptions: List<com.droiddeck.launcher.session.GameStorage.Option> = emptyList(),
|
||||
val steamLibraries: List<com.droiddeck.launcher.session.SteamLibraries.Entry> = emptyList(),
|
||||
val foundSteamLibraries: List<com.droiddeck.launcher.session.SteamLibraries.Found> = emptyList(),
|
||||
val allFilesAccessMissing: Boolean = false,
|
||||
val storageDiagnostics: Boolean = false,
|
||||
val fexPreset: String? = null,
|
||||
val forceSsbs: Boolean = false,
|
||||
@@ -89,7 +91,7 @@ class ModeSettings(
|
||||
val steamController: String? = null,
|
||||
val unfoldedControls: Boolean? = null,
|
||||
val unfoldedControlsWithController: Boolean = false,
|
||||
val runSteamAtStartup: Boolean = false,
|
||||
val startupSession: String = SessionPrefs.STARTUP_OFF,
|
||||
val bootMovie: String? = null,
|
||||
val bootMovieSound: Boolean = true,
|
||||
val bootMovieCustomName: String? = null,
|
||||
@@ -126,6 +128,8 @@ class ModeSettingsActions(
|
||||
val onPickGameStorageFolder: () -> Unit = {},
|
||||
val onStorageDiagnostics: (Boolean) -> Unit = {},
|
||||
val onAddSteamLibrary: () -> Unit = {},
|
||||
val onAddFoundSteamLibrary: (path: String) -> Unit = {},
|
||||
val onAllowAllFilesAccess: () -> Unit = {},
|
||||
val onRenameSteamLibrary: (id: String, label: String) -> Unit = { _, _ -> },
|
||||
val onRemoveSteamLibrary: (id: String) -> Unit = {},
|
||||
val onFexPreset: (String) -> Unit = {},
|
||||
@@ -141,7 +145,7 @@ class ModeSettingsActions(
|
||||
val onSteamController: (String) -> Unit = {},
|
||||
val onUnfoldedControls: (Boolean) -> Unit = {},
|
||||
val onUnfoldedControlsWithController: (Boolean) -> Unit = {},
|
||||
val onRunSteamAtStartup: (Boolean) -> Unit = {},
|
||||
val onStartupSession: (String) -> Unit = {},
|
||||
val onBootMovie: (String) -> Unit = {},
|
||||
val onBootMovieSound: (Boolean) -> Unit = {},
|
||||
val onImportBootMovie: () -> Unit = {},
|
||||
@@ -355,11 +359,15 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto), null,
|
||||
s.pipAutoEnter, onChange = a.onPipAutoEnter)
|
||||
}
|
||||
if (steam) SettingsGroup(stringResource(R.string.mode_startup)) {
|
||||
ToggleRow(
|
||||
host, "steam-startup", stringResource(R.string.mode_steam_startup),
|
||||
stringResource(R.string.mode_steam_startup_hint),
|
||||
s.runSteamAtStartup, onChange = a.onRunSteamAtStartup,
|
||||
SettingsGroup(stringResource(R.string.mode_startup)) {
|
||||
ChoiceRow(
|
||||
host, "startup-session", stringResource(R.string.mode_startup_session),
|
||||
stringResource(R.string.mode_startup_session_hint),
|
||||
listOf(
|
||||
SessionPrefs.STARTUP_OFF to stringResource(R.string.common_never),
|
||||
SessionPrefs.STARTUP_STEAM to stringResource(R.string.rail_steam),
|
||||
SessionPrefs.STARTUP_DESKTOP to stringResource(R.string.rail_desktop),
|
||||
), s.startupSession, onPick = a.onStartupSession,
|
||||
)
|
||||
}
|
||||
extras.performance()
|
||||
@@ -417,6 +425,19 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
}
|
||||
}
|
||||
}
|
||||
if (s.steamLibraries.size < com.droiddeck.launcher.session.SteamLibraries.MAX) for (found in s.foundSteamLibraries) {
|
||||
SettingsRow(
|
||||
found.label,
|
||||
stringResource(R.string.libraries_found_hint, pluralStringResource(R.plurals.mode_added_count, found.games, found.games), found.shown),
|
||||
) {
|
||||
SecondaryButton(stringResource(R.string.libraries_add_found), compact = true) { a.onAddFoundSteamLibrary(found.path) }
|
||||
}
|
||||
}
|
||||
if (s.allFilesAccessMissing && s.steamLibraries.size < com.droiddeck.launcher.session.SteamLibraries.MAX) {
|
||||
SettingsRow(stringResource(R.string.libraries_access_title), stringResource(R.string.libraries_access_hint)) {
|
||||
SecondaryButton(stringResource(R.string.libraries_access_allow), compact = true, onClick = a.onAllowAllFilesAccess)
|
||||
}
|
||||
}
|
||||
SettingsRow(
|
||||
stringResource(R.string.libraries_add),
|
||||
if (s.steamLibraries.size < com.droiddeck.launcher.session.SteamLibraries.MAX) stringResource(R.string.libraries_hint)
|
||||
|
||||
@@ -58,6 +58,7 @@ class SecondScreenPresentation(
|
||||
private val onMenu: (() -> Unit)? = null,
|
||||
private val menu: (@androidx.compose.runtime.Composable () -> Unit)? = null,
|
||||
private val dashboard: (@androidx.compose.runtime.Composable () -> Unit)? = null,
|
||||
private val onSwap: (() -> Unit)? = null,
|
||||
) : Presentation(sessionActivity, display) {
|
||||
private val frame = FrameLayout(context)
|
||||
private var menuView: androidx.compose.ui.platform.ComposeView? = null
|
||||
@@ -246,7 +247,7 @@ class SecondScreenPresentation(
|
||||
SecondScreenMode.DESKTOP -> {
|
||||
ownComposeViews()
|
||||
root.addView(BottomDesktopPanel(context, onClose, onMenu,
|
||||
(onSteamMenu to onQam).takeIf { SessionState.mode == SessionService.MODE_STEAM }), weightParams())
|
||||
(onSteamMenu to onQam).takeIf { SessionState.mode == SessionService.MODE_STEAM }, onSwap), weightParams())
|
||||
}
|
||||
SecondScreenMode.NONE -> Unit
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.material.icons.outlined.Close
|
||||
import androidx.compose.material.icons.outlined.Terminal
|
||||
import androidx.compose.material.icons.outlined.Dashboard
|
||||
@@ -244,6 +245,9 @@ class DrawerActions(
|
||||
val textureAnisotropy: Int? = 0,
|
||||
val textureLodBias: String? = TextureFiltering.LOD_BIAS_OFF,
|
||||
val secondScreenMode: SecondScreenMode,
|
||||
val gameOnBottom: Boolean = false,
|
||||
val gameSwapAvailable: Boolean = false,
|
||||
val onGameOnBottom: (Boolean) -> Unit = {},
|
||||
val dashboardAvailable: Boolean = false,
|
||||
val desktopAvailable: Boolean = false,
|
||||
val secondScreenDisplays: List<SecondScreenDisplay>,
|
||||
@@ -475,8 +479,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
SteamActionPill(
|
||||
stringResource(R.string.common_close), Icons.Outlined.Close, focus.track(page, "close"),
|
||||
) { host.open = null; a.onClose() }
|
||||
Spacer(Modifier.width(4.dp))
|
||||
BottomScreenModes(a, focus.track(page, "bottom-modes")) { host.open = null }
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
SteamActionPill(
|
||||
@@ -876,69 +878,15 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit
|
||||
val fill by animateColorAsState(if (hot) colors.error.copy(alpha = 0.18f) else Color.Transparent, Motion.tw(220), label = "dangerFill")
|
||||
val shape = RoundedCornerShape(20.dp)
|
||||
val stopDescription = stringResource(R.string.stop_session)
|
||||
val stopLabel = stringResource(R.string.drawer_stop)
|
||||
var iconOnly by remember(stopLabel, androidx.compose.ui.platform.LocalConfiguration.current.screenWidthDp) { mutableStateOf(false) }
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = modifier.heightIn(min = 44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop")
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center,
|
||||
modifier = modifier.heightIn(min = 44.dp).widthIn(min = 44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop")
|
||||
.clip(shape).background(fill).glideBorder(hot, shape, colors.error.copy(alpha = 0.9f), colors.error.copy(alpha = 0.55f))
|
||||
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onClick)
|
||||
.controllerConfirm(onClick = onClick)
|
||||
.padding(start = 12.dp, end = 14.dp),
|
||||
.padding(horizontal = 12.dp),
|
||||
) {
|
||||
Icon(Icons.Outlined.PowerSettingsNew, contentDescription = null, tint = colors.error, modifier = Modifier.size(18.dp))
|
||||
if (!iconOnly) Text(
|
||||
stopLabel, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.error,
|
||||
maxLines = 1, softWrap = false, onTextLayout = { if (it.hasVisualOverflow) iconOnly = true },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BottomScreenModes(a: DrawerActions, modifier: Modifier, onPick: () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val modes = buildList {
|
||||
if (com.droiddeck.launcher.session.SessionState.deckPad) add(SecondScreenMode.DECK_CONTROLS to Icons.Outlined.SportsEsports)
|
||||
add(SecondScreenMode.KEYBOARD_TRACKPAD to Icons.Outlined.Keyboard)
|
||||
add(SecondScreenMode.TERMINAL to Icons.Outlined.Terminal)
|
||||
if (a.dashboardAvailable) add(SecondScreenMode.DASHBOARD to Icons.Outlined.Dashboard)
|
||||
if (a.desktopAvailable) add(SecondScreenMode.DESKTOP to Icons.Outlined.DesktopWindows)
|
||||
}
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
modifier = modifier.focusGroup().clip(RoundedCornerShape(26.dp)).border(1.dp, pal.line, RoundedCornerShape(26.dp)).padding(4.dp),
|
||||
) {
|
||||
modes.forEach { (mode, icon) ->
|
||||
val selected = a.secondScreenMode == mode
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
|
||||
val shape = RoundedCornerShape(20.dp)
|
||||
val pick = { onPick(); a.onSecondScreenMode(mode) }
|
||||
val label = stringResource(mode.label)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(width = 52.dp, height = 40.dp).semantics { contentDescription = label }
|
||||
.clip(shape)
|
||||
.background(when {
|
||||
selected -> pal.signal
|
||||
hot -> pal.signal.copy(alpha = 0.14f)
|
||||
else -> Color.Transparent
|
||||
})
|
||||
.glideBorder(hot, shape, pal.signal)
|
||||
.hoverable(source)
|
||||
.selectable(selected, interactionSource = source, indication = LocalIndication.current, role = Role.Tab, onClick = pick)
|
||||
.controllerConfirm(onClick = pick),
|
||||
) {
|
||||
Icon(icon, contentDescription = null, modifier = Modifier.size(22.dp),
|
||||
tint = when {
|
||||
selected -> colors.background
|
||||
hot -> pal.signal
|
||||
else -> colors.onBackground
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1231,6 +1179,11 @@ private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String)
|
||||
a.secondScreenDisplays.map { it.id to it.label }, a.selectedSecondScreenDisplay,
|
||||
chipModifier = track("second-screen-display"), onPick = a.onSecondScreenDisplay)
|
||||
}
|
||||
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)),
|
||||
a.gameOnBottom, chipModifier = track("game-screen"), onPick = a.onGameOnBottom)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -26,6 +26,7 @@ import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.stateDescription
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
@@ -371,11 +372,12 @@ fun MenuItem(
|
||||
.background(if (hot && enabled) Color.White.copy(alpha = 0.07f) else Color.Transparent)
|
||||
.glideBorder(hot && enabled, RoundedCornerShape(8.dp), pal.signal)
|
||||
.alpha(if (enabled) 1f else 0.4f)
|
||||
.semantics { selected = checked }
|
||||
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
|
||||
.controllerConfirm(enabled = enabled, onClick = onClick)
|
||||
.padding(horizontal = 10.dp, vertical = 9.dp),
|
||||
) {
|
||||
Text("✓", fontSize = 12.sp, color = pal.signal, modifier = Modifier.width(18.dp).alpha(if (checked) 1f else 0f))
|
||||
Text("✓", fontSize = 12.sp, color = pal.signal, modifier = Modifier.width(18.dp).alpha(if (checked) 1f else 0f).clearAndSetSemantics {})
|
||||
if (leading != null) {
|
||||
leading()
|
||||
Spacer(Modifier.width(8.dp))
|
||||
|
||||
@@ -61,11 +61,11 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import coil.compose.AsyncImage
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.hud.DroidDeckMark
|
||||
import com.droiddeck.launcher.hud.FrameStats
|
||||
import com.droiddeck.launcher.hud.HudMetrics
|
||||
import com.droiddeck.launcher.session.StatsHud
|
||||
import java.io.File
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
@@ -164,10 +164,6 @@ private fun HudPanel(clock: String, right: String?, dim: Boolean, accent: Color,
|
||||
val divider = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = argb(if (dim) 38 else 90, a) }
|
||||
val blur = BlurMaskFilter(4.dp.toPx(), BlurMaskFilter.Blur.NORMAL)
|
||||
val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = stroke; color = argb(if (dim) 90 else 255, a) }
|
||||
val markH = min(h, w) * 0.55f
|
||||
val markX = w - DroidDeckMark.widthFor(markH) - 16.dp.toPx()
|
||||
val markBody = android.graphics.Color.argb(if (dim) 9 else 20, 255, 255, 255)
|
||||
val markOrb = argb(if (dim) 9 else 20, a)
|
||||
onDrawBehind {
|
||||
drawIntoCanvas { canvas ->
|
||||
val c = canvas.nativeCanvas
|
||||
@@ -176,7 +172,6 @@ private fun HudPanel(clock: String, right: String?, dim: Boolean, accent: Color,
|
||||
c.clipPath(body)
|
||||
c.drawRect(0f, 0f, w, headerPx + 1f, band)
|
||||
c.drawRect(0f, headerPx, w, headerPx + max(1f, density), divider)
|
||||
DroidDeckMark.draw(c, markX, (h - markH) / 2f, markH, markBody, markOrb)
|
||||
c.restore()
|
||||
for (pass in 0..2) {
|
||||
line.maskFilter = if (pass < 2) blur else null
|
||||
@@ -189,8 +184,7 @@ private fun HudPanel(clock: String, right: String?, dim: Boolean, accent: Color,
|
||||
.padding(start = 24.dp, end = 34.dp, bottom = 14.dp),
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth().height(HEADER), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
DroidDeckLogo(16.dp, body = headerInk, orb = if (dim) accent.copy(alpha = 0.5f) else accent)
|
||||
Text("DroidDeck", fontSize = 14.sp, fontWeight = FontWeight.Bold, color = headerInk, maxLines = 1)
|
||||
Wordmark(14.dp, ink = headerInk, ball = if (dim) accent.copy(alpha = 0.5f) else accent)
|
||||
if (clock.isNotEmpty()) {
|
||||
Text("·", fontSize = 13.sp, fontFamily = Mono, color = HudInk.sep)
|
||||
Text(clock, fontSize = 13.sp, fontFamily = Mono, fontWeight = FontWeight.Bold, color = HudInk.dim, maxLines = 1)
|
||||
@@ -271,13 +265,18 @@ private fun lowsText(d: HudData, size: TextUnit, accent: Color, deep: Boolean =
|
||||
}
|
||||
}
|
||||
|
||||
private val GRAPH_MIN_GAP = 3.dp
|
||||
|
||||
@Composable
|
||||
private fun Graph(values: List<Float>, lo: Float, hi: Float, color: Color, modifier: Modifier) {
|
||||
Canvas(modifier) {
|
||||
if (values.size < 2 || hi <= lo) return@Canvas
|
||||
val stride = ceil(GRAPH_MIN_GAP.toPx() * (values.size - 1) / size.width).toInt().coerceAtLeast(1)
|
||||
val points = if (stride == 1) values else values.chunked(stride) { it.average().toFloat() }
|
||||
if (points.size < 2) return@Canvas
|
||||
val path = Path()
|
||||
values.forEachIndexed { i, v ->
|
||||
val x = i / (values.size - 1f) * size.width
|
||||
points.forEachIndexed { i, v ->
|
||||
val x = i / (points.size - 1f) * size.width
|
||||
val y = size.height - ((v - lo) / (hi - lo)).coerceIn(0f, 1f) * size.height
|
||||
if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)
|
||||
}
|
||||
|
||||
@@ -111,8 +111,7 @@ private fun LogoBadge(size: Dp) {
|
||||
private fun LogoHeader(clock: String, game: String?) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 2.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
DroidDeckLogo(16.dp)
|
||||
Text("DroidDeck", fontSize = 13.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
Wordmark(14.dp, ink = colors.onBackground)
|
||||
Text(game.orEmpty(), fontSize = 13.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, textAlign = TextAlign.Center,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
if (clock.isNotEmpty()) Text(clock, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
|
||||
|
||||
@@ -38,6 +38,8 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.geometry.Rect
|
||||
import androidx.compose.ui.layout.boundsInParent
|
||||
import androidx.compose.ui.layout.layout
|
||||
import androidx.compose.ui.unit.Constraints
|
||||
import androidx.compose.ui.layout.onPlaced
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -166,11 +168,17 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
||||
)
|
||||
}
|
||||
|
||||
internal fun Modifier.overhang(by: androidx.compose.ui.unit.Dp = 4.dp): Modifier = layout { measurable, constraints ->
|
||||
val e = by.roundToPx()
|
||||
val placeable = measurable.measure(Constraints.fixed(constraints.maxWidth + e * 2, constraints.maxHeight + e * 2))
|
||||
layout(constraints.maxWidth, constraints.maxHeight) { placeable.place(-e, -e) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun WallFade() {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Box(
|
||||
Modifier.fillMaxSize().background(
|
||||
Modifier.fillMaxSize().overhang().background(
|
||||
Brush.horizontalGradient(
|
||||
0f to colors.background.copy(alpha = 0.97f),
|
||||
0.34f to colors.background.copy(alpha = 0.86f),
|
||||
@@ -179,7 +187,7 @@ internal fun WallFade() {
|
||||
),
|
||||
),
|
||||
)
|
||||
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0.55f to Color.Transparent, 1f to colors.background.copy(alpha = 0.9f))))
|
||||
Box(Modifier.fillMaxSize().overhang().background(Brush.verticalGradient(0.55f to Color.Transparent, 1f to colors.background.copy(alpha = 0.9f))))
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -31,6 +31,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) {
|
||||
Store.AMAZON.id -> SourceColours(Color(0xFF3A2A0A), Color(0xFFFFC266), Color(0xFFFF9900))
|
||||
Store.XBOX.id -> SourceColours(Color(0xFF17381B), Color(0xFFC6EDC2), Color(0xFF70C850))
|
||||
Store.ITCH.id -> SourceColours(Color(0xFF3A1A1E), Color(0xFFFFB3B3), Color(0xFFFF5C5C))
|
||||
Store.GAMEJOLT.id -> SourceColours(Color(0xFF232E00), Color(0xFFE3FF66), Color(0xFFCCFF00))
|
||||
Store.BATTLENET.id -> SourceColours(Color(0xFF0A2440), Color(0xFF9DD1FF), Color(0xFF148EFF))
|
||||
Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
|
||||
FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal)
|
||||
@@ -45,6 +46,7 @@ internal fun sourceLabel(source: String): String = when (source) {
|
||||
Store.AMAZON.id -> Store.AMAZON.label
|
||||
Store.XBOX.id -> Store.XBOX.label
|
||||
Store.ITCH.id -> Store.ITCH.label
|
||||
Store.GAMEJOLT.id -> Store.GAMEJOLT.label
|
||||
Store.BATTLENET.id -> Store.BATTLENET.label
|
||||
else -> stringResource(R.string.source_added)
|
||||
}
|
||||
|
||||
@@ -130,6 +130,7 @@ import coil.compose.AsyncImage
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.gamejolt.GameJoltBrowseState
|
||||
import com.droiddeck.launcher.stores.itch.ItchBrowseState
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreTab
|
||||
@@ -389,7 +390,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
|
||||
}
|
||||
}
|
||||
},
|
||||
) { key -> GameDetail(key, s, a, heroFocus, backLabel, hopRail = null, onBack = { closeGame() }) }
|
||||
) { key -> GameDetail(key, s, a, heroFocus, backLabel, hopRail = null, onBack = { closeGame() }, inStore = true) }
|
||||
}
|
||||
FlightLayer(hostAt)
|
||||
StoresMotion.step?.let { ask ->
|
||||
@@ -827,8 +828,10 @@ private fun Storefront(
|
||||
fun shown(i: CatalogItem) = s.storesShowMature || !i.mature || i.accessible
|
||||
fun shelf(l: List<CatalogItem>?) = l?.filter(::shown)
|
||||
LaunchedEffect(store, q) { StoresState.search(ctx, store, q) }
|
||||
val browsing = store == Store.ITCH && q.isEmpty() && ItchBrowseState.active
|
||||
val browseItems = if (browsing) ItchBrowseState.items else emptyList()
|
||||
val gameJolt = store == Store.GAMEJOLT
|
||||
LaunchedEffect(gameJolt, s.storesShowMature) { if (gameJolt) GameJoltBrowseState.sync(ctx, s.storesShowMature) }
|
||||
val browsing = q.isEmpty() && ((store == Store.ITCH && ItchBrowseState.active) || gameJolt)
|
||||
val browseItems = if (!browsing) emptyList() else if (gameJolt) GameJoltBrowseState.items else ItchBrowseState.items
|
||||
val catalog = store == Store.BATTLENET && q.isEmpty()
|
||||
val visible = remember(found, library, shelves, q, s.storesShowMature, browsing, browseItems, catalog) {
|
||||
if (catalog) shelf(shelves?.trending) ?: emptyList()
|
||||
@@ -840,8 +843,10 @@ private fun Storefront(
|
||||
.filter { (it.title.lowercase().contains(q) || it.key in foundKeys) && shown(it) }
|
||||
}
|
||||
val nothing = stringResource(when {
|
||||
browsing && ItchBrowseState.loading -> R.string.stores_shelves_loading
|
||||
browsing && ItchBrowseState.failed -> R.string.stores_itch_browse_failed
|
||||
browsing && gameJolt && GameJoltBrowseState.loading -> R.string.stores_shelves_loading
|
||||
browsing && gameJolt && GameJoltBrowseState.failed -> R.string.stores_gamejolt_browse_failed
|
||||
browsing && !gameJolt && ItchBrowseState.loading -> R.string.stores_shelves_loading
|
||||
browsing && !gameJolt && ItchBrowseState.failed -> R.string.stores_itch_browse_failed
|
||||
catalog && shelves == null -> R.string.stores_shelves_loading
|
||||
else -> R.string.stores_nothing_matches
|
||||
})
|
||||
@@ -857,7 +862,8 @@ private fun Storefront(
|
||||
val bareTab = if (searching) visible.isEmpty() else shelves == null || shelves.isEmpty
|
||||
val barLine = StoresState.status[store]?.takeIf { bareTab && syncCount(it) != null }
|
||||
val itchBar = store == Store.ITCH && q.isEmpty()
|
||||
val headerItems = 2 + (if (barLine != null) 1 else 0) + (if (StoresState.problems[store] != null) 1 else 0) + (if (itchBar) 1 else 0) + (if (catalog) 1 else 0)
|
||||
val gameJoltBar = gameJolt && q.isEmpty()
|
||||
val headerItems = 2 + (if (barLine != null) 1 else 0) + (if (StoresState.problems[store] != null) 1 else 0) + (if (itchBar || gameJoltBar) 1 else 0) + (if (catalog) 1 else 0)
|
||||
val card: @Composable (CatalogItem) -> Unit = { item ->
|
||||
val first = if (searching) item.key == visible.firstOrNull()?.key else !firstPlaced
|
||||
firstPlaced = true
|
||||
@@ -906,12 +912,14 @@ private fun Storefront(
|
||||
barLine?.let { line -> item(key = "sync", span = { GridItemSpan(maxLineSpan) }) { Rise(3) { SyncBar(line) } } }
|
||||
StoresState.problems[store]?.let { line -> item(key = "problem", span = { GridItemSpan(maxLineSpan) }) { Rise(3) { Box(Modifier.padding(bottom = 8.dp)) { Note(line) } } } }
|
||||
if (itchBar) item(key = "itch-browse-bar", span = { GridItemSpan(maxLineSpan) }) { ItchBrowseBar() }
|
||||
if (gameJoltBar) item(key = "gamejolt-browse-bar", span = { GridItemSpan(maxLineSpan) }) { GameJoltBrowseBar(s.storesShowMature) }
|
||||
if (catalog) item(key = "catalog-label", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Box(Modifier.padding(top = 10.dp)) { SectionLabel(stringResource(R.string.bnet_store)) }
|
||||
}
|
||||
if (searching) {
|
||||
storeGrid(visible, nothing, card)
|
||||
if (browsing) item(key = "itch-more", span = { GridItemSpan(maxLineSpan) }) { ItchLoadMore() }
|
||||
if (browsing && gameJolt) item(key = "gamejolt-more", span = { GridItemSpan(maxLineSpan) }) { GameJoltLoadMore() }
|
||||
else if (browsing) item(key = "itch-more", span = { GridItemSpan(maxLineSpan) }) { ItchLoadMore() }
|
||||
} else item(key = "shelves", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Column {
|
||||
Shelf(stringResource(R.string.stores_shelf_new), shelf(shelves?.whatsNew), card)
|
||||
@@ -1147,6 +1155,7 @@ internal fun storePalette(base: Palette, store: Store?): Palette {
|
||||
Store.AMAZON -> Color(0xFFFF9900) to Color(0xFFE07800)
|
||||
Store.XBOX -> Color(0xFF70C850) to Color(0xFF107C10)
|
||||
Store.ITCH -> Color(0xFFFF5C5C) to Color(0xFFD93B3B)
|
||||
Store.GAMEJOLT -> Color(0xFFCCFF00) to Color(0xFFA3CC00)
|
||||
Store.BATTLENET -> Color(0xFF148EFF) to Color(0xFF0B6BD3)
|
||||
null -> return base
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.drawscope.scale
|
||||
import androidx.compose.ui.graphics.drawscope.translate
|
||||
import androidx.compose.ui.graphics.vector.PathParser
|
||||
@@ -16,22 +17,21 @@ import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.hud.WordmarkArt
|
||||
|
||||
@Composable
|
||||
internal fun Wordmark(height: Dp, modifier: Modifier = Modifier) {
|
||||
val ink = MaterialTheme.colorScheme.onBackground
|
||||
val ball = LocalPalette.current.signal
|
||||
internal fun Wordmark(height: Dp, modifier: Modifier = Modifier, ink: Color = MaterialTheme.colorScheme.onBackground, ball: Color = LocalPalette.current.signal) {
|
||||
val name = stringResource(R.string.app_name)
|
||||
val letters = remember { PathParser().parsePathString(LETTERS).toPath() }
|
||||
val leftHalf = remember { PathParser().parsePathString(LEFT_HALF).toPath() }
|
||||
val rightHalf = remember { PathParser().parsePathString(RIGHT_HALF).toPath() }
|
||||
Canvas(modifier.height(height).width(height * (BOX_W / BOX_H)).semantics { contentDescription = name }) {
|
||||
val k = size.height / BOX_H
|
||||
val letters = remember { PathParser().parsePathString(WordmarkArt.LETTERS).toPath() }
|
||||
val leftHalf = remember { PathParser().parsePathString(WordmarkArt.LEFT_HALF).toPath() }
|
||||
val rightHalf = remember { PathParser().parsePathString(WordmarkArt.RIGHT_HALF).toPath() }
|
||||
Canvas(modifier.height(height).width(height * (WordmarkArt.BOX_W / WordmarkArt.BOX_H)).semantics { contentDescription = name }) {
|
||||
val k = size.height / WordmarkArt.BOX_H
|
||||
scale(k, k, Offset.Zero) {
|
||||
translate(-BOX_X, -BOX_Y) {
|
||||
translate(-WordmarkArt.BOX_X, -WordmarkArt.BOX_Y) {
|
||||
drawPath(letters, ink)
|
||||
translate(239.135f, 123.36f) {
|
||||
scale(MARK_SCALE, MARK_SCALE, Offset.Zero) {
|
||||
scale(WordmarkArt.MARK_SCALE, WordmarkArt.MARK_SCALE, Offset.Zero) {
|
||||
translate(31.98f, 0f) {
|
||||
drawPath(leftHalf, ink)
|
||||
drawPath(rightHalf, ink)
|
||||
@@ -43,22 +43,3 @@ internal fun Wordmark(height: Dp, modifier: Modifier = Modifier) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private const val BOX_X = 239.135f
|
||||
private const val BOX_Y = 120.02f
|
||||
private const val BOX_W = 1040.7f - 239.135f
|
||||
private const val BOX_H = 243.2f - 120.02f
|
||||
private const val MARK_SCALE = 0.527445f
|
||||
|
||||
private const val LEFT_HALF = "M-31.98 0H56.055V40.489A71.81 71.81 0 0 0 56.055 183.231V223.72H-31.98Z"
|
||||
private const val RIGHT_HALF = "M71.885 0.28A111.86 111.86 0 0 1 71.885 223.44V183.234A71.81 71.81 0 0 0 71.885 40.486Z"
|
||||
private const val LETTERS =
|
||||
"M361.45 241.36V160.13H387.02V241.36ZM387.02 196.73 376.32 188.38Q379.5 174.17 387.02 166.31Q394.54 158.46 407.91 158.46Q413.76 158.46 418.19 160.21Q422.62 161.97 425.96 165.65L410.75 184.87Q409.08 183.03 406.57 182.03Q404.07 181.02 400.89 181.02Q394.54 181.02 390.78 184.95Q387.02 188.88 387.02 196.73" +
|
||||
"ZM467.91 243.2Q455.38 243.2 445.27 237.6Q435.15 232 429.3 222.31Q423.45 212.61 423.45 200.58Q423.45 188.54 429.3 179.02Q435.15 169.49 445.18 163.89Q455.21 158.29 467.91 158.29Q480.62 158.29 490.64 163.81Q500.67 169.32 506.52 178.93Q512.37 188.54 512.37 200.58Q512.37 212.61 506.52 222.31Q500.67 232 490.64 237.6Q480.62 243.2 467.91 243.2" +
|
||||
"ZM467.91 219.97Q473.43 219.97 477.61 217.54Q481.79 215.12 484.04 210.69Q486.3 206.26 486.3 200.58Q486.3 194.9 483.96 190.63Q481.62 186.37 477.52 183.95Q473.43 181.52 467.91 181.52Q462.56 181.52 458.39 183.95Q454.21 186.37 451.87 190.72Q449.53 195.06 449.53 200.75Q449.53 206.26 451.87 210.69Q454.21 215.12 458.39 217.54Q462.56 219.97 467.91 219.97" +
|
||||
"ZM523.4 241.36V160.13H548.98V241.36ZM536.27 148.93Q530.26 148.93 526.33 144.84Q522.4 140.74 522.4 134.89Q522.4 128.88 526.33 124.86Q530.26 120.85 536.27 120.85Q542.29 120.85 546.13 124.86Q549.98 128.88 549.98 134.89Q549.98 140.74 546.13 144.84Q542.29 148.93 536.27 148.93ZM599.95 243.03Q588.42 243.03 579.48 237.52Q570.54 232 565.44 222.47Q560.34 212.95 560.34 200.75Q560.34 188.54 565.44 179.02Q570.54 169.49 579.48 163.97Q588.42 158.46 599.95 158.46Q608.31 158.46 615.08 161.63Q621.85 164.81 626.28 170.41Q630.71 176.01 631.21 183.2V217.46Q630.71 224.65 626.36 230.41Q622.02 236.18 615.16 239.61Q608.31 243.03 599.95 243.03" +
|
||||
"ZM604.47 219.97Q609.98 219.97 613.99 217.54Q618 215.12 620.34 210.77Q622.68 206.43 622.68 200.75Q622.68 195.06 620.43 190.8Q618.17 186.54 614.08 184.03Q609.98 181.52 604.63 181.52Q599.28 181.52 595.19 184.03Q591.09 186.54 588.67 190.88Q586.25 195.23 586.25 200.75Q586.25 206.26 588.59 210.61Q590.93 214.95 595.11 217.46Q599.28 219.97 604.47 219.97" +
|
||||
"ZM646.75 241.36H621.68V219.46L625.53 199.74L621.18 180.02V120.02H646.75ZM683.19 241.36V218.29H712.44Q723.13 218.29 731.16 214.03Q739.18 209.77 743.53 201.58Q747.87 193.39 747.87 182.19Q747.87 170.99 743.44 162.97Q739.01 154.95 731.07 150.6Q723.13 146.26 712.44 146.26H682.35V123.36H712.77Q726.14 123.36 737.42 127.62Q748.71 131.88 757.15 139.82Q765.59 147.76 770.18 158.54Q774.78 169.32 774.78 182.36Q774.78 195.23 770.18 206.09Q765.59 216.96 757.23 224.81Q748.87 232.67 737.59 237.01Q726.31 241.36 713.11 241.36" +
|
||||
"ZM665.47 241.36V123.36H691.71V241.36ZM827.6 243.2Q814.39 243.2 804.11 237.77Q793.83 232.33 787.98 222.64Q782.13 212.95 782.13 200.75Q782.13 188.54 787.9 178.93Q793.67 169.32 803.53 163.81Q813.39 158.29 825.76 158.29Q837.79 158.29 846.98 163.47Q856.18 168.65 861.44 177.85Q866.71 187.04 866.71 198.91Q866.71 201.08 866.46 203.5Q866.21 205.93 865.54 209.1L795.51 209.27V191.72L854.67 191.55L843.64 198.91Q843.47 191.89 841.47 187.29Q839.46 182.69 835.54 180.27Q831.61 177.85 825.92 177.85Q819.91 177.85 815.48 180.61Q811.05 183.36 808.63 188.38Q806.2 193.39 806.2 200.58Q806.2 207.77 808.79 212.86Q811.38 217.96 816.15 220.72Q820.91 223.48 827.43 223.48Q833.45 223.48 838.29 221.39Q843.14 219.3 846.82 215.12L860.86 229.16Q854.84 236.18 846.32 239.69Q837.79 243.2 827.6 243.2" +
|
||||
"ZM916.68 243.2Q904.15 243.2 893.95 237.68Q883.75 232.17 877.9 222.47Q872.05 212.78 872.05 200.75Q872.05 188.54 877.99 178.93Q883.92 169.32 894.12 163.81Q904.31 158.29 917.02 158.29Q926.54 158.29 934.48 161.55Q942.42 164.81 948.6 171.33L932.22 187.71Q929.38 184.53 925.62 183.03Q921.86 181.52 917.02 181.52Q911.5 181.52 907.24 183.95Q902.98 186.37 900.55 190.63Q898.13 194.9 898.13 200.58Q898.13 206.26 900.55 210.61Q902.98 214.95 907.32 217.46Q911.67 219.97 917.02 219.97Q922.03 219.97 925.96 218.21Q929.88 216.46 932.73 213.28L948.94 229.66Q942.59 236.35 934.56 239.77Q926.54 243.2 916.68 243.2" +
|
||||
"ZM1010.61 241.36 982.2 199.24 1010.45 160.13H1039.03L1004.93 204.09L1005.77 193.56L1040.7 241.36ZM958.63 241.36V120.02H984.21V241.36Z"
|
||||
@@ -20,12 +20,15 @@ class BottomDesktopCompositorService : Service() {
|
||||
private var client: Messenger? = null
|
||||
/** Echoed in every reply, so the session process can tell replies to an earlier attach apart. */
|
||||
@Volatile private var attachTag = 0
|
||||
private var outputWidth = 0
|
||||
private var outputHeight = 0
|
||||
|
||||
private val handler = object : Handler(Looper.getMainLooper()) {
|
||||
override fun handleMessage(msg: Message) {
|
||||
when (msg.what) {
|
||||
MSG_ATTACH -> attach(msg)
|
||||
MSG_DETACH -> CompositorHost.detach(null)
|
||||
MSG_RESIZE -> resize(msg.arg1, msg.arg2)
|
||||
MSG_TOUCH -> WaylandCompositor.nativeSendTouch(msg.arg1 and 0xff, msg.arg1 shr 8,
|
||||
msg.arg2 ushr 16, msg.arg2 and 0xffff)
|
||||
MSG_KEY -> WaylandCompositor.nativeSendKey(msg.arg1, msg.arg2)
|
||||
@@ -75,15 +78,26 @@ class BottomDesktopCompositorService : Service() {
|
||||
}
|
||||
val turnip = com.droiddeck.launcher.gpu.TurnipDriver(this)
|
||||
val driverId = if (CompositorHost.isStarted) null else turnip.install()
|
||||
val resized = CompositorHost.isStarted && (width != outputWidth || height != outputHeight)
|
||||
val started = CompositorHost.startOrAttach(
|
||||
this, surface, runtimeDir.path, driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
|
||||
applicationInfo.nativeLibraryDir,
|
||||
width, height, data.getFloat(KEY_REFRESH, 60f), 0,
|
||||
)
|
||||
outputWidth = width
|
||||
outputHeight = height
|
||||
if (resized) WaylandCompositor.nativeResizeOutput(width, height)
|
||||
Log.i(TAG, (if (started) "compositor started" else "compositor attached") + " at ${width}x$height in ${runtimeDir.path}")
|
||||
reply(MSG_ATTACHED)
|
||||
}
|
||||
|
||||
private fun resize(width: Int, height: Int) {
|
||||
if (width <= 0 || height <= 0 || !CompositorHost.isStarted || (width == outputWidth && height == outputHeight)) return
|
||||
outputWidth = width
|
||||
outputHeight = height
|
||||
WaylandCompositor.nativeResizeOutput(width, height)
|
||||
}
|
||||
|
||||
private fun reply(what: Int) {
|
||||
val target = client ?: return
|
||||
runCatching { target.send(Message.obtain(null, what, attachTag, 0)) }
|
||||
@@ -102,6 +116,7 @@ class BottomDesktopCompositorService : Service() {
|
||||
const val MSG_POINTER = 8
|
||||
const val MSG_SCENE = 9
|
||||
const val MSG_CURSOR = 10
|
||||
const val MSG_RESIZE = 11
|
||||
const val MSG_ATTACHED = 101
|
||||
const val MSG_FIRST_FRAME = 102
|
||||
const val KEY_RUNTIME_DIR = "runtimeDir"
|
||||
|
||||
Reference in new issue
Block a user