Merge upstream shortcuts and dual-screen session updates

Preserve profile bindings, shared held-input ownership and custom panels alongside upstream physical shortcuts, mouse routing and docked menus. Add integration regressions and record the full 2,918-test JVM run.
This commit is contained in:
Delete228 committed 2026-10-30 17:00:29 +03:00
commit d6b4b0589b
630 files changed
+42269 -1875

No files matched your search

@@ -46,6 +46,7 @@ class App : Application() {
com.droiddeck.launcher.glasses.Glasses.init(this)
com.droiddeck.launcher.glasses.GlassesMenuMirror.initialize(this)
BwrapSpawner.start(this)
com.droiddeck.launcher.runtime.RootSpawner.start(this)
com.droiddeck.launcher.frontend.GameFileSync.start(this)
com.droiddeck.launcher.stores.StoresState.init(this)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.gog.GogBackend)
@@ -108,6 +108,8 @@ class FrontEndActivity : ComponentActivity() {
private var ready by mutableStateOf(false)
private var removalPending by mutableStateOf(false)
private var available by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
private var catalogFresh = false
private var componentsQueueBusy by mutableStateOf(false)
private var busy by mutableStateOf(false)
private var stage by mutableStateOf("")
private var percent by mutableIntStateOf(-1)
@@ -212,6 +214,7 @@ class FrontEndActivity : ComponentActivity() {
}
private val mediaReceiver = object : android.content.BroadcastReceiver() {
override fun onReceive(context: android.content.Context?, intent: Intent?) {
usbScan++
ui.removeCallbacks(mediaRefresh)
ui.postDelayed(mediaRefresh, MEDIA_SETTLE_MS)
}
@@ -471,6 +474,16 @@ class FrontEndActivity : ComponentActivity() {
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
private var backActionsInverted by mutableStateOf(false)
private var gameStorage by mutableStateOf("")
private var slowUsb by mutableStateOf<com.droiddeck.launcher.session.UsbLink.SlowDrive?>(null)
private var usbScan = 0
private var slowUsbNever by mutableStateOf(false)
private fun showSlowUsb(drive: com.droiddeck.launcher.session.UsbLink.SlowDrive?) {
val off = slowUsbNever
if (off) SessionPrefs.setSlowUsbWarningOff(this)
slowUsbNever = false
slowUsb = drive.takeUnless { off }
}
private var storageDiagnostics by mutableStateOf(false)
private var storageOptions by mutableStateOf<List<GameStorage.Option>>(emptyList())
private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
@@ -513,6 +526,12 @@ class FrontEndActivity : ComponentActivity() {
}
}
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
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 dualScreenControls by mutableStateOf(true)
private var launcherStarted = false
private lateinit var displayManager: DisplayManager
private val secondScreenDisplayListener = object : DisplayManager.DisplayListener {
override fun onDisplayAdded(displayId: Int) = refreshSecondScreenDisplays()
@@ -533,6 +552,10 @@ class FrontEndActivity : ComponentActivity() {
android.widget.Toast.makeText(this, R.string.main_wait_runtime, android.widget.Toast.LENGTH_SHORT).show()
return
}
SessionState.installing != null && !SessionState.running -> {
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
return
}
compat -> Unit
pkgStage != null -> {
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
@@ -558,12 +581,12 @@ class FrontEndActivity : ComponentActivity() {
}
private fun launchFlooded(f: PendingFlood) {
if (busy || LinuxRuntimeInstaller.isBusy() || protons.protonBusyId != null ||
ProtonExtras.installInProgress || pkgStage != null) {
if (busy || LinuxRuntimeInstaller.isBusy() || (SessionState.installing != null && !SessionState.running) ||
protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
flood = null
floodProgress = 0f
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
if (!busy && !LinuxRuntimeInstaller.isBusy() &&
if (!busy && !LinuxRuntimeInstaller.isBusy() && !(SessionState.installing != null && !SessionState.running) &&
(protons.protonBusyId != null || ProtonExtras.installInProgress)) {
compatFlood = com.droiddeck.launcher.ui.Themes.byId(theme).signal
waitForCompat(f.intent)
@@ -597,7 +620,7 @@ class FrontEndActivity : ComponentActivity() {
}
if (!compatLaunchVisible) { ui.postDelayed(this, 250); return }
val problem = protons.protonProblem.takeIf { waiting.menuInstall }
if (problem == null && (busy || LinuxRuntimeInstaller.isBusy() || pkgStage != null)) {
if (problem == null && (busy || LinuxRuntimeInstaller.isBusy() || (SessionState.installing != null && !SessionState.running) || pkgStage != null)) {
waiting.loading.say(pkgStage ?: stage.takeIf { it.isNotBlank() } ?: getString(R.string.main_wait_runtime),
com.droiddeck.launcher.session.LoadingState.Topic.RUNTIME, readable = true)
waiting.loading.percent = if (pkgStage != null) pkgPercent else percent
@@ -644,7 +667,23 @@ class FrontEndActivity : ComponentActivity() {
private var shortcutPicker by mutableStateOf(false)
private var shortcutLibraryScanning by mutableStateOf(false)
@Volatile private var libraryScanGeneration = 0
@Volatile private var lastComponentRestore = 0L
@Volatile private var componentRestoreRetry = false
private val componentRestoreLock = Any()
private fun retryComponentRestore() {
val run = synchronized(componentRestoreLock) {
componentRestoreRetry = false
val now = android.os.SystemClock.elapsedRealtime()
(!isDestroyed && now - lastComponentRestore >= COMPONENT_RESTORE_MS).also { if (it) lastComponentRestore = now }
}
if (run) Thread({
runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) }
}, "components-restore").start()
}
private var pendingGameLink: String? = null
private var gameLinkReading = false
private var gameLinkTried = false
private var gameSyncFolder by mutableStateOf<String?>(null)
private fun pickGameExport(game: Library.SteamGame?) {
onSavePicked = { folder ->
@@ -685,14 +724,20 @@ class FrontEndActivity : ComponentActivity() {
shortcutLibraryScanning = true
} else shortcutLibraryScanning = false
pendingGameLink = null
gameLinkReading = false
gameLinkTried = false
if (GameLaunchIntent.accepts(request.action)) {
gameLinkReading = true
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
val copy = Intent(request)
Thread({
val id = GameLaunchIntent.read(this, copy)
ui.post {
if (intent === request && !isDestroyed) {
gameLinkReading = false
pendingGameLink = id
if (id == null) {
syncDualPanel()
android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show()
} else refresh()
}
@@ -900,12 +945,17 @@ class FrontEndActivity : ComponentActivity() {
private fun handleGameLink(games: List<Library.SteamGame>) {
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return
val id = pendingGameLink ?: return
gameLinkTried = true
ui.postDelayed({
if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel()
}, LINK_PANEL_MS)
val game = games.firstOrNull { it.gameIdString == id }
if (game == null) {
pendingGameLink = null
intent.data = null
intent.action = Intent.ACTION_MAIN
intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
syncDualPanel()
android.widget.Toast.makeText(this, R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show()
} else if (launchGame(game, returnHome = true)) {
pendingGameLink = null
@@ -960,6 +1010,13 @@ class FrontEndActivity : ComponentActivity() {
if (decky.deckyPendingZip != null) com.droiddeck.launcher.ui.DeckyZipWarningDialog(
onConfirm = { decky.confirmPluginZip() }, onCancel = { decky.cancelPluginZip() },
)
slowUsb?.let { drive ->
com.droiddeck.launcher.ui.SlowUsbDialog(drive, slowUsbNever, { slowUsbNever = it }) {
com.droiddeck.launcher.session.UsbLink.markShown(this, drive)
showSlowUsb(null)
checkUsbLink()
}
}
val page: (@Composable () -> Unit)? = when {
showPerformance -> { { PerformanceHost() } }
showComponents -> { { ComponentsHost() } }
@@ -994,6 +1051,11 @@ class FrontEndActivity : ComponentActivity() {
integrationFocus = integrationFocus,
androidApps = androidApps,
secondScreenDisplays = secondScreenDisplays,
dualScreen = dualDisplayId >= 0 && com.droiddeck.launcher.ui.DualScreenPanel.available,
dualScreenDevice = dualScreenDevice,
dualScreenMode = dualScreenMode,
dualScreenLauncher = dualScreenLauncher,
dualScreenControls = dualScreenControls,
packages = packageRows,
packageCatalogLoading = catalogLoading,
packageBusyId = pkgId,
@@ -1222,6 +1284,18 @@ class FrontEndActivity : ComponentActivity() {
onStoresSort = { sort -> SessionPrefs.setStoresSort(this, sort); storesSort = sort },
onStoresView = { view -> SessionPrefs.setStoresView(this, view); storesView = view },
onLibraryChanged = { refreshAddedGames(); refresh() },
onDualScreenMode = { mode ->
SessionPrefs.setDualScreenMode(this, mode)
refreshSecondScreenDisplays()
},
onDualScreenLauncher = { on ->
SessionPrefs.setDualScreenLauncher(this, on)
refreshSecondScreenDisplays()
},
onDualScreenControls = { on ->
SessionPrefs.setDualScreenSessionControls(this, on)
dualScreenControls = on
},
onAnimationsEnabled = { on ->
SessionPrefs.setAnimationsEnabled(this, on)
animationsEnabled = on
@@ -1310,7 +1384,7 @@ class FrontEndActivity : ComponentActivity() {
showPhantomGate = true
},
onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) },
onStartPairingGuide = { displayId -> PairingGuideActivity.start(this, displayId) },
onStartPairingGuide = { displayId, toggleOnly -> PairingGuideActivity.start(this, displayId, toggleOnly) },
onOpenNotificationSettings = {
startActivity(Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName)
@@ -1451,6 +1525,9 @@ class FrontEndActivity : ComponentActivity() {
super.onNewIntent(intent)
setIntent(intent)
if (intent.action == SteamIntegration.ACTION_SETUP) {
gameLinkReading = false
pendingGameLink = null
syncDualPanel()
readIntegrationIntent(intent)
return
}
@@ -1550,6 +1627,7 @@ class FrontEndActivity : ComponentActivity() {
override fun onResume() {
super.onResume()
compatLaunchVisible = true
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
orientation = SessionPrefs.orientation(this)
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
requestedOrientation = launcherOrientation
@@ -1567,14 +1645,21 @@ class FrontEndActivity : ComponentActivity() {
drivers.checkOnOpen()
resumeInterruptedPackages()
protons.checkUpdates()
if (!SessionState.running) Thread({
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
if (applied.isNotEmpty()) ui.post {
android.widget.Toast.makeText(this, getString(R.string.main_applied, applied.joinToString(", ")), android.widget.Toast.LENGTH_LONG).show()
}
ui.post { if (showComponents) components.refreshComponents() }
}, "components-queue").start()
else if (showComponents) components.refreshComponents()
catalogFresh = false
if (!SessionState.running && !componentsQueueBusy && !LinuxRuntimeInstaller.isBusy()) {
componentsQueueBusy = true
Thread({
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
if (applied.isNotEmpty()) ui.post {
android.widget.Toast.makeText(this, getString(R.string.main_applied, applied.joinToString(", ")), android.widget.Toast.LENGTH_LONG).show()
}
ui.post {
componentsQueueBusy = false
if (showComponents) components.refreshComponents()
autoUpdateRuntime()
}
}, "components-queue").start()
} else if (showComponents) components.refreshComponents()
oscMode = SessionPrefs.oscMode(this)
refreshController()
refreshHomeAppState()
@@ -1597,6 +1682,7 @@ class FrontEndActivity : ComponentActivity() {
addDataScheme("file")
})
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
launcherStarted = true
refreshSecondScreenDisplays()
getSystemService(android.content.pm.LauncherApps::class.java).registerCallback(packageCallback, ui)
HomeWidgets.startListening(this)
@@ -1611,6 +1697,7 @@ class FrontEndActivity : ComponentActivity() {
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
if (slowUsbNever) SessionPrefs.setSlowUsbWarningOff(this)
saveCompatLaunch(outState)
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
switchingTo?.let {
@@ -1638,6 +1725,8 @@ class FrontEndActivity : ComponentActivity() {
com.droiddeck.launcher.stores.StoresState.libraryListener = null
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
launcherStarted = false
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
flood = null
returning = null
floodProgress = 0f
@@ -1671,13 +1760,31 @@ class FrontEndActivity : ComponentActivity() {
if (!::displayManager.isInitialized) return
// The launcher can itself be shown on a non-default display (DeX, an external monitor); that one is not a "second screen".
val ownDisplayId = if (android.os.Build.VERSION.SDK_INT >= 30) display?.displayId ?: android.view.Display.DEFAULT_DISPLAY else @Suppress("DEPRECATION") windowManager.defaultDisplay.displayId
dualScreenMode = SessionPrefs.dualScreenMode(this)
secondScreenDisplays = SecondScreenDisplays.available(displayManager, ownDisplayId)
dualScreenDevice = com.droiddeck.launcher.input.DualScreen.anyDisplay(displayManager, ownDisplayId) != null
dualScreenLauncher = SessionPrefs.dualScreenLauncher(this)
dualScreenControls = SessionPrefs.dualScreenSessionControls(this)
val target = com.droiddeck.launcher.input.DualScreen.display(this, displayManager, ownDisplayId)
dualDisplayId = if (dualScreenLauncher) target?.displayId ?: -1 else -1
syncDualPanel()
}
private fun syncDualPanel() {
if (launchPending()) return
if (launcherStarted && dualDisplayId >= 0) com.droiddeck.launcher.ui.DualScreenPanel.show(this, dualDisplayId, taskId)
else com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
}
private fun launchPending(): Boolean = gameLinkReading || (pendingGameLink != null && !gameLinkTried)
private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) {
val onOwnScreen = displayId == null || displayId == (display?.displayId ?: Display.DEFAULT_DISPLAY)
if (onOwnScreen) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, true)
try {
HomeApp.launch(this, app, displayId)
} catch (_: Exception) {
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
val label = secondScreenDisplays.firstOrNull { it.id == displayId }?.label
val message = when {
displayId == null || displayId == Display.DEFAULT_DISPLAY -> getString(R.string.android_app_open_failed_primary, app.label)
@@ -2186,6 +2293,7 @@ class FrontEndActivity : ComponentActivity() {
}
private fun refreshAddedGames() {
checkUsbLink()
sgdbKeyKnown()
fetchAddedGameArt()
}
@@ -2290,6 +2398,20 @@ class FrontEndActivity : ComponentActivity() {
}
SessionPrefs.setGameStorage(this, path, label)
gameStorage = path
checkUsbLink()
}
private fun checkUsbLink() {
if (android.os.Looper.myLooper() != android.os.Looper.getMainLooper()) { ui.post { checkUsbLink() }; return }
val scan = ++usbScan
Thread({
val drive = runCatching { com.droiddeck.launcher.session.UsbLink.slowLibrary(this) }.getOrNull()
ui.post {
if (scan != usbScan || isFinishing) return@post
val due = drive?.takeIf { com.droiddeck.launcher.session.UsbLink.stillDue(this, it) }
if (due == null) { if (slowUsb != null) showSlowUsb(null) } else if (slowUsb?.key != due.key) showSlowUsb(due)
}
}, "usb-link").start()
}
private fun refreshCores() {
@@ -2338,6 +2460,7 @@ class FrontEndActivity : ComponentActivity() {
installed = LinuxRuntimeInstaller.installedVersion(this)
ready = LinuxRuntime.isInstalled(this)
removalPending = LinuxRuntimeInstaller.hasRemovalPending(this)
ui.post { autoUpdateRuntime() }
frameGenLabel = FrameGen.label(this)
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
logsEnabled = SessionPrefs.logsEnabled(this)
@@ -2384,11 +2507,28 @@ class FrontEndActivity : ComponentActivity() {
val all = games.distinctBy { it.gameId }
if (ready && scanGeneration == libraryScanGeneration) com.droiddeck.launcher.frontend.LibraryCache.save(this, all, scannedX64)
val endedSession = SessionState.sessionId.takeIf { !SessionState.running && it != null && it != componentSweepSession }
if (ready && (!componentSweepDone || endedSession != null)) {
val sweepDue = ready && (!componentSweepDone || endedSession != null)
if (sweepDue) {
componentSweepDone = true
endedSession?.let { componentSweepSession = it }
ui.postDelayed({ Thread({ com.droiddeck.launcher.frontend.AutoComponents.sweep(this, all) }, "components-sweep").start() }, 10_000)
}
val restoreDue = synchronized(componentRestoreLock) {
val now = android.os.SystemClock.elapsedRealtime()
val due = ready && (lastComponentRestore == 0L || now - lastComponentRestore >= COMPONENT_RESTORE_MS)
if (due) {
lastComponentRestore = now
} else if (ready && !componentRestoreRetry) {
componentRestoreRetry = true
ui.postDelayed({ retryComponentRestore() }, (COMPONENT_RESTORE_MS - (now - lastComponentRestore)).coerceAtLeast(0L))
}
due
}
if (restoreDue || sweepDue) ui.postDelayed({
Thread({
if (restoreDue) runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) }
if (sweepDue) com.droiddeck.launcher.frontend.AutoComponents.sweep(this, all)
}, "components-restore").start()
}, 10_000)
ui.post {
if (scanGeneration == libraryScanGeneration) {
val current = steamGames.filter { it.library != Library.ADDED }.associateBy { it.appId }
@@ -2429,6 +2569,10 @@ class FrontEndActivity : ComponentActivity() {
private fun startSession(intent: Intent, steamSession: Boolean = false): Boolean {
if (busy || LinuxRuntimeInstaller.isBusy()) return false
if (SessionState.installing != null && !SessionState.running) {
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
return false
}
if (com.droiddeck.launcher.storage.StorageState.cleaning) {
android.widget.Toast.makeText(this, R.string.storage_cleanup_busy, android.widget.Toast.LENGTH_SHORT).show()
return false
@@ -2478,7 +2622,7 @@ class FrontEndActivity : ComponentActivity() {
private fun runtimeChangesBlocked(): Boolean =
busy || LinuxRuntimeInstaller.isBusy() || SessionState.running ||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null ||
protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null || componentsQueueBusy ||
components.compBusy != null || saveBusy != null || com.droiddeck.launcher.store.UserAppsState.working != null
private fun removeDesktop() {
@@ -2538,15 +2682,32 @@ class FrontEndActivity : ComponentActivity() {
}, "runtime-operation").start()
}
private fun autoUpdateRuntime() {
val release = available?.takeIf { catalogFresh } ?: return
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED) || runtimeChangesBlocked() || removalPending) return
if (release.version == installed || installed == null) return
if (com.droiddeck.launcher.runtime.RuntimeAutoUpdate.claim(this, installed, release.version)) {
Log.i(TAG, "runtime: updating $installed to ${release.version} by itself")
install(release)
}
}
private fun checkCatalog() {
val release = LinuxRuntimeInstaller.fetchRelease()
Log.i(TAG, "catalog: " + (release?.version ?: "unreachable"))
ui.post { if (release != null) available = release }
ui.post {
if (release == null) return@post
available = release
catalogFresh = true
autoUpdateRuntime()
}
}
companion object {
private const val TAG = "MainActivity"
private const val MEDIA_SETTLE_MS = 1500L
private const val COMPONENT_RESTORE_MS = 60_000L
private const val LINK_PANEL_MS = 1500L
private const val SESSION_SWITCH_WAIT_MS = 30_000L
private const val SESSION_SWITCH_POLL_MS = 250L
private const val KEY_PENDING_SWITCH = "pending_switch"
@@ -58,6 +58,7 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.core.AppLanguage
import com.droiddeck.launcher.core.GlobalSettings
import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.WirelessAdbPairingService
import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage
import com.droiddeck.launcher.ui.DroidDeckTheme
@@ -67,9 +68,10 @@ import com.droiddeck.launcher.ui.SecondaryButton
import kotlinx.coroutines.delay
class PairingGuideActivity : ComponentActivity() {
enum class Step { BUILD_NUMBER, WIRELESS_DEBUGGING, PAIR, CODE, WORKING, DONE, FAILED }
enum class Step { BUILD_NUMBER, CHILD_PROCESS, WIRELESS_DEBUGGING, PAIR, CODE, WORKING, DONE, FAILED }
private var settingsDisplay: Int? = null
private var toggleOnly = false
private var inPip by mutableStateOf(false)
private var launchPending = false
@@ -78,6 +80,7 @@ class PairingGuideActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
toggleOnly = intent.getBooleanExtra(EXTRA_TOGGLE_ONLY, false)
setContent { DroidDeckTheme { Guide() } }
launchPending = savedInstanceState == null
}
@@ -86,6 +89,7 @@ class PairingGuideActivity : ComponentActivity() {
super.onNewIntent(intent)
setIntent(intent)
settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
toggleOnly = intent.getBooleanExtra(EXTRA_TOGGLE_ONLY, false)
launchPending = true
}
@@ -108,7 +112,7 @@ class PairingGuideActivity : ComponentActivity() {
private fun launchSettings() {
launchPending = false
openSettings(stepFor(this, WirelessAdbPairingService.stage.value))
openSettings(stepFor(SettingsState.read(this), WirelessAdbPairingService.stage.value, toggleOnly))
}
private fun enterPip() {
@@ -121,7 +125,9 @@ class PairingGuideActivity : ComponentActivity() {
val intent = if (step == Step.BUILD_NUMBER) {
Intent(Settings.ACTION_DEVICE_INFO_SETTINGS).putExtra(HIGHLIGHT_KEY, "build_number")
} else {
Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS).putExtra(HIGHLIGHT_KEY, "toggle_adb_wireless")
Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS).apply {
if (step != Step.CHILD_PROCESS) putExtra(HIGHLIGHT_KEY, "toggle_adb_wireless")
}
}.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val display = settingsDisplay
runCatching {
@@ -147,10 +153,10 @@ class PairingGuideActivity : ComponentActivity() {
delay(500)
}
}
val step = stepFor(settingsState, stage)
val step = stepFor(settingsState, stage, toggleOnly)
var previous by remember { mutableStateOf(step) }
LaunchedEffect(step) {
if (previous == Step.BUILD_NUMBER && step == Step.WIRELESS_DEBUGGING) openSettings(step)
if (previous == Step.BUILD_NUMBER && (step == Step.WIRELESS_DEBUGGING || step == Step.CHILD_PROCESS)) openSettings(step)
previous = step
when (step) {
Step.DONE -> { delay(1_500); returnToApp() }
@@ -158,7 +164,7 @@ class PairingGuideActivity : ComponentActivity() {
else -> Unit
}
}
LaunchedEffect(stage) { if (stage == Stage.Idle) finish() }
LaunchedEffect(stage) { if (stage == Stage.Idle && !toggleOnly) finish() }
BackHandler(enabled = !inPip && settingsDisplay == null) { enterPip() }
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center) {
@@ -199,7 +205,7 @@ class PairingGuideActivity : ComponentActivity() {
openSettings(step)
})
SecondaryButton(stringResource(R.string.common_cancel), onClick = {
WirelessAdbPairingService.cancel(this@PairingGuideActivity)
if (!toggleOnly) WirelessAdbPairingService.cancel(this@PairingGuideActivity)
returnToApp()
})
}
@@ -210,6 +216,7 @@ class PairingGuideActivity : ComponentActivity() {
@Composable
private fun instruction(step: Step, stage: Stage): String = when (step) {
Step.BUILD_NUMBER -> stringResource(R.string.pairguide_build_number)
Step.CHILD_PROCESS -> stringResource(R.string.pairguide_child_process)
Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_wireless)
Step.PAIR -> stringResource(R.string.pairguide_pair)
Step.CODE -> (stage as? Stage.CodeNeeded)?.error ?: stringResource(R.string.gate_step3)
@@ -226,6 +233,7 @@ class PairingGuideActivity : ComponentActivity() {
val beat by pulse.animateFloat(0f, 1f, infiniteRepeatable(tween(900, easing = LinearEasing), RepeatMode.Restart), label = "beat")
val label = when (step) {
Step.BUILD_NUMBER -> stringResource(R.string.pairguide_row_build_number)
Step.CHILD_PROCESS -> stringResource(R.string.pairguide_row_child_process)
Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_row_wireless)
Step.PAIR -> stringResource(R.string.pairguide_row_pair)
Step.CODE -> stringResource(R.string.adbpair_enter_code)
@@ -240,7 +248,7 @@ class PairingGuideActivity : ComponentActivity() {
Text(label, style = if (compact) MaterialTheme.typography.labelMedium else MaterialTheme.typography.bodyLarge,
color = colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
when (step) {
Step.WIRELESS_DEBUGGING -> Toggle(on = beat > 0.5f, accent = accent, compact = compact)
Step.WIRELESS_DEBUGGING, Step.CHILD_PROCESS -> Toggle(on = beat > 0.5f, accent = accent, compact = compact)
else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
if (step == Step.BUILD_NUMBER) Text("×7", style = MaterialTheme.typography.labelLarge, color = accent)
Box(contentAlignment = Alignment.Center) {
@@ -267,7 +275,8 @@ class PairingGuideActivity : ComponentActivity() {
@Composable
private fun StepDots(step: Step) {
val accent = LocalPalette.current.signal
val shown = listOf(Step.BUILD_NUMBER, Step.WIRELESS_DEBUGGING, Step.PAIR, Step.CODE)
val shown = if (toggleOnly) listOf(Step.BUILD_NUMBER, Step.CHILD_PROCESS)
else listOf(Step.BUILD_NUMBER, Step.WIRELESS_DEBUGGING, Step.PAIR, Step.CODE)
val at = shown.indexOf(step).takeIf { it >= 0 } ?: shown.size
Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
shown.forEachIndexed { index, _ ->
@@ -278,22 +287,30 @@ class PairingGuideActivity : ComponentActivity() {
}
}
private data class SettingsState(val developerOptions: Boolean, val wirelessDebugging: Boolean) {
private data class SettingsState(
val developerOptions: Boolean,
val wirelessDebugging: Boolean,
val childProcessBlocked: Boolean,
) {
companion object {
fun read(context: Context) = SettingsState(
GlobalSettings.developerOptionsOn(context),
GlobalSettings.wirelessDebuggingOn(context),
PhantomProcessLimit.blocksSteam(PhantomProcessLimit.read(context)),
)
}
}
companion object {
private const val EXTRA_DISPLAY = "settingsDisplay"
private const val EXTRA_TOGGLE_ONLY = "toggleOnly"
private const val HIGHLIGHT_KEY = ":settings:fragment_args_key"
private fun stepFor(context: Context, stage: Stage) = stepFor(SettingsState.read(context), stage)
private fun stepFor(settings: SettingsState, stage: Stage): Step = when (stage) {
private fun stepFor(settings: SettingsState, stage: Stage, toggleOnly: Boolean): Step = if (toggleOnly) when {
!settings.developerOptions -> Step.BUILD_NUMBER
settings.childProcessBlocked -> Step.CHILD_PROCESS
else -> Step.DONE
} else when (stage) {
is Stage.Working -> Step.WORKING
Stage.Done -> Step.DONE
is Stage.Failed -> Step.FAILED
@@ -317,10 +334,11 @@ class PairingGuideActivity : ComponentActivity() {
return mode == AppOpsManager.MODE_ALLOWED
}
fun start(context: Context, settingsDisplay: Int?): Boolean {
fun start(context: Context, settingsDisplay: Int?, toggleOnly: Boolean = false): Boolean {
if (settingsDisplay == null && !canFloat(context)) return false
context.startActivity(Intent(context, PairingGuideActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(EXTRA_TOGGLE_ONLY, toggleOnly)
.apply { if (settingsDisplay != null) putExtra(EXTRA_DISPLAY, settingsDisplay) })
return true
}
File diff suppressed because it is too large. Load diff
@@ -22,6 +22,14 @@ object AgentGuest {
private set
var steamKeyboard by mutableStateOf(false)
private set
var desktopTextField by mutableStateOf(false)
private set
var keyboardRequests by mutableIntStateOf(0)
private set
var keyboardDismissals by mutableIntStateOf(0)
private set
@Volatile private var keyboardRoute = false
@Volatile private var routeDir: File? = null
private const val TAG = "AgentGuest"
private const val POLL_MS = 50L
private val lock = Any()
@@ -35,10 +43,12 @@ object AgentGuest {
observer?.stopWatching()
observer = null
lastFocusKey = null
main.post { steamKeyboard = false }
main.post { steamKeyboard = false; desktopTextField = false }
val dir = dir(context)
dir.deleteRecursively()
dir.mkdirs()
routeDir = dir
writeKeyboardRoute(dir, keyboardRoute)
@Suppress("DEPRECATION")
observer = object : FileObserver(dir.path, MOVED_TO or CLOSE_WRITE) {
override fun onEvent(event: Int, path: String?) {
@@ -48,6 +58,9 @@ object AgentGuest {
}
"focus.json" -> readJson(File(dir, path))?.let(::recordFocus)
"keyboard.json" -> readJson(File(dir, path))?.let { recordKeyboard(this, it) }
"ime.json" -> readJson(File(dir, path))?.let { recordTextField(this, it) }
"keyboard-request.json" -> readJson(File(dir, path))?.let { recordKeyboardRequest(this) }
"keyboard-dismiss.json" -> readJson(File(dir, path))?.let { recordKeyboardDismiss(this) }
}
}
}.also { it.startWatching() }
@@ -58,10 +71,46 @@ object AgentGuest {
synchronized(lock) {
observer?.stopWatching()
observer = null
main.post { steamKeyboard = false }
main.post { steamKeyboard = false; desktopTextField = false }
}
}
fun routeKeyboard(context: Context, bottom: Boolean) {
synchronized(lock) {
if (keyboardRoute == bottom) return
keyboardRoute = bottom
writeKeyboardRoute(routeDir ?: dir(context), bottom)
}
}
private fun writeKeyboardRoute(dir: File, bottom: Boolean) {
val file = File(dir, "keyboard-route")
runCatching {
if (!bottom) file.delete()
else if (dir.isDirectory) {
val temp = File(dir, "keyboard-route.tmp")
temp.writeText("bottom")
if (!temp.renameTo(file)) temp.delete()
}
}.onFailure { Log.w(TAG, "keyboard route not written", it) }
}
private fun recordKeyboardRequest(source: FileObserver) {
synchronized(lock) {
if (source !== observer) return
main.post { keyboardRequests++ }
}
SessionEvents.record("keyboard.requested", emptyMap())
}
private fun recordKeyboardDismiss(source: FileObserver) {
synchronized(lock) {
if (source !== observer) return
main.post { keyboardDismissals++ }
}
SessionEvents.record("keyboard.dismissed", emptyMap())
}
private fun recordKeyboard(source: FileObserver, snapshot: JSONObject) {
val showing = snapshot.optBoolean("steamKeyboard")
synchronized(lock) {
@@ -71,6 +120,15 @@ object AgentGuest {
SessionEvents.record("keyboard.changed", mapOf("steamKeyboard" to showing, "seq" to snapshot.optInt("seq")))
}
private fun recordTextField(source: FileObserver, snapshot: JSONObject) {
val focused = snapshot.optBoolean("textField")
synchronized(lock) {
if (source !== observer) return
main.post { desktopTextField = focused }
}
SessionEvents.record("ime.changed", mapOf("textField" to focused, "seq" to snapshot.optInt("seq")))
}
private fun recordFocus(snapshot: JSONObject) {
val fields = linkedMapOf<String, Any?>(
"focusedApp" to snapshot.opt("focusedApp"),
@@ -23,6 +23,9 @@ class AgentStartActivity : Activity() {
Thread({
try {
AgentBridgeProvider.awaitRecovery()
val until = android.os.SystemClock.elapsedRealtime() + RUNTIME_WAIT_MS
while (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isBusy() && !isFinishing &&
android.os.SystemClock.elapsedRealtime() < until) Thread.sleep(RUNTIME_POLL_MS)
runOnUiThread {
if (!isFinishing) startSession(request)
}
@@ -51,6 +54,11 @@ class AgentStartActivity : Activity() {
}
private fun startSession(request: JSONObject) {
if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isBusy()) {
Log.w(TAG, "the Linux runtime is being installed or changed")
finish()
return
}
try {
AgentAccess.requireStart(this, request)
} catch (e: AgentException) {
@@ -107,5 +115,7 @@ class AgentStartActivity : Activity() {
companion object {
const val EXTRA_REQUEST = "request"
private const val TAG = "AgentStartActivity"
private const val RUNTIME_WAIT_MS = 15 * 60_000L
private const val RUNTIME_POLL_MS = 500L
}
}
@@ -146,5 +146,7 @@ internal class AddonPack(
listOf("version", "xodus-cli", "xodus-service"))
val COMET = AddonPack("comet", BuildConfig.PACK_COMET_SHA256, BuildConfig.PACK_COMET_SIZE,
listOf("version", "comet"))
val BUTLER = AddonPack("butler", BuildConfig.PACK_BUTLER_SHA256, BuildConfig.PACK_BUTLER_SIZE,
listOf("version", "butler", "7z.so", "libc7zip.so"))
}
}
@@ -16,20 +16,83 @@ import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public final class Downloader {
private static final String TAG = "Downloader";
private static final int CONNECT_TIMEOUT_MS = 10_000;
private static final int STALL_TIMEOUT_MS = 15_000;
private static final int HTTP_RANGE_NOT_SATISFIABLE = 416;
private static final java.util.concurrent.ExecutorService CANCEL_EXECUTOR =
java.util.concurrent.Executors.newCachedThreadPool(r -> {
Thread thread = new Thread(r, "download-cancel");
thread.setDaemon(true);
return thread;
});
private Downloader() {}
public static final class Cancellation implements java.util.function.BooleanSupplier {
private final AtomicBoolean cancelled = new AtomicBoolean();
private final AtomicReference<HttpURLConnection> connection = new AtomicReference<>();
private final AtomicReference<InputStream> input = new AtomicReference<>();
private final java.util.function.BooleanSupplier external;
public Cancellation() { this(null); }
public Cancellation(java.util.function.BooleanSupplier external) { this.external = external; }
public void cancel() {
cancelled.set(true);
HttpURLConnection active = connection.get();
if (active != null) disconnectAsync(active);
InputStream activeInput = input.get();
if (activeInput != null) closeAsync(activeInput);
}
private static void disconnectAsync(HttpURLConnection active) {
CANCEL_EXECUTOR.execute(() -> {
try { active.disconnect(); } catch (RuntimeException ignored) { }
});
}
private static void closeAsync(InputStream active) {
CANCEL_EXECUTOR.execute(() -> {
try { active.close(); } catch (IOException ignored) { }
});
}
@Override public boolean getAsBoolean() {
return cancelled.get() || (external != null && external.getAsBoolean());
}
private void attach(HttpURLConnection active) {
connection.set(active);
if (getAsBoolean()) disconnectAsync(active);
}
private void detach(HttpURLConnection active) { connection.compareAndSet(active, null); }
private void attach(InputStream active) {
input.set(active);
if (getAsBoolean()) closeAsync(active);
}
private void detach(InputStream active) { input.compareAndSet(active, null); }
}
public static String downloadString(String url) {
return downloadString(url, null);
}
public static String downloadString(String url, java.util.function.BooleanSupplier cancelled) {
List<String> sources = DownloadSource.INSTANCE.candidates(url);
for (int i = 0; i < sources.size(); i++) {
if (isCancelled(cancelled)) return null;
if (i > 0) Log.i(TAG, "retrying " + url + " via " + sources.get(i));
Fetch fetch = fetch(sources.get(i));
Fetch fetch = fetch(sources.get(i), cancelled);
// A cancelled fetch says nothing about the source, so it must not count as a failure.
if (isCancelled(cancelled)) return null;
if (fetch.body != null) {
DownloadSource.INSTANCE.succeeded(sources.get(i));
return fetch.body;
@@ -53,30 +116,52 @@ public final class Downloader {
/** Verify each candidate before accepting it, so a bad mirror can fall back. */
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
java.util.function.Consumer<Float> progress) {
return downloadFile(url, destination, resume, expectedSha256, null, progress);
}
/** {@code cancelled} is polled while bytes arrive; a cancel stops at once and leaves the partial file for the caller. */
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
java.util.function.BooleanSupplier cancelled,
java.util.function.Consumer<Float> progress) {
if (expectedSha256 != null && !expectedSha256.matches("(?i)[0-9a-f]{64}"))
throw new IllegalArgumentException("Expected SHA-256 must be 64 hex characters");
return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, progress);
return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, cancelled, progress);
}
/** A third-party mirror may only serve bytes that can be checked against a digest from a direct source. */
static List<String> sources(String url, String expectedSha256) {
return expectedSha256 == null ? java.util.Collections.singletonList(url) : DownloadSource.INSTANCE.candidates(url);
}
// Package-private for the local multi-source HTTP test.
static boolean downloadCandidates(String original, List<String> sources, File destination, boolean resume,
String expectedSha256, java.util.function.Consumer<Float> progress) {
return downloadCandidates(original, sources, destination, resume, expectedSha256, null, progress);
}
static boolean downloadCandidates(String original, List<String> sources, File destination, boolean resume,
String expectedSha256, java.util.function.BooleanSupplier cancelled,
java.util.function.Consumer<Float> progress) {
Identity identity = loadIdentity(destination, resume, expectedSha256);
for (int i = 0; i < sources.size(); i++) {
String source = sources.get(i);
if (isCancelled(cancelled)) return false;
if (i > 0) Log.i(TAG, "retrying " + original + " via " + source);
Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, progress);
Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, cancelled, progress);
// A cancel is not a source failure: no other mirror, and no DownloadSource.failed().
if (outcome == Outcome.CANCELLED) return false;
if (outcome == Outcome.DONE) {
if (expectedSha256 != null && !expectedSha256.equalsIgnoreCase(Hashes.sha256(destination))) {
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
if (!discardPartial(destination, identity)) return false;
continue;
if (expectedSha256 != null) {
String actualSha256 = Hashes.sha256(destination);
if (isCancelled(cancelled)) return false;
if (!expectedSha256.equalsIgnoreCase(actualSha256)) {
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
if (!discardPartial(destination, identity)) return false;
continue;
}
}
if (isCancelled(cancelled)) return false;
resumeFile(destination).delete();
DownloadSource.INSTANCE.succeeded(source);
if (progress != null) progress.accept(1f);
@@ -88,7 +173,11 @@ public final class Downloader {
return false;
}
private enum Outcome { DONE, RETRY, FATAL }
private enum Outcome { DONE, RETRY, FATAL, CANCELLED }
private static boolean isCancelled(java.util.function.BooleanSupplier cancelled) {
return cancelled != null && cancelled.getAsBoolean();
}
private static final class Identity {
private String source;
@@ -156,7 +245,9 @@ public final class Downloader {
}
private static Outcome attempt(String url, File destination, boolean resume, Identity identity,
String expectedSha256, java.util.function.Consumer<Float> progress) {
String expectedSha256, java.util.function.BooleanSupplier cancelled,
java.util.function.Consumer<Float> progress) {
if (isCancelled(cancelled)) return Outcome.CANCELLED;
HttpURLConnection connection = null;
long have = resume && destination.isFile() ? destination.length() : 0;
try {
@@ -166,6 +257,7 @@ public final class Downloader {
have = 0;
}
connection = open(url, STALL_TIMEOUT_MS);
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).attach(connection);
if (have > 0) {
connection.setRequestProperty("Range", "bytes=" + have + "-");
connection.setRequestProperty("If-Range", identity.etag);
@@ -174,7 +266,7 @@ public final class Downloader {
if (have > 0 && code == HTTP_RANGE_NOT_SATISFIABLE) {
connection.disconnect();
if (!discardPartial(destination, identity)) return Outcome.RETRY;
return attempt(url, destination, false, identity, expectedSha256, progress);
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
}
if (code / 100 != 2) {
Log.w(TAG, url + " -> HTTP " + code);
@@ -185,13 +277,13 @@ public final class Downloader {
if (appending && !rangeStartsAt(connection.getHeaderField("Content-Range"), have)) {
connection.disconnect();
if (!discardPartial(destination, identity)) return Outcome.RETRY;
return attempt(url, destination, false, identity, expectedSha256, progress);
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
}
String etag = connection.getHeaderField("ETag");
if (have > 0 && appending && (!strongETag(etag) || !etag.equals(identity.etag))) {
connection.disconnect();
if (!discardPartial(destination, identity)) return Outcome.RETRY;
return attempt(url, destination, false, identity, expectedSha256, progress);
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
}
if (!appending && have > 0) {
// If-Range may legitimately return full 200 when representation changed.
@@ -208,26 +300,36 @@ public final class Downloader {
identity.etag = strongETag(etag) ? etag : null;
saveIdentity(destination, identity, expectedSha256);
long written = have;
try (InputStream in = new BufferedInputStream(connection.getInputStream(), 1 << 16);
InputStream input = connection.getInputStream();
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).attach(input);
try (InputStream in = new BufferedInputStream(input, 1 << 16);
OutputStream out = new FileOutputStream(destination, appending)) {
byte[] buffer = new byte[1 << 16];
long lastReport = 0;
for (int read = in.read(buffer); read > 0; read = in.read(buffer)) {
out.write(buffer, 0, read);
written += read;
if (isCancelled(cancelled)) return Outcome.CANCELLED;
if (progress != null && written - lastReport > (1 << 20)) {
lastReport = written;
progress.accept(total > 0 ? written / (float) total : -1f);
}
}
} finally {
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(input);
}
if (isCancelled(cancelled)) return Outcome.CANCELLED;
if (total > 0 && written < total) return Outcome.RETRY;
return Outcome.DONE;
} catch (Exception e) {
if (isCancelled(cancelled)) return Outcome.CANCELLED;
Log.w(TAG, "download " + url, e);
return Outcome.RETRY;
} finally {
if (connection != null) connection.disconnect();
if (connection != null) {
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(connection);
connection.disconnect();
}
}
}
@@ -256,9 +358,15 @@ public final class Downloader {
}
private static Fetch fetch(String url) {
return fetch(url, null);
}
private static Fetch fetch(String url, java.util.function.BooleanSupplier cancelled) {
HttpURLConnection connection = null;
Cancellation token = cancelled instanceof Cancellation ? (Cancellation) cancelled : null;
try {
connection = open(url, STALL_TIMEOUT_MS);
if (token != null) token.attach(connection);
int code = connection.getResponseCode();
if (code / 100 != 2) {
Log.w(TAG, url + " -> HTTP " + code);
@@ -270,10 +378,14 @@ public final class Downloader {
return new Fetch(new String(out.toByteArray(), StandardCharsets.UTF_8), false);
}
} catch (Exception e) {
if (isCancelled(cancelled)) return new Fetch(null, false);
Log.w(TAG, "GET " + url, e);
return new Fetch(null, false);
} finally {
if (connection != null) connection.disconnect();
if (connection != null) {
if (token != null) token.detach(connection);
connection.disconnect();
}
}
}
@@ -161,6 +161,25 @@ object AddedGames {
"appxmanifest.xml" to Regex("<Application\\b[^>]*?\\bExecutable\\s*=\\s*\"([^\"]+)\"", RegexOption.IGNORE_CASE),
)
private val GAME_PARTS = setOf(
"bin", "bin32", "bin64", "binaries", "x64", "x86", "win64", "win32", "windows",
"launcher", "game", "engine", "system", "data", "app",
)
internal fun groupGames(folder: File): List<File>? {
val files = folder.listFiles() ?: return null
if (files.any { it.isFile && it.name.endsWith(".exe", ignoreCase = true) && !skipExe(it.name) }) return null
if (declaredExes(folder).isNotEmpty()) return null
val dirs = files.filter { it.isDirectory && !it.name.startsWith(".") }.sortedBy { it.name.lowercase() }
if (dirs.size < 2 || dirs.any { it.name.lowercase() in GAME_PARTS }) return null
return dirs.takeIf { all -> all.all { rank(it).exes.isNotEmpty() } }
}
private fun expand(folder: File, entries: Set<String>): List<File> =
if (folder.path in entries) listOf(folder) else groupGames(folder) ?: listOf(folder)
private fun entryFolders(context: Context): Set<String> = AddedExes.list(context).map { it.folder }.toSet()
/** The card's Steam libraries: the arm64 client's steamapps and the x86-64 client's own folder beside it. */
internal fun isSteamLibraryFolder(name: String): Boolean =
name.equals("steamapps", ignoreCase = true) || name == com.droiddeck.launcher.session.GameStorage.X64_CARD_DIR
@@ -173,6 +192,7 @@ object AddedGames {
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
)
val removed = SessionPrefs.removedAddedGames(context).toSet()
val entries = entryFolders(context)
for (dir in folders.distinctBy { it.absolutePath }) {
if (!dir.isDirectory) { Log.w(TAG, "$dir is not a folder; skipped"); continue }
val steamInstalls = steamInstallDirs(dir)
@@ -180,7 +200,7 @@ object AddedGames {
if (folder.name.lowercase() in steamInstalls || isSteamLibraryFolder(folder.name)) continue
if (folder.path in removed) continue
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
scanGame(context, folder, out)
for (game in expand(folder, entries)) if (game.path !in removed) scanGame(context, game, out)
}
}
for (entry in AddedExes.list(context)) {
@@ -232,8 +252,9 @@ object AddedGames {
val entries = AddedExes.list(context)
fun owns(f: File) = holds(f) && sameGame(f, currentExe(context, entries, f), exe)
entries.map { File(it.folder) }.filter(::owns).maxByOrNull { canonical(it).length }?.let { return it }
SessionPrefs.removedAddedGames(context).map { File(it) }.filter(::owns).maxByOrNull { canonical(it).length }?.let { return it }
SessionPrefs.removedAddedGames(context).map { File(it) }.filter { owns(it) && groupGames(it) == null }.maxByOrNull { canonical(it).length }?.let { return it }
StoreInstallRoot.gameFolders(context).firstOrNull(::holds)?.let { return it }
val removed = SessionPrefs.removedAddedGames(context)
val dirs = listOfNotNull(
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
GameStorage.effective(context)?.let { File(it.path) },
@@ -242,7 +263,10 @@ object AddedGames {
val base = canonical(dir)
if (!inside(path, base)) continue
val first = path.removePrefix("$base/").substringBefore('/')
File(dir, first).takeIf { it.isDirectory && !isSteamLibraryFolder(first) }?.let { return it }
val top = File(dir, first).takeIf { it.isDirectory && !isSteamLibraryFolder(first) && it.path !in removed } ?: continue
val group = groupGames(top) ?: return top
if (top.path in entries.map { it.folder }) return null
return group.firstOrNull(::holds)
}
return null
}
@@ -295,10 +319,11 @@ object AddedGames {
if (guestPath(app, dir) == null) bindFolder(app, dir)
val removed = SessionPrefs.removedAddedGames(app).toSet()
val listed = listedFolders(app, removed)
val entries = entryFolders(app)
var already = 0
val fresh = ArrayList<String>()
val added = ArrayList<Game>()
for (sub in dir.listFiles { f -> f.isDirectory && (showHidden || !f.name.startsWith(".")) }?.sortedBy { it.name.lowercase() }.orEmpty()) {
for (sub in dir.listFiles { f -> f.isDirectory && (showHidden || !f.name.startsWith(".")) }?.sortedBy { it.name.lowercase() }.orEmpty().flatMap { expand(it, entries) }) {
val path = canonical(sub)
if (listed.any { it == path || inside(path, it) || inside(it, path) }) { already++; continue }
onChecking(sub.name)
@@ -332,6 +357,7 @@ object AddedGames {
private fun listedFolders(context: Context, removed: Set<String>): List<String> {
val out = ArrayList<String>()
val entries = entryFolders(context)
GamesFolderMigration.run(context)
val dirs = listOfNotNull(
GameStorage.effective(context)?.let { File(it.path) },
@@ -341,7 +367,7 @@ object AddedGames {
for (folder in dir.listFiles { f -> f.isDirectory }.orEmpty()) {
if (folder.path in removed || isSteamLibraryFolder(folder.name)) continue
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
out.add(canonical(folder))
expand(folder, entries).filter { it.path !in removed }.forEach { out.add(canonical(it)) }
}
}
AddedExes.list(context).filter { it.folder !in removed }.forEach { out.add(canonical(File(it.folder))) }
@@ -89,7 +89,13 @@ object AutoComponents {
private fun enqueue(context: Context, job: Job) {
if (!queuedKeys.add(job.key)) {
if (job.asked && jobs.removeIf { it.key == job.key && !it.asked }) jobs.add(job)
synchronized(jobs) {
val old = jobs.firstOrNull { it.key == job.key }
if (old != null && ((job.asked && !old.asked) || (job.inSession && !old.inSession)) && jobs.remove(old)) {
jobs.add(Job(old.game ?: job.game, old.component, old.asked || job.asked,
if (job.asked && !old.asked) job.seq else old.seq, old.pics ?: job.pics, old.inSession || job.inSession))
}
}
if (runNow && !draining) drain(context)
return
}
@@ -185,18 +191,19 @@ object AutoComponents {
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return
val wanted = autoPicks(findings, catalog)
val user = WinComponents.selection(context, key).user
val before = WinComponents.selection(context, key).auto
val installed = installedOf(context)
val kept = LinkedHashMap<String, WinComponents.AutoReason>()
val missing = ArrayList<String>()
for ((id, reason) in wanted) {
if (user[id] == false) { kept[id] = reason; continue }
if (id in installed) { kept[id] = reason; continue }
if (id in before) kept[id] = reason
synchronized(waiting) { waiting.getOrPut(id) { ArrayList() }.let { if (it.none { g -> appKey(g) == key }) it.add(game) } }
queueDownload(context, id, asked, inSession)
missing.add(id)
}
if (inSession) Pending.set(context, key, missing)
val before = WinComponents.selection(context, key).auto
if (inSession) Pending.set(context, key, (Pending.ids(context, key).filter { it !in installed && it !in wanted } + missing).distinct())
if (before.keys != kept.keys) {
WinComponents.setAuto(context, key, kept)
Log.i(TAG, "${game.name}: on by itself ${kept.keys.joinToString().ifEmpty { "(none)" }}")
@@ -235,6 +242,16 @@ object AutoComponents {
write(context, games)
}
@Synchronized fun ids(context: Context, key: String): List<String> =
read(context).optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
@Synchronized fun add(context: Context, key: String, ids: List<String>) {
val games = read(context)
val have = games.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
games.put(key, JSONArray((have + ids).distinct()))
write(context, games)
}
@Synchronized fun drop(context: Context, id: String) {
val games = read(context)
for (k in games.keys().asSequence().toList()) {
@@ -317,6 +334,32 @@ object AutoComponents {
fun beforeLaunch(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = false)
fun restoreMissing(context: Context): List<String> {
val selections = WinComponents.selections(context)
if (selections.isEmpty()) return emptyList()
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return emptyList()
val installed = installedOf(context)
val lostFor = selections.mapValues { (_, selection) ->
withParts(selection.effective.filter { WinComponents.validId(it) }, catalog).filter { it !in installed && it in catalog }
}.filterValues { it.isNotEmpty() }
if (lostFor.isEmpty()) return emptyList()
val lost = lostFor.values.flatten().distinct()
Log.i(TAG, "wincomp: reinstalling ${lost.joinToString()}, picked for games but missing from the runtime")
lostFor.forEach { (key, ids) -> Pending.add(context, key, ids) }
lost.forEach { queueDownload(context, it, asked = true, inSession = true) }
return lost
}
private fun withParts(ids: List<String>, catalog: Map<String, WinComponents.Component>): List<String> {
val out = LinkedHashSet<String>()
fun visit(id: String, depth: Int) {
if (depth > 8 || !out.add(id)) return
catalog[id]?.dependencies?.forEach { visit(it, depth + 1) }
}
ids.forEach { visit(it, 0) }
return out.toList()
}
fun refreshLater(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = true)
fun sweep(context: Context, games: List<Library.SteamGame>) {
@@ -274,7 +274,7 @@ object Library {
Spec("duckstation", "DuckStation", "PS1", "/opt/appimages/duckstation.AppImage", listOf("ps1", "psx"), setOf("cue", "chd", "pbp", "iso", "bin", "img", "ecm", "m3u")),
Spec("melonds", "melonDS", "DS", "/opt/appimages/melonds.AppImage", listOf("ds", "nds"), setOf("nds", "dsi"), atPanel = true),
Spec("cemu", "Cemu", "Wii U", "/opt/appimages/cemu.AppImage", listOf("wiiu", "wii u"), setOf("wua", "wud", "wux", "rpx")),
Spec("ppsspp", "PPSSPP", "PSP", "/usr/bin/PPSSPPSDL", listOf("psp"), setOf("iso", "cso", "pbp", "chd")),
Spec("ppsspp", "PPSSPP", "PSP", "/usr/local/bin/PPSSPPSDL", listOf("psp"), setOf("iso", "cso", "pbp", "chd")),
Spec("retroarch", "RetroArch", "many systems", "/usr/bin/retroarch", emptyList(), emptySet()),
)
private fun displayTitle(name: String): String =
@@ -16,6 +16,7 @@ data class GpuInfo(
val modelSource: String = "",
val kgslChipId: String = "",
val platformGpuModel: Int = 0,
val verifiedDevice: Boolean = false,
) {
enum class Family(val label: String) {
A8XX("Adreno 8xx"),
@@ -36,6 +37,7 @@ data class GpuInfo(
get() = when {
family == Family.NOT_ADRENO -> Support.UNSUPPORTED
isA850 -> Support.UNTESTED
verifiedDevice -> Support.TESTED
family == Family.A6XX && model == 650 -> Support.TESTED
family == Family.A8XX -> Support.TESTED
family == Family.A7XX && model >= 725 -> Support.TESTED
@@ -85,9 +87,13 @@ data class GpuInfo(
oneUi8Gen2 = samsung && model == 740,
kgslName = raw.orEmpty(), modelSource = source, kgslChipId = chipId,
platformGpuModel = platformGpuModel,
verifiedDevice = adreno && verifiedOn(model, Build.MODEL),
)
}
internal fun verifiedOn(model: Int, device: String): Boolean =
model == 722 && device.equals("Retroid Pocket Duo", ignoreCase = true)
internal fun threeDigits(text: String): Int = Regex("""(?i)\badreno\s*(?:\(TM\)\s*)?(\d{3})(?!\d)""").find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
internal fun modelFromNames(
@@ -0,0 +1,53 @@
package com.droiddeck.launcher.hud
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Path
/** artwork/droiddeck-mark.svg: the split D with its circular cut-out and the blue orb. */
internal object DroidDeckMark {
private const val VIEW_X = -55.98f
const val VIEW_W = 239.92f
const val VIEW_H = 223.72f
private val body: Path by lazy {
val d = Path().apply {
moveTo(-31.98f, 0f)
lineTo(63.97f, 0f)
cubicTo(125.81f, 0f, 175.93f, 50.08f, 175.93f, 111.86f)
cubicTo(175.93f, 173.64f, 125.81f, 223.72f, 63.97f, 223.72f)
lineTo(-31.98f, 223.72f)
close()
}
val cut = Path().apply {
addCircle(63.98f, 111.86f, 71.81f, Path.Direction.CW)
addRect(56.055f, 0f, 71.885f, 45f, Path.Direction.CW)
addRect(56.055f, 178.72f, 71.885f, 223.72f, Path.Direction.CW)
}
d.op(cut, Path.Op.DIFFERENCE)
d.offset(-VIEW_X, 0f)
d
}
private val scaled = Path()
private val matrix = Matrix()
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
fun widthFor(height: Float): Float = height * VIEW_W / VIEW_H
/** Where the drawn mark starts and ends inside [widthFor]: the artwork has empty space on both sides. */
fun inkLeftFor(height: Float): Float = (-31.98f - VIEW_X) * height / VIEW_H
fun inkRightFor(height: Float): Float = (175.93f - VIEW_X) * height / VIEW_H
fun draw(canvas: Canvas, left: Float, top: Float, height: Float, bodyColor: Int, orbColor: Int) {
val s = height / VIEW_H
matrix.setScale(s, s)
matrix.postTranslate(left, top)
body.transform(matrix, scaled)
paint.color = bodyColor
canvas.drawPath(scaled, paint)
paint.color = orbColor
canvas.drawCircle(left + (63.98f - VIEW_X) * s, top + 111.86f * s, 55.98f * s, paint)
}
}
@@ -0,0 +1,56 @@
package com.droiddeck.launcher.hud
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
/** FusionHUD's settings as one "key=value,…" string (FusionHudView.applyConfig), stored in SessionPrefs. */
internal object FusionHudConfig {
/**
* Bannerlator's Fusion defaults (DeckOverlaySettings), with the FPS graph from the old DroidDeck HUD. The HUD starts
* locked, so like the old HUD it lets touches through until it is unlocked to move it.
*/
val DEFAULTS: Map<String, String> = linkedMapOf(
"hudSize" to "minimal", "hudLocked" to "1", "hudScale" to "100", "hudOpacity" to "80", "hudColor" to "mid",
"hudOutline" to "40", "hudOutlineAccent" to "1",
"showFPS" to "1", "showFPSGraph" to "1", "showCPUUsage" to "1", "showCPULoad" to "1", "showGPULoad" to "1",
"showVram" to "1", "showRAM" to "1", "showPower" to "1", "showTemp" to "1", "showBatteryTemp" to "1",
"showGpuTemp" to "0", "showBattery" to "0", "showLow001" to "1", "fpsDecimal" to "1", "showPerCore" to "1",
"showSwap" to "1", "showNet" to "1", "showResolution" to "1", "showProton" to "1", "showSession" to "1",
"showClock" to "1", "showEngine" to "1", "showRenderer" to "1", "showGpuModel" to "1",
"tempUnit" to "c", "tempBands" to "1", "tempAuto" to "1", "tempRedCpu" to "90", "tempRedGpu" to "90", "tempRedBat" to "48",
)
/** Switches Bannerlator sets together (DeckOverlaySettings twins). */
private val TWINS = mapOf("showCPUUsage" to "showCPULoad", "showTemp" to "showBatteryTemp", "showEngine" to "showRenderer")
fun load(context: Context): MutableMap<String, String> {
val values = LinkedHashMap(DEFAULTS)
val stored = SessionPrefs.fusionHudConfig(context)
if (stored == null) {
values["showFPS"] = flag(SessionPrefs.hudShowFps(context))
values["showFPSGraph"] = flag(SessionPrefs.hudShowGraph(context))
values["hudOpacity"] = SessionPrefs.hudOpacity(context).toString()
} else {
for (entry in KeyValueSet(stored)) if (entry.size == 2 && entry[0] in DEFAULTS) values[entry[0]] = entry[1]
}
return values
}
fun encode(values: Map<String, String>): String = values.entries.joinToString(",") { "${it.key}=${it.value}" }
fun set(context: Context, key: String, value: String): Map<String, String> {
val values = load(context)
if (key !in DEFAULTS) return values
values[key] = value
TWINS[key]?.let { values[it] = value }
SessionPrefs.setFusionHudConfig(context, encode(values))
return values
}
fun reset(context: Context): Map<String, String> {
SessionPrefs.setFusionHudConfig(context, encode(DEFAULTS))
return DEFAULTS
}
private fun flag(on: Boolean) = if (on) "1" else "0"
}
@@ -0,0 +1,236 @@
package com.droiddeck.launcher.hud
import android.content.Context
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.view.Choreographer
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import kotlin.math.roundToInt
/**
* FusionHUD on the session screen, in place of the old text HUD: the view, the frame feed from gamescope
* (MangoHud's frame times) and MangoHud's readings, started with the session's first frame.
*/
class FusionHudHost(context: Context) {
private val context = context.applicationContext
private val handler = Handler(Looper.getMainLooper())
private val feed = GameFrameFeed(File(LinuxRuntime.rootDir(this.context), HudFrames.PATH))
private val readings = MangoReadings(File(this.context.filesDir, "session"), LinuxRuntime.rootDir(this.context))
private var view: FusionHudView? = null
private var parent: ViewGroup? = null
private var running = false
private var hidden = false
private var backgrounded = false
private var polling = false
private var wantX = Float.NaN
private var wantY = Float.NaN
private var engine = ""
private var gpuName = ""
private var protonPid = 0
private var proton = ""
@Volatile private var lastWindow: String? = null
var onPresentingWindowChanged: (() -> Unit)? = null
/** The HUD itself changed a setting: a tap cycles the size, a long press locks it. */
var onConfigChanged: (() -> Unit)? = null
/** Screen point → whether an on-screen control takes a touch there; a locked HUD lets those through. */
var passesTouchAt: ((rawX: Float, rawY: Float) -> Boolean)? = null
private val listener = object : WaylandCompositor.GameListener {
override fun onGameSurface(window: String?, gpuName: String?) {
if (!gpuName.isNullOrBlank()) handler.post { this@FusionHudHost.gpuName = cleanGpuName(gpuName) }
if (window != null && window != lastWindow) {
lastWindow = window
handler.post { onPresentingWindowChanged?.invoke() }
}
}
override fun onGameFrame() {
feed.onCompositorFrame(System.nanoTime())
}
}
private val frameCallback = object : Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) {
if (!running || !polling) return
if (feed.poll(System.nanoTime())) view?.onFrames()
Choreographer.getInstance().postFrameCallback(this)
}
}
private val enabled: Boolean
get() = SessionPrefs.hudEnabled(context) &&
!File(Environment.getExternalStorageDirectory(), "Download/droiddeck-no-hud").exists()
/** Adds the HUD to [root] at [index] (above the game surface, under the session overlay). */
fun attach(root: FrameLayout, index: Int) {
if (view != null) return
val hud = FusionHudView(root.context)
hud.setFrameStats(feed.stats)
hud.setMangoReadings(readings)
hud.setGpuModel(cleanGpuName(GpuInfo.detect().displayName(context)))
hud.onRefresh = Runnable { refreshLabels(hud) }
hud.setOnMovedListener { x, y ->
wantX = x; wantY = y
keepOnScreen(hud)
wantX = hud.x; wantY = hud.y
SessionPrefs.setFusionHudPosition(context, hud.x, hud.y)
}
hud.setOnSizeCycledListener { size -> FusionHudConfig.set(context, "hudSize", size); onConfigChanged?.invoke() }
hud.setOnLockChangedListener { locked ->
FusionHudConfig.set(context, "hudLocked", if (locked) "1" else "0")
onConfigChanged?.invoke()
}
hud.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> if (!hud.isDragging) keepOnScreen(hud) }
hud.passesTouchAt = { x, y -> passesTouchAt?.invoke(x, y) == true }
hud.visibility = View.GONE
val margin = (16 * root.resources.displayMetrics.density).roundToInt()
root.addView(hud, index, FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply {
leftMargin = margin
topMargin = margin
})
SessionPrefs.fusionHudPosition(context)?.let { (x, y) -> wantX = x; wantY = y; hud.post { keepOnScreen(hud) } }
view = hud
parent = root
applyConfig()
}
fun applyConfig() {
view?.applyConfig(FusionHudConfig.encode(FusionHudConfig.load(context)))
}
fun refresh() {
applyConfig()
if (!enabled) stop() else if (!running) start()
}
fun start() {
if (running || !enabled || view == null) return
running = true
WaylandCompositor.setGameListener(listener)
applyShown()
}
fun stop() {
running = false
showing = false
polling = false
Choreographer.getInstance().removeFrameCallback(frameCallback)
WaylandCompositor.clearGameListener(listener)
feed.close()
view?.visibility = View.GONE
}
/** Picture-in-picture and similar: keep running, draw nothing. */
fun setHidden(hide: Boolean) {
hidden = hide
applyShown()
}
/** The session screen is stopped (another app in front): draw nothing and stop reading sensors. */
fun setBackgrounded(stopped: Boolean) {
backgrounded = stopped
applyShown()
}
private fun applyShown() {
if (!running) return
val show = !hidden && !backgrounded
view?.visibility = if (show) View.VISIBLE else View.GONE
showing = show
// Frames are read once per display frame only while the HUD is drawn.
if (show != polling) {
polling = show
if (show) Choreographer.getInstance().postFrameCallback(frameCallback)
else Choreographer.getInstance().removeFrameCallback(frameCallback)
}
}
/** A sensor report (FusionHUD's diagnostics) in Downloads/DroidDeck; null when it can't be written. */
fun exportDiagnostics(): File? = runCatching {
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "DroidDeck")
dir.mkdirs()
val stamp = java.text.SimpleDateFormat("yyyyMMdd-HHmmss", java.util.Locale.US).format(java.util.Date())
val file = File(dir, "HUD-diagnostics-$stamp.txt")
// Its own reader: the HUD's CPU load is the change since its previous sample, which an export must
// not move. Two samples half a second apart, MangoHud's sampling period.
val metrics = HudMetrics(context)
metrics.setMangoReadings(MangoReadings(File(context.filesDir, "session"), LinuxRuntime.rootDir(context)))
metrics.snapshot()
Thread.sleep(500)
val mango = metrics.snapshot()
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, " +
"RAM ${mango.ramUsedText()}/${mango.ramTotalText()}, VRAM ${mango.vramText()}, battery ${mango.battery.percent}% " +
"${mango.battery.watts}W charging=${mango.battery.charging}\n" +
"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")
file
}.getOrNull()
private fun refreshLabels(hud: FusionHudView) {
if (feed.engine.isNotBlank() && !feed.steamFocused) engine = feed.engine
hud.setEngineLabel(engine)
if (gpuName.isNotBlank()) hud.setGpuModel(gpuName)
hud.setResolution(if (feed.outputWidth > 0 && feed.outputHeight > 0) buildString {
append(feed.outputWidth).append('x').append(feed.outputHeight)
if (feed.refreshMilliHz > 0) append(" @ ").append((feed.refreshMilliHz + 499) / 1000).append("Hz")
} else "")
val pid = feed.pid
if (pid > 0 && pid != protonPid) {
protonPid = pid
proton = protonName(pid) ?: proton
}
hud.setWineVersion(proton)
hud.setPresentedFps(presentedFps())
}
private fun presentedFps(): Float {
if (FrameGen.mode(context).engine == FrameGen.ENGINE_OFF) return 0f
val stats = runCatching { WaylandCompositor.nativeFrameGenStats() }.getOrNull() ?: return 0f
return if (stats.size > 3 && stats[3] > 1f) stats[3] else 0f
}
// The HUD is clamped from where the user left it (wantX/wantY, set on a drop or restore), not from where
// it is drawn: a window that shrinks and grows back (picture-in-picture, a fold) must not leave it in the
// corner the small window pushed it to.
private fun keepOnScreen(v: View) {
val p = v.parent as? View ?: return
if (p.width <= 0 || p.height <= 0 || v.width <= 0 || v.height <= 0) return
if (wantX.isNaN()) { wantX = v.x; wantY = v.y }
val maxX = (p.width - v.width).toFloat().coerceAtLeast(0f)
val maxY = (p.height - v.height).toFloat().coerceAtLeast(0f)
val x = wantX.coerceIn(0f, maxX)
val y = wantY.coerceIn(0f, maxY)
if (v.x != x) v.x = x
if (v.y != y) v.y = y
}
companion object {
/** True while the HUD is on screen; DroidDeck keeps sampling VRAM for it (GpuMemComponent). */
@Volatile @JvmStatic var showing = false
private set
/** "Adreno (TM) 750" as the driver names it, "Adreno 750" as DroidDeck does elsewhere. */
internal fun cleanGpuName(name: String): String = name.replace("(TM)", "").replace(Regex("\\s+"), " ").trim()
/** The Proton build of a game process: the first STEAM_COMPAT_TOOL_PATHS entry's folder. */
internal fun protonName(pid: Int): String? = runCatching {
val environ = File("/proc/$pid/environ").readBytes().toString(Charsets.UTF_8).split('\u0000')
val paths = environ.firstOrNull { it.startsWith("STEAM_COMPAT_TOOL_PATHS=") }?.substringAfter('=') ?: return null
paths.split(':').firstOrNull { it.isNotBlank() }?.trimEnd('/')?.substringAfterLast('/')
}.getOrNull()?.takeIf { it.isNotBlank() }
}
}
@@ -0,0 +1,86 @@
/*
* FusionHUD — a lightweight in-game performance HUD for Android / Winlator overlays.
* Copyright (C) The412Banner <https://github.com/The412Banner>
*
* Licensed under the GNU General Public License v3.0 (see LICENSE), with an
* ADDITIONAL attribution requirement under GPL-3.0 §7(b) (see ATTRIBUTION.md):
* any use, fork, or distribution must preserve credit to "The412Banner" and a
* link to https://github.com/The412Banner/FusionHUD in the project documentation
* AND in the in-app credits/about screen.
*
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
*/
package com.droiddeck.launcher.hud
/**
* Size modes for the Fusion HUD (the 4th selectable in-game overlay style). One shared color-coded
* visual language, four amounts of detail — see the approved mockup. The config value is the lower-case
* token stored under the `hudSize` key; the label is the user-facing string.
*/
enum class FusionSize(val token: String, val label: String) {
FULL("full", "Full"),
TILES("tiles", "Tiles"),
PILL("pill", "Pill"),
MINIMAL("minimal", "Minimal"),
MEGA("mega", "Mega");
/** Next size in the tap-cycle: Full → Tiles → Pill → Minimal → Mega → Full. */
fun next(): FusionSize {
val all = values()
return all[(ordinal + 1) % all.size]
}
/**
* The metric toggle chips this size actually renders — the SINGLE source of truth queried by BOTH
* config surfaces ({@code FpsCounterConfigDialog} + in-game {@code XServerDrawer} HudContent) so the
* chip list can't drift from what the view draws. Chip ids are the chip LABELS used in the UI.
* (Hiding a chip is purely UI; buildConfig() still emits every key — strip-invariant.)
*/
fun supportedChips(): Set<String> = when (this) {
MINIMAL -> MINIMAL_CHIPS
PILL -> PILL_CHIPS
FULL, TILES -> STANDARD_CHIPS
MEGA -> MEGA_CHIPS
}
companion object {
fun from(token: String?): FusionSize =
values().firstOrNull { it.token.equals(token, ignoreCase = true) } ?: FULL
// Chip-label ids (must match the labels the config UIs build). "Clock" is a small subtle
// corner readout available in EVERY size, so it's in all sets.
// The API/engine label ("Engine" chip) shows on the FPS row in EVERY size, so it's in all sets.
// "Wrapper" and "DX ver" are Mega-only: the wrapper appears solely below Mega's frametime graph,
// and "DX ver" gates the DX-version suffix on Mega's FPS-row engine label.
val MINIMAL_CHIPS = setOf("FPS", "FPS graph", "0.01% low", "FPS .1", "Engine", "Clock")
val PILL_CHIPS = setOf("FPS", "FPS graph", "GPU", "CPU", "VRAM", "RAM", "Battery", "GPU model", "FPS .1", "Engine", "Clock")
val STANDARD_CHIPS = setOf(
"FPS", "FPS graph", "GPU", "GPU temp", "CPU", "VRAM", "RAM", "Power", "Temp",
"Battery", "GPU model", "Engine", "0.01% low", "FPS .1", "Clock",
)
val MEGA_ONLY = setOf(
"Per-core", "Swap", "Network", "Resolution", "Proton", "Wrapper", "DX ver", "Session",
)
val MEGA_CHIPS = STANDARD_CHIPS + MEGA_ONLY
}
}
/**
* The Wayland HDR state the Fusion HUD shows on its own line, directly under the latency · display-server
* line (the host sets it with [FusionHudView.setHdrState]). [NONE] = no line at all: every session whose
* HDR gate is closed (X11, SDR screens, HDR off) keeps the HUD exactly as it was.
*/
object FusionHdr {
const val NONE = 0
const val ON = 1 // HDR frames on screen with HDR headroom
const val NO_HEADROOM = 2 // HDR frames on screen, but the display gives them no headroom (5 s+)
const val OFF = 3 // the drawer's HDR output switch is off (tone-mapped to SDR)
const val READY = 4 // HDR open for the session, no HDR frames on screen right now
const val TONEMAPPED = 5 // HDR output on, but the frames are shown tone-mapped (frame generation
// on a screen that offers no HDR10 swapchain)
const val NOT_ON_THIS_SCREEN = 6 // HDR open for the session, but the screen the game is on NOW
// reports no HDR10 (the TV was unplugged mid-game). The offer to the
// game cannot be withdrawn once made, so the gate stays open for the
// session — but "ready" would be a lie on a panel that cannot show it.
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,262 @@
package com.droiddeck.launcher.hud
import java.io.File
import kotlin.math.roundToInt
/**
* Frame statistics by MangoHud's rules, so the HUD and Steam's performance overlay agree: MangoHud
* overlay.cpp update_hud_info_with_frametime and hud_elements.cpp fps() / frame_timing(). The FPS is the
* frames counted over a sampling period of at least 500 ms, the frame time next to it is 1000 / FPS, and
* the graph holds the last 200 frame times (zeros until filled) on a fixed 0-50 ms scale, min and max
* taken over those 200. Average and lows are FusionHUD's own readouts.
*/
internal class FrameStats {
private val graph = FloatArray(GRAPH_FRAMES)
private var graphHead = 0
private var lastPresentNs = 0L
private var lastFpsUpdateNs = 0L
private var framesSinceUpdate = 0
private val lowsRing = LongArray(LOWS_FRAMES)
private var lowsHead = 0
private var lowsSize = 0
private var cachedLows = Lows.EMPTY
private var cachedLowsNs = 0L
private var sessionStartNs = 0L
private var sessionFrames = 0L
@Volatile var fps = 0f
private set
/** Completed sampling periods; MangoHud redraws its readouts when one completes. */
@Volatile var fpsUpdates = 0L
private set
/** Frames added so far; the HUD redraws its graph when this moves. */
@Volatile var count = 0L
private set
@Synchronized
fun add(frametimeNs: Long, timeNs: Long) {
if (frametimeNs <= 0L) return
if (lastPresentNs != 0L) {
graph[graphHead] = frametimeNs / 1e6f
graphHead = (graphHead + 1) % GRAPH_FRAMES
}
val elapsed = timeNs - lastFpsUpdateNs
if (elapsed >= FPS_PERIOD_NS) {
fps = (1e9 * framesSinceUpdate / elapsed).toFloat()
framesSinceUpdate = 0
lastFpsUpdateNs = timeNs
fpsUpdates++
}
lastPresentNs = timeNs
framesSinceUpdate++
if (frametimeNs < PAUSE_NS) {
lowsRing[lowsHead] = frametimeNs
lowsHead = (lowsHead + 1) % LOWS_FRAMES
if (lowsSize < LOWS_FRAMES) lowsSize++
if (sessionStartNs == 0L) sessionStartNs = timeNs - frametimeNs
sessionFrames++
}
count++
}
@Synchronized
fun reset() {
graph.fill(0f)
graphHead = 0
lastPresentNs = 0L
lastFpsUpdateNs = 0L
framesSinceUpdate = 0
lowsHead = 0
lowsSize = 0
cachedLows = Lows.EMPTY
cachedLowsNs = 0L
sessionStartNs = 0L
sessionFrames = 0L
fps = 0f
count++
}
/** MangoHud's frame time readout: 1000 / FPS. */
fun frametimeMs(): Float = 1000f / maxOf(fps, 1f)
/** The graph, oldest first, into [out] (GRAPH_FRAMES long). */
@Synchronized
fun graph(out: FloatArray) {
for (i in 0 until GRAPH_FRAMES) out[i] = graph[(graphHead + i) % GRAPH_FRAMES]
}
@Synchronized
fun graphMinMs(): Float = graph.min()
@Synchronized
fun graphMaxMs(): Float = graph.max()
/** Average over the frames this session, from the first frame to [nowNs]'s last frame. */
@Synchronized
fun averageFps(): Float {
if (sessionFrames < 2 || lastPresentNs <= sessionStartNs) return 0f
return (1e9 * sessionFrames / (lastPresentNs - sessionStartNs)).toFloat()
}
@Synchronized
fun sessionSeconds(nowNs: Long): Float = if (sessionStartNs == 0L) 0f else (nowNs - sessionStartNs) / 1e9f
class Lows(val low1Fps: Float, val low01Fps: Float, val low001Fps: Float) {
companion object {
val EMPTY = Lows(0f, 0f, 0f)
}
}
/** FPS at the 99th, 99.9th and 99.99th percentile frame time of the last LOWS_FRAMES frames. */
fun lows(nowNs: Long): Lows {
val copy: LongArray
synchronized(this) {
if (cachedLows !== Lows.EMPTY && nowNs - cachedLowsNs < LOWS_RECOMPUTE_NS) return cachedLows
if (lowsSize < 2) return Lows.EMPTY
copy = LongArray(lowsSize)
val start = (lowsHead - lowsSize + LOWS_FRAMES) % LOWS_FRAMES
for (i in 0 until lowsSize) copy[i] = lowsRing[(start + i) % LOWS_FRAMES]
}
copy.sort()
fun at(p: Double): Float {
val ft = copy[(p * (copy.size - 1)).roundToInt().coerceIn(0, copy.size - 1)]
return if (ft > 0) (1e9 / ft).toFloat() else 0f
}
val result = Lows(at(0.99), at(0.999), at(0.9999))
synchronized(this) {
cachedLows = result
cachedLowsNs = nowNs
}
return result
}
companion object {
const val GRAPH_FRAMES = 200
const val GRAPH_MAX_MS = 50f
const val FPS_PERIOD_NS = 500_000_000L
const val LOWS_FRAMES = 8192
private const val PAUSE_NS = 1_000_000_000L
private const val LOWS_RECOMPUTE_NS = 250_000_000L
}
}
/**
* Feeds [stats] with the frame times gamescope shares (the ones MangoHud shows). Sessions without the
* shared file, or where gamescope stopped sending, fall back to the frames DroidDeck's compositor shows,
* which stop at the screen's refresh rate.
*/
internal class GameFrameFeed(private val file: File, val stats: FrameStats = FrameStats()) {
private var handle = 0L
private var nextOpenNs = 0L
private var lastRingFrameNs = 0L
private var lastInfoNs = 0L
private val frametimes = LongArray(HudFrames.CAPACITY)
private val times = LongArray(HudFrames.CAPACITY)
private val info = IntArray(5)
@Volatile private var fromGamescope = false
private var lastCompositorNs = 0L
@Volatile private var compositorFrames = 0L // written by the compositor thread only
private var seenCompositorFrames = 0L
@Volatile var engine = ""
private set
@Volatile var steamFocused = false
private set
@Volatile var pid = 0
private set
@Volatile var outputWidth = 0
private set
@Volatile var outputHeight = 0
private set
@Volatile var refreshMilliHz = 0
private set
/** Main thread, once per display frame. True when new frames arrived. */
fun poll(nowNs: Long): Boolean {
val compositorAdded = compositorFrames != seenCompositorFrames
seenCompositorFrames = compositorFrames
if (handle == 0L) {
if (nowNs < nextOpenNs) return compositorAdded
nextOpenNs = nowNs + REOPEN_NS
handle = runCatching { HudFrames.nativeOpen(file.path) }.getOrDefault(0L)
if (handle == 0L) return compositorAdded
// Frames already in the file were written before this reader started.
HudFrames.nativePoll(handle, frametimes, times)
}
val n = HudFrames.nativePoll(handle, frametimes, times)
if (n > 0) {
if (!fromGamescope) {
stats.reset()
fromGamescope = true
}
for (i in 0 until n) stats.add(frametimes[i], times[i])
lastRingFrameNs = times[n - 1]
} else if (lastRingFrameNs != 0L && nowNs - lastRingFrameNs > LIVE_NS) {
fromGamescope = false
}
// A new session writes the file again from the start; reopen when gamescope has gone quiet.
if (n <= 0 && nowNs - maxOf(lastRingFrameNs, nextOpenNs - REOPEN_NS) > STALE_NS) close()
if (nowNs - lastInfoNs >= INFO_NS) {
lastInfoNs = nowNs
readInfo()
}
return n > 0 || compositorAdded
}
/** Compositor thread: one frame shown on the panel. */
fun onCompositorFrame(nowNs: Long) {
if (fromGamescope) {
lastCompositorNs = 0L
return
}
val last = lastCompositorNs
lastCompositorNs = nowNs
if (last != 0L) {
stats.add(nowNs - last, nowNs)
compositorFrames++
}
}
fun close() {
if (handle != 0L) HudFrames.nativeClose(handle)
handle = 0L
}
private fun readInfo() {
val name = if (handle != 0L && fromGamescope) HudFrames.nativeInfo(handle, info) else null
if (name == null) {
engine = ""
return
}
pid = info[0]
outputWidth = info[1]
outputHeight = info[2]
refreshMilliHz = info[3]
steamFocused = info[4] != 0
engine = engineLabel(name)
}
companion object {
private const val REOPEN_NS = 2_000_000_000L
private const val LIVE_NS = 2_000_000_000L
private const val STALE_NS = 5_000_000_000L
private const val INFO_NS = 500_000_000L
/** DroidDeck's mangoapp's names for gamescope's engine field (Valve's 20260902.1 build, app/main.cpp
* engine_type_from_str and overlay.h engines); gamescope sends "gamescope" when it knows none. */
fun engineLabel(name: String): String = when (name) {
"DXVK" -> "DXVK"
"vkd3d" -> "VKD3D"
"mesa zink" -> "ZINK"
"Damavand" -> "DAMAVAND"
"Feral3D" -> "Feral3D"
"gamescope", "" -> "GAMESCOPE"
else -> "VULKAN"
}
}
}
@@ -0,0 +1,17 @@
package com.droiddeck.launcher.hud
/** Reader for the frame-times file gamescope patch 0125 writes (hudframes.c). */
internal object HudFrames {
init {
System.loadLibrary("droiddeckwayland")
}
/** Under the Linux root: the session exports /run/droiddeck-hud/frames to gamescope. */
const val PATH = "run/droiddeck-hud/frames"
const val CAPACITY = 1024
@JvmStatic external fun nativeOpen(path: String): Long
@JvmStatic external fun nativeClose(handle: Long)
@JvmStatic external fun nativePoll(handle: Long, frametimes: LongArray, times: LongArray): Int
@JvmStatic external fun nativeInfo(handle: Long, info: IntArray): String?
}
@@ -0,0 +1,265 @@
/*
* FusionHUD — a lightweight in-game performance HUD for Android / Winlator overlays.
* Copyright (C) The412Banner <https://github.com/The412Banner>
*
* Licensed under the GNU General Public License v3.0 (see LICENSE), with an
* ADDITIONAL attribution requirement under GPL-3.0 §7(b) (see ATTRIBUTION.md):
* any use, fork, or distribution must preserve credit to "The412Banner" and a
* link to https://github.com/The412Banner/FusionHUD in the project documentation
* AND in the in-app credits/about screen.
*
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
*/
package com.droiddeck.launcher.hud;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.SystemClock;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
/**
* Shared touch + lock behaviour for every in-game performance HUD (classic FrameRating(+Horizontal),
* GameHub PerfHudView, GameNative PerformanceHudView, and the Fusion HUD). One place so the four
* overlays can't drift:
*
* <ul>
* <li><b>tap</b> → {@link Callbacks#onTap()} (orientation-toggle for the first three; size-cycle for
* Fusion) — a no-op that only re-flashes the lock badge while locked.</li>
* <li><b>drag</b> → moves the host view and, on release, {@link Callbacks#onMoved} to persist the
* position — disabled (frozen) while locked.</li>
* <li><b>long-press</b> → toggles {@code hudLocked}, persisted via {@link Callbacks#onLockChanged}
* and kept in sync with the "Lock in place" menu chip. Works locked or unlocked (so a long-press
* always unlocks); a locked {@code FusionHudView} passes touches on only over on-screen controls.</li>
* </ul>
*
* <p>On every lock/unlock (and on a blocked gesture while locked) a small padlock badge fades in →
* holds → fades out in a corner of the panel. The fade is driven by a self-reposting Runnable that
* invalidates only while visible — nothing runs on the present path, nothing animates at rest.
*
* <p>All methods are Main-thread only (touch + draw), matching the epoll-thread rule: the views feed
* this from {@code onTouchEvent}/{@code dispatchDraw}, never from a present tick.
*/
public class HudLockController {
public interface Callbacks {
/** Unlocked single tap: orientation-toggle (classic/gamehub/gamenative) or size-cycle (fusion). */
void onTap();
/** Drag released (unlocked): persist the new (x, y). */
void onMoved(float x, float y);
/** Lock toggled by long-press: persist {@code hudLocked} + sync the menu chip. */
void onLockChanged(boolean locked);
}
// Fade timing (ms): in → hold → out. Lock/unlock hold ~1.5 s; a blocked-gesture re-flash is shorter.
private static final long FADE_IN_MS = 160;
private static final long HOLD_TOGGLE_MS = 1500;
private static final long HOLD_REFLASH_MS = 750;
private static final long FADE_OUT_MS = 420;
private static final long FRAME_MS = 32;
private final View view;
private final Callbacks cb;
private final GestureDetector detector;
private boolean locked = false;
// Drag state
private float downRawX, downRawY, startX, startY;
private boolean dragging = false;
// Fade state
private long fadeStart = 0;
private long holdMs = HOLD_TOGGLE_MS;
private boolean fadeShowLocked = false;
private final Paint iconFill = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint iconStroke = new Paint(Paint.ANTI_ALIAS_FLAG);
public HudLockController(Context context, View view, Callbacks cb) {
this.view = view;
this.cb = cb;
this.detector = new GestureDetector(context, new Listener());
this.detector.setIsLongpressEnabled(true);
iconFill.setStyle(Paint.Style.FILL);
iconStroke.setStyle(Paint.Style.STROKE);
iconStroke.setStrokeCap(Paint.Cap.ROUND);
iconStroke.setStrokeJoin(Paint.Join.ROUND);
}
/** Set lock state from config (applyConfig) WITHOUT firing the persist callback. */
public void setLocked(boolean locked) { this.locked = locked; }
public boolean isLocked() { return locked; }
public boolean isDragging() { return dragging; }
/** Feed from the host view's onTouchEvent. Always consumes (mirrors the legacy manual handlers). */
public boolean onTouchEvent(MotionEvent event) {
detector.onTouchEvent(event);
int action = event.getActionMasked();
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
if (dragging && !locked) cb.onMoved(view.getX(), view.getY());
dragging = false;
}
return true;
}
private final class Listener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
downRawX = e.getRawX();
downRawY = e.getRawY();
startX = view.getX();
startY = view.getY();
dragging = false;
return true;
}
@Override
public void onLongPress(MotionEvent e) {
// Long-press always toggles — this is the only gesture that still works while locked.
locked = !locked;
cb.onLockChanged(locked);
flash(locked, HOLD_TOGGLE_MS);
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
if (locked) {
flash(true, HOLD_REFLASH_MS); // intentionally locked — remind the user
} else {
cb.onTap();
}
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (locked) {
if (!dragging) flash(true, HOLD_REFLASH_MS);
dragging = true; // mark so the blocked drag doesn't fall through to a tap
return true;
}
view.setX(startX + (e2.getRawX() - downRawX));
view.setY(startY + (e2.getRawY() - downRawY));
dragging = true;
return true;
}
}
// ---- Fade badge -------------------------------------------------------
private void flash(boolean showLocked, long hold) {
fadeShowLocked = showLocked;
holdMs = hold;
fadeStart = SystemClock.elapsedRealtime();
view.removeCallbacks(fadeTick);
view.post(fadeTick);
}
private final Runnable fadeTick = new Runnable() {
@Override
public void run() {
view.invalidate();
if (currentAlpha() > 0f) view.postDelayed(this, FRAME_MS);
}
};
private float currentAlpha() {
if (fadeStart == 0) return 0f;
long e = SystemClock.elapsedRealtime() - fadeStart;
if (e < 0) return 0f;
if (e < FADE_IN_MS) return e / (float) FADE_IN_MS;
long holdEnd = FADE_IN_MS + holdMs;
if (e < holdEnd) return 1f;
long outEnd = holdEnd + FADE_OUT_MS;
if (e < outEnd) return 1f - (e - holdEnd) / (float) FADE_OUT_MS;
return 0f;
}
private static int withAlpha(int color, float a) {
return Color.argb(Math.round(255 * a), Color.red(color), Color.green(color), Color.blue(color));
}
/**
* Draw the padlock badge in the top-right of the panel if a fade is in progress. Call from the
* host's onDraw (plain View) or dispatchDraw (ViewGroup), after the content.
*
* <p>No background box: the glyph is drawn twice — a slightly expanded, thicker semi-transparent
* black "halo" pass for legibility on any game frame, then the white glyph on top — so it reads as
* a floating icon, not an opaque tile.
*/
public void drawBadge(Canvas canvas) {
float a = currentAlpha();
if (a <= 0f) return;
float d = view.getResources().getDisplayMetrics().density;
float size = 15f * d;
float margin = 4f * d;
float right = view.getWidth() - margin;
float left = right - size;
float top = margin;
float cx = (left + right) / 2f;
float bottom = top + size;
float bodyTop = top + size * 0.46f;
float bodyLeft = left + size * 0.14f;
float bodyRight = right - size * 0.14f;
float r = size * 0.2f;
float shackleTop = top + size * 0.08f;
// Pass 1: dark halo (expanded body, thicker shackle) for contrast; Pass 2: white glyph.
drawLock(canvas, cx, bodyTop, bodyLeft, bodyRight, bottom, r, shackleTop, d,
Color.argb(Math.round(150 * a), 0, 0, 0), 3.0f * d, 0.9f * d, false);
drawLock(canvas, cx, bodyTop, bodyLeft, bodyRight, bottom, r, shackleTop, d,
withAlpha(0xFFFFFFFF, a), 1.7f * d, 0f, true);
}
/** One padlock pass. {@code halo} inflates the body/shackle in dark; the white pass punches the keyhole. */
private void drawLock(Canvas canvas, float cx, float bodyTop, float bodyLeft, float bodyRight,
float bottom, float r, float shackleTop, float d,
int color, float strokeW, float expand, boolean punchKeyhole) {
iconFill.setColor(color);
iconStroke.setColor(color);
iconStroke.setStrokeWidth(strokeW);
// Body
canvas.drawRoundRect(bodyLeft - expand, bodyTop - expand, bodyRight + expand, bottom + expand,
2.4f * d, 2.4f * d, iconFill);
if (punchKeyhole) {
int prev = iconFill.getColor();
iconFill.setColor(Color.argb(Color.alpha(color), 0, 0, 0));
canvas.drawCircle(cx, (bodyTop + bottom) / 2f, 1.6f * d, iconFill);
iconFill.setColor(prev);
}
RectF arc = new RectF(cx - r, shackleTop, cx + r, shackleTop + 2f * r);
if (fadeShowLocked) {
// Closed: both legs run straight down into the body.
Path p = new Path();
p.addArc(arc, 180f, 180f);
p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop);
p.moveTo(cx + r, shackleTop + r); p.lineTo(cx + r, bodyTop);
canvas.drawPath(p, iconStroke);
} else {
// Open, clearly to the LEFT: the RIGHT leg stays seated in the body; the arc + LEFT leg
// hinge up-and-left off the right attachment so the left leg lifts well clear of the body.
canvas.drawLine(cx + r, shackleTop + r, cx + r, bodyTop, iconStroke); // fixed right leg
Path p = new Path();
p.addArc(arc, 180f, 180f);
p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop); // full-length left leg
canvas.save();
canvas.rotate(-42f, cx + r, shackleTop + r);
canvas.drawPath(p, iconStroke);
canvas.restore();
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,132 @@
/*
* FusionHUD — a lightweight in-game performance HUD for Android / Winlator overlays.
* Copyright (C) The412Banner <https://github.com/The412Banner>
*
* Licensed under the GNU General Public License v3.0 (see LICENSE), with an
* ADDITIONAL attribution requirement under GPL-3.0 §7(b) (see ATTRIBUTION.md):
* any use, fork, or distribution must preserve credit to "The412Banner" and a
* link to https://github.com/The412Banner/FusionHUD in the project documentation
* AND in the in-app credits/about screen.
*
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
*/
package com.droiddeck.launcher.hud;
import androidx.annotation.NonNull;
import java.util.Iterator;
public class KeyValueSet implements Iterable<String[]> {
private String data = "";
// Default constructor for an empty KeyValueSet
public KeyValueSet() {
this.data = "";
}
// Constructor to initialize with a string representation of key-value pairs
public KeyValueSet(String data) {
this.data = data != null && !data.isEmpty() ? data : "";
}
// Helper method to find the start and end indices of a key in the data string
private int[] indexOfKey(String key) {
int start = 0;
int end = data.indexOf(",");
if (end == -1) end = data.length();
while (start < end) {
int index = data.indexOf("=", start);
String currKey = data.substring(start, index);
if (currKey.equals(key)) return new int[]{start, end};
start = end + 1;
end = data.indexOf(",", start);
if (end == -1) end = data.length();
}
return null;
}
// Method to get the value associated with a key, or an empty string if the key is not present
public String get(String key) {
for (String[] keyValue : this) if (keyValue[0].equals(key)) return keyValue[1];
return "";
}
// Method to get the value associated with a key, or a fallback value if the key is not present
public String get(String key, String fallback) {
for (String[] keyValue : this) if (keyValue[0].equals(key)) return keyValue[1];
return fallback;
}
// Method to get a boolean value associated with a key, or a fallback value if the key is not present
public boolean getBoolean(String key, boolean fallback) {
String value = get(key);
if (value.isEmpty()) return fallback;
return value.equals("1") || value.equals("t") || value.equalsIgnoreCase("true");
}
// Method to get a float value associated with a key, or a fallback value if the key is not present
public float getFloat(String key, float fallback) {
String value = get(key);
try {
if (!value.isEmpty()) return Float.parseFloat(value);
} catch (NumberFormatException e) {
// Ignore exception and return fallback
}
return fallback;
}
// Method to set a value for a key in the key-value data
public void put(String key, Object value) {
int[] range = indexOfKey(key);
if (range != null) {
data = data.substring(0, range[0]) + key + "=" + value + data.substring(range[1]);
} else {
data = (!data.isEmpty() ? data + "," : "") + key + "=" + value;
}
}
// Method to set a float value for a key in the key-value data
public void put(String key, float value) {
put(key, String.valueOf(value));
}
// Iterator implementation for key-value pairs in the format [key, value]
@NonNull
@Override
public Iterator<String[]> iterator() {
final int[] start = {0};
final int[] end = {data.indexOf(",")};
// A single-item config (no comma) gives indexOf == -1, making hasNext() (start < end)
// immediately false so the sole pair was never iterated (get() then returned the
// fallback). Guard it exactly as next() already does. An empty string still yields
// end == 0 → no iteration, which is correct.
if (end[0] == -1) end[0] = data.length();
final String[] item = new String[2];
return new Iterator<String[]>() {
@Override
public boolean hasNext() {
return start[0] < end[0];
}
@Override
public String[] next() {
int index = data.indexOf("=", start[0]);
item[0] = data.substring(start[0], index);
item[1] = data.substring(index + 1, end[0]);
start[0] = end[0] + 1;
end[0] = data.indexOf(",", start[0]);
if (end[0] == -1) end[0] = data.length();
return item;
}
};
}
@NonNull
@Override
public String toString() {
return data;
}
}
@@ -0,0 +1,157 @@
package com.droiddeck.launcher.hud
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
/**
* The readings Steam's performance overlay shows in a DroidDeck session (Valve's mangohud 20260902.1,
* tools/mangoapp), taken from the files the session hands it and computed the same way, so the two
* overlays agree. Sources and formulas follow that build: cpu.cpp calculateCPUData, deckard_temp.cpp,
* msm.cpp getQcomGpuInfo, memory.cpp update_meminfo and battery.cpp getPercent / getPower.
*/
internal class MangoReadings(private val sessionDir: File, private val rootDir: File) {
class Cpu(val percent: Int, val perCore: IntArray)
class Memory(val usedBytes: Long, val totalBytes: Long, val swapUsedBytes: Long, val swapTotalBytes: Long)
class Battery(val percent: Int?, val watts: Float, val charging: Boolean)
private val cpuTimes = HashMap<String, LongArray>()
private val cpuPercents = HashMap<String, Int>()
/** Total and per-core load from the session's /proc/stat (DroidDeck's stand-in when the app can't read it). */
@JvmOverloads
fun cpu(stat: File = statFile()): Cpu? {
val lines = runCatching { stat.readLines() }.getOrNull() ?: return null
var total: Int? = null
val cores = ArrayList<Int>()
for (line in lines) {
if (!line.startsWith("cpu")) break
val parts = line.split(WHITESPACE)
if (parts.size < 11) continue
val values = LongArray(10) { parts[it + 1].toLongOrNull() ?: 0L }
val percent = cpuPercent(parts[0], values)
if (parts[0] == "cpu") total = percent else cores.add(percent)
}
return total?.let { Cpu(it, cores.toIntArray()) }
}
private fun statFile(): File =
File(sessionDir, "proc-stat").takeIf { !File("/proc/stat").canRead() && it.isFile } ?: File("/proc/stat")
private fun cpuPercent(key: String, v: LongArray): Int {
// user nice system idle iowait irq softirq steal guest guest_nice; guest time is already in user.
val user = v[0] - v[8]
val nice = v[1] - v[9]
val systemAll = v[2] + v[5] + v[6]
val idleAll = v[3] + v[4]
val virt = v[8] + v[9]
val totalTime = user + nice + systemAll + idleAll + v[7] + virt
val now = longArrayOf(user, nice, systemAll, v[7], virt, totalTime)
val last = cpuTimes.put(key, now) ?: LongArray(6)
fun period(i: Int) = if (now[i] > last[i]) now[i] - last[i] else 0L
val totalPeriod = period(5).toFloat()
if (totalPeriod == 0f) return cpuPercents[key] ?: 0
val busy = period(1) * 100f / totalPeriod + period(0) * 100f / totalPeriod +
period(2) * 100f / totalPeriod + (period(3) + period(4)) * 100f / totalPeriod
return busy.coerceIn(0f, 100f).toInt().also { cpuPercents[key] = it }
}
/** Average of the zones the session types cpuN-thermal, truncated. */
fun cpuTempC(): Int? {
var sum = 0f
var count = 0
for (zone in LinuxRuntime.cpuTempZones()) {
val milli = readLong(File(zone, "temp")) ?: continue
sum += milli / 1000f
count++
}
return if (count == 0) null else (sum / count).toInt()
}
fun gpuPercent(): Int? {
val feed = fresh(File(sessionDir, "sys/kgsl-3d0/perf_now"))
val source = feed ?: LinuxRuntime.gpuLoadSource()?.let(::File) ?: return null
return leadingNumber(source)?.toInt()?.coerceIn(0, 100)
}
fun gpuClockMhz(): Int? {
val feed = fresh(File(sessionDir, "sys/kgsl-3d0/cur_freq"))
val source = feed ?: listOf("$KGSL/devfreq/cur_freq", "$KGSL/gpuclk").map(::File).firstOrNull { it.canRead() } ?: return null
val hz = leadingNumber(source) ?: return null
return (hz / 1_000_000.0).toInt().takeIf { it > 0 }
}
fun gpuTempC(): Int? {
val milli = LinuxRuntime.gpuTempSource()?.let { readLong(File(it)) } ?: return null
return (milli / 1000.0).toInt()
}
/** MemTotal - MemAvailable and SwapTotal - SwapFree from /proc/meminfo. */
fun memory(): Memory? {
val kb = HashMap<String, Long>()
runCatching {
File("/proc/meminfo").forEachLine { line ->
val colon = line.indexOf(':')
if (colon > 0) line.substring(colon + 1).trim().split(WHITESPACE).firstOrNull()?.toLongOrNull()
?.let { kb[line.substring(0, colon)] = it }
}
}
val total = kb["MemTotal"] ?: return null
val available = kb["MemAvailable"] ?: return null
val swapTotal = kb["SwapTotal"] ?: 0L
val swapFree = kb["SwapFree"] ?: 0L
return Memory((total - available) * 1024, total * 1024, (swapTotal - swapFree) * 1024, swapTotal * 1024)
}
/** The KGSL total DroidDeck shares with the session (GpuMemComponent). */
fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)
/** BAT* under the session's power_supply (BatteryComponent): no watts while charging, full or unknown. */
fun battery(): Battery? {
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }
if (dirs.isNullOrEmpty()) return null
var chargeNow = 0f
var chargeFull = 0f
var watts = 0f
var charging = false
for (dir in dirs) {
val status = runCatching { File(dir, "status").readLines().firstOrNull() }.getOrNull()
if (status == "Charging" || status == "Unknown" || status == "Full") charging = true
val now = File(dir, "charge_now").takeIf { it.exists() } ?: File(dir, "energy_now")
val full = File(dir, "charge_full").takeIf { it.exists() } ?: File(dir, "energy_full")
if (now.exists()) {
chargeNow += (readFloat(now) ?: 0f) / 1_000_000f
chargeFull += (readFloat(full) ?: 0f) / 1_000_000f
} else {
chargeNow += (readFloat(File(dir, "capacity")) ?: 0f) / 100f
chargeFull = dirs.size.toFloat()
}
if (!charging) {
val power = File(dir, "power_now")
watts += if (power.exists()) kotlin.math.abs(readFloat(power) ?: 0f) / 1_000_000f
else kotlin.math.abs((readFloat(File(dir, "current_now")) ?: 0f) * (readFloat(File(dir, "voltage_now")) ?: 0f)) / 1e12f
}
}
val percent = if (chargeFull > 0f) Math.round(chargeNow / chargeFull * 100f) else null
return Battery(percent, if (charging) 0f else watts, charging)
}
private fun fresh(file: File, maxAgeMs: Long = FEED_FRESH_MS): File? =
file.takeIf { it.isFile && System.currentTimeMillis() - it.lastModified() < maxAgeMs }
companion object {
private const val KGSL = "/sys/class/kgsl/kgsl-3d0"
const val VRAM_FILE = "run/droiddeck-hud/gpu-mem"
private const val FEED_FRESH_MS = 10_000L
private const val VRAM_FRESH_MS = 15_000L
private val WHITESPACE = Regex("\\s+")
private fun readLong(file: File): Long? = runCatching { file.readText().trim().toLong() }.getOrNull()
private fun readFloat(file: File): Float? = runCatching { file.readLines().first().trim().toFloat() }.getOrNull()
/** std::stod on the first line: the leading number, "6 %" -> 6. */
fun leadingNumber(file: File): Double? = runCatching {
Regex("^\\s*-?\\d+(\\.\\d+)?").find(file.readLines().first())?.value?.trim()?.toDouble()
}.getOrNull()
}
}
@@ -0,0 +1,118 @@
package com.droiddeck.launcher.input
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.os.Build
import android.view.Gravity
import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.View
import android.view.WindowInsets
import android.widget.FrameLayout
import com.droiddeck.launcher.R
@SuppressLint("ViewConstructor")
class DesktopKeyboardButton(context: Context, private val onTap: () -> Unit) : View(context) {
private val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = dp(1.5f) }
private val box = RectF()
private var idleFill = 0
private var idleStroke = 0
private var heldStroke = 0
private var pressed = false
init {
contentDescription = context.getString(R.string.second_show_keyboard)
isClickable = true
visibility = GONE
layoutParams = FrameLayout.LayoutParams(dp(SIZE).toInt(), dp(SIZE).toInt(), Gravity.BOTTOM or Gravity.START)
place(0, 0)
applyColors()
}
private fun dp(value: Float) = value * resources.displayMetrics.density
fun applyColors() {
val settings = ControllerPrefs.read(context)
val tint = settings.tint
val alpha = settings.opacity / 100f
fun light(a: Int, f: Float) = Color.argb(
(a * alpha).toInt(),
(Color.red(tint) + (255 - Color.red(tint)) * f).toInt(),
(Color.green(tint) + (255 - Color.green(tint)) * f).toInt(),
(Color.blue(tint) + (255 - Color.blue(tint)) * f).toInt(),
)
idleFill = Color.argb(190, (Color.red(tint) * 0.12f).toInt(), (Color.green(tint) * 0.12f).toInt(), (Color.blue(tint) * 0.12f).toInt())
idleStroke = light(150, 0.25f)
heldStroke = light(230, 0.7f)
invalidate()
}
private fun place(left: Int, bottom: Int) {
val params = layoutParams as FrameLayout.LayoutParams
val marginStart = left + (dp(CENTER_X) - dp(SIZE) / 2f).toInt()
val marginBottom = bottom + (dp(CENTER_Y) - dp(SIZE) / 2f).toInt()
if (params.leftMargin == marginStart && params.bottomMargin == marginBottom) return
params.leftMargin = marginStart
params.bottomMargin = marginBottom
layoutParams = params
}
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
val cutout = if (Build.VERSION.SDK_INT >= 28) insets.displayCutout else null
place(cutout?.safeInsetLeft ?: 0, cutout?.safeInsetBottom ?: 0)
return super.onApplyWindowInsets(insets)
}
override fun onDraw(canvas: Canvas) {
val x = width / 2f
val y = height / 2f
fill.color = idleFill
canvas.drawCircle(x, y, dp(18f), fill)
stroke.color = if (pressed) heldStroke else idleStroke
canvas.drawCircle(x, y, dp(18f), stroke)
box.set(x - dp(10f), y - dp(7f), x + dp(10f), y + dp(7f))
canvas.drawRoundRect(box, dp(2f), dp(2f), stroke)
for (row in 0..1) for (col in 0..2) {
val kx = x + dp(-6f + col * 5f)
val ky = y + dp(-3f + row * 4f)
canvas.drawLine(kx, ky, kx + dp(2f), ky, stroke)
}
canvas.drawLine(x - dp(5f), y + dp(4f), x + dp(5f), y + dp(4f), stroke)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> { pressed = true; invalidate() }
MotionEvent.ACTION_UP -> {
val inside = event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()
pressed = false
invalidate()
if (inside) {
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
performClick()
}
}
MotionEvent.ACTION_CANCEL -> { pressed = false; invalidate() }
}
return true
}
override fun performClick(): Boolean {
super.performClick()
onTap()
return true
}
private companion object {
const val SIZE = 52f
const val CENTER_X = 90f
const val CENTER_Y = 34f
}
}
@@ -8,52 +8,125 @@ import kotlin.math.abs
class DirectTouchHold(
private val slopPx: Float,
private val listener: PointerGestures.Listener,
private val cancelTouch: () -> Unit,
private val touch: Touch,
) {
interface Touch {
fun down(pointerId: Int, x: Float, y: Float)
fun move(pointerId: Int, x: Float, y: Float)
fun up(pointerId: Int, x: Float, y: Float)
fun cancel()
}
private val handler = Handler(Looper.getMainLooper())
private var x = 0f
private var y = 0f
private var consumed = false
private var pressed = false
private var downX = 0f
private var downY = 0f
private var downId = 0
private var delayMs = 0L
private var holdBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK
private var forwarded = false
private var held = false
private var pressing = false
private var upX = 0f
private var upY = 0f
private var liftId = 0
private var liftPending = false
private val lift = Runnable {
liftPending = false
if (forwarded) {
touch.up(liftId, upX, upY)
forwarded = false
}
}
private val release = Runnable {
if (pressed) listener.onButton(PointerGestures.BTN_RIGHT, false, x, y)
pressed = false
if (pressing) listener.onButton(PointerGestures.BTN_RIGHT, false, downX, downY)
pressing = false
}
private val hold = Runnable {
cancelTouch()
consumed = true
held = true
listener.onLongPress()
listener.onButton(PointerGestures.BTN_RIGHT, true, x, y)
pressed = true
handler.postDelayed(release, 50L)
listener.onButton(PointerGestures.BTN_RIGHT, true, downX, downY)
pressing = true
if (holdBehavior != TouchGestureConfig.MOUSE_BEHAVIOR_HOLD) handler.postDelayed(release, 50L)
}
fun configure(config: TouchGestureConfig) {
cancel()
delayMs = if (config.longPressEnabled) config.longPressDelay.toLong().coerceAtLeast(1L) else 0L
delayMs = config.longPressDelay.toLong().coerceAtLeast(1L)
holdBehavior = config.directHoldBehavior
}
fun cancel() {
handler.removeCallbacks(hold)
handler.removeCallbacks(release)
handler.removeCallbacks(lift)
liftPending = false
release.run()
consumed = false
if (forwarded) touch.cancel()
forwarded = false
held = false
}
fun onTouch(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
if (liftPending) {
handler.removeCallbacks(lift)
lift.run()
}
cancel()
downX = event.x
downY = event.y
downId = event.getPointerId(0)
if (holdBehavior == TouchGestureConfig.MOUSE_BEHAVIOR_NONE) forwardDown()
else handler.postDelayed(hold, delayMs)
return true
}
if (held) {
when (event.actionMasked) {
MotionEvent.ACTION_UP -> { release.run(); held = false }
MotionEvent.ACTION_CANCEL -> cancel()
}
return true
}
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
cancel()
x = event.x; y = event.y
if (delayMs > 0L) handler.postDelayed(hold, delayMs)
MotionEvent.ACTION_POINTER_DOWN -> {
handler.removeCallbacks(hold)
if (!forwarded) forwardDown()
val index = event.actionIndex
touch.down(event.getPointerId(index), event.getX(index), event.getY(index))
}
MotionEvent.ACTION_MOVE -> {
if (!forwarded && (event.pointerCount > 1 ||
abs(event.x - downX) > slopPx || abs(event.y - downY) > slopPx)) {
handler.removeCallbacks(hold)
forwardDown()
}
if (forwarded) for (index in 0 until event.pointerCount)
touch.move(event.getPointerId(index), event.getX(index), event.getY(index))
}
MotionEvent.ACTION_POINTER_UP -> {
val index = event.actionIndex
touch.up(event.getPointerId(index), event.getX(index), event.getY(index))
}
MotionEvent.ACTION_UP -> {
handler.removeCallbacks(hold)
if (!forwarded) forwardDown()
upX = event.x
upY = event.y
liftId = event.getPointerId(event.actionIndex)
liftPending = true
handler.postDelayed(lift, LIFT_MS)
}
MotionEvent.ACTION_MOVE -> if (event.pointerCount > 1 ||
abs(event.x - x) > slopPx || abs(event.y - y) > slopPx) handler.removeCallbacks(hold)
MotionEvent.ACTION_POINTER_DOWN, MotionEvent.ACTION_POINTER_UP,
MotionEvent.ACTION_UP -> handler.removeCallbacks(hold)
MotionEvent.ACTION_CANCEL -> cancel()
}
return consumed
return true
}
private fun forwardDown() {
touch.down(downId, downX, downY)
forwarded = true
}
private companion object {
const val LIFT_MS = 50L
}
}
@@ -0,0 +1,40 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.hardware.display.DisplayManager
import android.os.Build
import android.view.Display
import com.droiddeck.launcher.session.SessionPrefs
object DualScreen {
const val MODE_AUTO = "auto"
const val MODE_ON = "on"
const val MODE_OFF = "off"
val modes = listOf(MODE_AUTO, MODE_ON, MODE_OFF)
private const val TYPE_INTERNAL = 1
private val knownModels = setOf("retroid pocket duo", "ayn thor")
fun builtInDisplay(displayManager: DisplayManager, primaryDisplayId: Int): Display? =
displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION).firstOrNull {
it.isValid && it.displayId != primaryDisplayId && (it.flags and Display.FLAG_PRESENTATION) != 0 &&
isBuiltIn(displayType(it), Build.MODEL)
}
fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int): Display? =
when (SessionPrefs.dualScreenMode(context)) {
MODE_OFF -> null
MODE_ON -> builtInDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
else -> builtInDisplay(displayManager, primaryDisplayId)
}
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
}
internal fun isBuiltIn(type: Int?, model: String): Boolean =
if (type != null) type == TYPE_INTERNAL else model.trim().lowercase() in knownModels
private fun displayType(display: Display): Int? =
runCatching { Display::class.java.getMethod("getType").invoke(display) as Int }.getOrNull()
}
@@ -14,6 +14,7 @@ public class FakeInputWriter {
public static final short EV_SYN = 0x00;
public static final short EV_KEY = 0x01;
public static final short EV_REL = 0x02;
public static final short EV_ABS = 0x03;
public static final short EV_MSC = 0x04;
@@ -52,7 +53,8 @@ public class FakeInputWriter {
private static final int EVENT_SIZE = 24;
static final int MAX_EVENTS_PER_UPDATE = 32;
private static final int BUFFER_SIZE = EVENT_SIZE * MAX_EVENTS_PER_UPDATE;
private static final int MAX_FAKE_INPUT_SLOTS = 4;
private static final int MAX_FAKE_INPUT_SLOTS = 5;
public static final int MOUSE_SLOT = 4;
private static final int RING_CAPACITY_EVENTS = 4096;
private static final int RING_HEADER_SIZE = 64;
@@ -88,6 +90,17 @@ public class FakeInputWriter {
public static final int PAD_TYPE_XBOX = 2;
public static final int PAD_TYPE_DS4 = 3;
public static final int PAD_TYPE_DUALSENSE = 4;
public static final int PAD_TYPE_MOUSE = 5;
public static final short REL_X = 0x00;
public static final short REL_Y = 0x01;
public static final short REL_HWHEEL = 0x06;
public static final short REL_WHEEL = 0x08;
public static final short REL_WHEEL_HI_RES = 0x0b;
public static final short REL_HWHEEL_HI_RES = 0x0c;
public static final short MOUSE_BTN_LEFT = 0x110;
public static final short MOUSE_BTN_RIGHT = 0x111;
public static final short MOUSE_BTN_MIDDLE = 0x112;
private static volatile int padType = -1;
private static volatile boolean tritonConnected = false;
private static final int TRITON_OFFSET = RING_SIZE + 64;
@@ -136,6 +149,8 @@ public class FakeInputWriter {
private int prevThumbLX, prevThumbLY, prevThumbRX, prevThumbRY;
private int prevTriggerL, prevTriggerR;
private int prevHatX, prevHatY;
private final boolean[] prevMouseButtons = new boolean[3];
private float pendingMouseX, pendingMouseY;
private boolean hasChanges = false;
private boolean pendingFullResend = false;
private boolean forceResend = false;
@@ -201,7 +216,7 @@ public class FakeInputWriter {
return FakeInputRingPaths.ringFile(fakeInputDir, slot);
}
private static void initializeRingHeader(ByteBuffer data) {
private static void initializeRingHeader(int slot, ByteBuffer data) {
data.order(ByteOrder.LITTLE_ENDIAN);
data.putInt(RING_MAGIC_OFFSET, RING_MAGIC);
data.putInt(RING_VERSION_OFFSET, RING_VERSION);
@@ -221,7 +236,7 @@ public class FakeInputWriter {
data.putShort(IMU_ACCEL_OFFSET + (i * 2), (short) 0);
}
data.putInt(DECK_CONTROLS_OFFSET, 0);
int type = padType;
int type = slot == MOUSE_SLOT ? PAD_TYPE_MOUSE : padType;
data.putInt(PAD_TYPE_OFFSET, type >= 0 ? PAD_TYPE_SET | type : 0);
data.putInt(LATENCY_OFFSET, latency);
data.putInt(TRITON_OFFSET, TRITON_MAGIC);
@@ -312,7 +327,7 @@ public class FakeInputWriter {
raf.setLength(RING_FILE_SIZE);
channel = raf.getChannel();
ByteBuffer data = channel.map(FileChannel.MapMode.READ_WRITE, 0, RING_FILE_SIZE);
initializeRingHeader(data);
initializeRingHeader(slot, data);
RingSlot ringSlot = new RingSlot();
ringSlot.data = data;
@@ -745,6 +760,14 @@ public class FakeInputWriter {
prevHatY = 0;
writeEvent(EV_ABS, ABS_HAT0Y, 0);
}
for (int i = 0; i < prevMouseButtons.length; i++) {
if (prevMouseButtons[i]) {
prevMouseButtons[i] = false;
writeEvent(EV_KEY, (short) (MOUSE_BTN_LEFT + i), 0);
}
}
pendingMouseX = 0;
pendingMouseY = 0;
if (hasChanges) {
writeEvent(EV_SYN, SYN_REPORT, 0);
@@ -874,4 +897,64 @@ public class FakeInputWriter {
public boolean isOpen() {
return isOpen;
}
public synchronized void writeMouseDelta(float dx, float dy) {
if (!isOpen && !open())
return;
pendingMouseX += dx;
pendingMouseY += dy;
int x = (int) Math.floor(pendingMouseX);
int y = (int) Math.floor(pendingMouseY);
if (x == 0 && y == 0)
return;
pendingMouseX -= x;
pendingMouseY -= y;
buffer.clear();
hasChanges = false;
if (x != 0) writeEvent(EV_REL, REL_X, x);
if (y != 0) writeEvent(EV_REL, REL_Y, y);
writeEvent(EV_SYN, SYN_REPORT, 0);
buffer.flip();
if (!flushBuffer())
Log.e(TAG, "Mouse delta write error: fake input mmap ring unavailable");
}
public synchronized void writeMouseButton(short code, boolean pressed) {
if (code < MOUSE_BTN_LEFT || code > MOUSE_BTN_MIDDLE)
return;
int idx = code - MOUSE_BTN_LEFT;
if (!isOpen && !open())
return;
if (prevMouseButtons[idx] == pressed)
return;
prevMouseButtons[idx] = pressed;
buffer.clear();
hasChanges = false;
writeEvent(EV_KEY, code, pressed ? 1 : 0);
writeEvent(EV_SYN, SYN_REPORT, 0);
buffer.flip();
if (!flushBuffer())
Log.e(TAG, "Mouse button write error: fake input mmap ring unavailable");
}
public synchronized void writeMouseWheel(int verticalClicks, int horizontalClicks, int value120) {
if (verticalClicks == 0 && horizontalClicks == 0)
return;
if (!isOpen && !open())
return;
buffer.clear();
hasChanges = false;
if (verticalClicks != 0) {
writeEvent(EV_REL, REL_WHEEL, verticalClicks);
writeEvent(EV_REL, REL_WHEEL_HI_RES, verticalClicks * value120);
}
if (horizontalClicks != 0) {
writeEvent(EV_REL, REL_HWHEEL, horizontalClicks);
writeEvent(EV_REL, REL_HWHEEL_HI_RES, horizontalClicks * value120);
}
writeEvent(EV_SYN, SYN_REPORT, 0);
buffer.flip();
if (!flushBuffer())
Log.e(TAG, "Mouse wheel write error: fake input mmap ring unavailable");
}
}
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.input
import android.os.Build
import android.view.KeyEvent
class HomeGuideInput(private val setPressed: (Boolean) -> Unit, private val onCancel: () -> Unit = {}) {
@@ -8,6 +9,10 @@ class HomeGuideInput(private val setPressed: (Boolean) -> Unit, private val onCa
fun onKeyEvent(event: KeyEvent, enabled: Boolean): Boolean {
if (!isHome(event.keyCode)) return false
if (isQuickMenuKey(event)) {
if (event.action == KeyEvent.ACTION_DOWN) cancel()
return false
}
if (!enabled) cancel()
val device = event.deviceId
return when (event.action) {
@@ -43,5 +48,10 @@ class HomeGuideInput(private val setPressed: (Boolean) -> Unit, private val onCa
companion object {
// The Retroid Nova pad falls back to Generic.kl, which maps its Home scan code to MOVE_HOME.
fun isHome(keyCode: Int) = keyCode == KeyEvent.KEYCODE_HOME || keyCode == KeyEvent.KEYCODE_MOVE_HOME
private const val DUO_QUICK_MENU_SCAN_CODE = 194
fun isQuickMenuKey(event: KeyEvent) =
event.scanCode == DUO_QUICK_MENU_SCAN_CODE && "Retroid Pocket Duo".equals(Build.MODEL, ignoreCase = true)
}
}
@@ -23,6 +23,9 @@ class KeyboardHost(
private val map: KeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)
var shown = false
private set
var imeShowing = false
private set
var onImeChanged: ((Boolean) -> Unit)? = null
init {
isFocusable = false
@@ -42,6 +45,28 @@ class KeyboardHost(
return KeyConnection()
}
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val visible = insets.isVisible(WindowInsets.Type.ime())
if (visible != imeShowing) {
imeShowing = visible
onImeChanged?.invoke(visible)
}
}
return super.onApplyWindowInsets(insets)
}
override fun onKeyPreIme(keyCode: Int, event: KeyEvent): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R || keyCode != KeyEvent.KEYCODE_BACK || !shown) {
return super.onKeyPreIme(keyCode, event)
}
if (event.action == KeyEvent.ACTION_UP && !event.isCanceled) {
hide()
onImeChanged?.invoke(false)
}
return true
}
fun toggle() = if (shown && imeVisible()) hide() else show()
private fun imeVisible() = Build.VERSION.SDK_INT < Build.VERSION_CODES.R ||
@@ -673,6 +673,11 @@ class OnScreenControls(
private fun closestSnap(position: Float, targets: List<Float>): Float? =
targets.minByOrNull { abs(position - it) }?.takeIf { abs(position - it) <= dp(SNAP_DP) }
/** Whether a finger going down at ([x], [y]) lands on something here, as [onTouchEvent] decides it. */
fun takesTouchAt(x: Float, y: Float): Boolean =
editing || keyboardContains(x, y) || (!buttonsOnly && quickContains(x, y)) ||
(!quickHidden && (controlAt(x, y) ?: adaptiveStickAt(x, y)) != null)
private fun controlAt(x: Float, y: Float): Control? =
controls.firstOrNull {
!quickHidden && isVisible(it) && (editing || !settings.adaptiveSticks || it.stick < 0) && it.contains(x, y, it.radius)
@@ -0,0 +1,145 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.util.Log
import android.view.InputDevice
import android.view.KeyEvent
import androidx.annotation.StringRes
import com.droiddeck.launcher.R
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
object PhysicalShortcuts {
internal const val KEY = "physicalShortcuts"
private const val TAG = "PhysicalShortcuts"
enum class Action(@StringRes val label: Int) {
STEAM(R.string.drawer_steam_menu),
QAM(R.string.drawer_open_qam),
DROIDDECK(R.string.shortcuts_dd_menu),
}
data class Button(
val device: String,
val name: String,
val keyCode: Int,
val scanCode: Int,
) {
fun matches(event: KeyEvent): Boolean =
event.device?.let { device == identity(it) } == true &&
keyCode == event.keyCode && scanCode == event.scanCode
fun sameInput(other: Button): Boolean =
device == other.device && keyCode == other.keyCode && scanCode == other.scanCode
val label: String
get() = KeyEvent.keyCodeToString(keyCode).removePrefix("KEYCODE_").removePrefix("BUTTON_")
}
data class Binding(val button: Button, val action: Action)
private fun identity(device: InputDevice): String =
"${device.vendorId}:${device.productId}:${device.descriptor.ifBlank { device.name }}"
fun isVolumeKey(event: KeyEvent): Boolean = when (event.keyCode) {
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> true
else -> false
}
fun isDrawerNavigationKey(event: KeyEvent): Boolean = when (event.keyCode) {
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN,
KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT -> true
else -> false
}
fun button(event: KeyEvent): Button? {
val device = event.device ?: return null
if (device.isVirtual || isVolumeKey(event)) return null
when (event.keyCode) {
KeyEvent.KEYCODE_HOME, KeyEvent.KEYCODE_POWER, KeyEvent.KEYCODE_SLEEP,
KeyEvent.KEYCODE_WAKEUP, KeyEvent.KEYCODE_APP_SWITCH -> return null
}
if (event.keyCode == KeyEvent.KEYCODE_UNKNOWN && event.scanCode <= 0) return null
return Button(identity(device), device.name, event.keyCode, event.scanCode)
}
fun read(context: Context): List<Binding> {
val raw = ControllerPrefs.prefs(context).getString(KEY, null) ?: return emptyList()
return try {
val array = JSONArray(raw)
buildList {
for (i in 0 until array.length()) {
try {
val entry = array.getJSONObject(i)
val action = Action.entries.firstOrNull { it.name == entry.getString("action") }
val code = entry.getInt("keyCode")
val scan = entry.getInt("scanCode")
val device = entry.getString("device")
if (action == null || device.isBlank() || code < 0 || scan < 0) {
Log.w(TAG, "Ignoring invalid shortcut at index $i")
continue
}
val binding = Binding(Button(device, entry.getString("name"), code, scan), action)
if (none { it.button.sameInput(binding.button) }) add(binding)
} catch (e: JSONException) {
Log.w(TAG, "Ignoring malformed shortcut at index $i", e)
}
}
}
} catch (e: JSONException) {
Log.w(TAG, "Could not read physical shortcuts; reset shortcuts to restore defaults", e)
emptyList()
}
}
fun assign(context: Context, button: Button, action: Action) {
val bindings = read(context).filterNot {
it.button.sameInput(button) || (it.button.device == button.device && it.action == action)
} + Binding(button, action)
write(context, bindings)
}
fun remove(context: Context, binding: Binding) {
write(context, read(context).filterNot { it == binding })
}
private fun write(context: Context, bindings: List<Binding>) {
val array = JSONArray()
bindings.forEach {
array.put(JSONObject().put("device", it.button.device).put("name", it.button.name)
.put("keyCode", it.button.keyCode).put("scanCode", it.button.scanCode).put("action", it.action.name))
}
ControllerPrefs.prefs(context).edit().putString(KEY, array.toString()).apply()
}
}
class PhysicalShortcutRouter {
var bindings: List<PhysicalShortcuts.Binding> = emptyList()
private data class Press(val device: Int, val keyCode: Int, val scanCode: Int)
private val held = mutableSetOf<Press>()
fun onKey(event: KeyEvent, enabled: Boolean, steam: Boolean, perform: (PhysicalShortcuts.Action) -> Unit): Boolean {
val press = Press(event.deviceId, event.keyCode, event.scanCode)
if (event.action == KeyEvent.ACTION_UP) return held.remove(press)
if (event.action != KeyEvent.ACTION_DOWN) return false
if (press in held) return true
if (!enabled || bindings.isEmpty()) return false
val button = PhysicalShortcuts.button(event) ?: return false
val binding = bindings.firstOrNull { it.button.sameInput(button) } ?: return false
if (!steam && binding.action != PhysicalShortcuts.Action.DROIDDECK) return false
held.add(press)
if (event.repeatCount == 0) perform(binding.action)
return true
}
fun onDeviceRemoved(deviceId: Int) {
held.removeAll { it.device == deviceId }
}
fun clear() {
held.clear()
}
}
@@ -1,104 +1,22 @@
package com.droiddeck.launcher.input
import android.os.Handler
import android.os.Looper
import android.view.MotionEvent
import android.view.ViewConfiguration
import kotlin.math.abs
import kotlin.math.roundToInt
class PointerGestures(
private val slopPx: Float,
private val listener: Listener,
) {
class PointerGestures {
interface Listener {
fun onMove(x: Float, y: Float)
fun onButton(button: Int, pressed: Boolean, x: Float, y: Float)
fun onWheel(steps: Int)
fun onLongPress()
}
private val handler = Handler(Looper.getMainLooper())
private var downX = 0f
private var downY = 0f
private var downAt = 0L
private var moved = false
private var held = false
private var dragging = false
private var scrolling = false
private var scrollAnchorY = 0f
private val longPress = Runnable {
held = true
listener.onLongPress()
}
fun onTouch(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
downX = event.x; downY = event.y; downAt = event.eventTime
moved = false; held = false; dragging = false; scrolling = false
listener.onMove(event.x, event.y)
handler.postDelayed(longPress, HOLD_MS)
return true
}
MotionEvent.ACTION_POINTER_DOWN -> {
handler.removeCallbacks(longPress)
if (dragging) { listener.onButton(BTN_LEFT, false, event.x, event.y); dragging = false }
scrolling = true
scrollAnchorY = event.getY(0)
return true
}
MotionEvent.ACTION_MOVE -> {
if (scrolling) {
val dy = event.getY(0) - scrollAnchorY
val steps = (dy / SCROLL_STEP_PX).toInt()
if (steps != 0) {
listener.onWheel(-steps)
scrollAnchorY += steps * SCROLL_STEP_PX
}
return true
}
if (!moved && (abs(event.x - downX) > slopPx || abs(event.y - downY) > slopPx)) {
moved = true
handler.removeCallbacks(longPress)
if (held) {
dragging = true
listener.onButton(BTN_LEFT, true, downX, downY)
}
}
if (moved) listener.onMove(event.x, event.y)
return true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
handler.removeCallbacks(longPress)
val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL
when {
scrolling -> {}
dragging -> listener.onButton(BTN_LEFT, false, event.x, event.y)
held && !moved && !cancelled -> {
listener.onButton(BTN_RIGHT, true, downX, downY)
listener.onButton(BTN_RIGHT, false, downX, downY)
}
!moved && !cancelled && event.eventTime - downAt < TAP_MS -> {
listener.onButton(BTN_LEFT, true, downX, downY)
listener.onButton(BTN_LEFT, false, downX, downY)
}
}
scrolling = false; dragging = false; held = false
return true
}
MotionEvent.ACTION_POINTER_UP -> return true
}
return false
fun onScroll(dx: Float, dy: Float) {}
fun onScrollEnd() {}
fun onZoom(steps: Int) {}
}
companion object {
const val BTN_LEFT = 0x110
const val BTN_RIGHT = 0x111
const val BTN_MIDDLE = 0x112
private const val HOLD_MS = 450L
private const val TAP_MS = 350L
private const val SCROLL_STEP_PX = 40f
fun slop(context: android.content.Context) = ViewConfiguration.get(context).scaledTouchSlop.toFloat()
}
@@ -609,6 +609,9 @@ class ScreenKeys(context: Context, private val sendKey: (Int, Boolean) -> Unit)
else -> entry.halfH
}
/** Whether a finger going down at ([x], [y]) lands on something here, as [onTouchEvent] decides it. */
fun takesTouchAt(x: Float, y: Float): Boolean = editing || entryAt(x, y) != null
private fun entryAt(x: Float, y: Float): Entry? = entries.lastOrNull { entry ->
x >= entry.cx - entry.halfW && x <= entry.cx + entry.halfW && y >= entry.cy - entry.halfH && y <= entry.cy + entry.halfH
}
@@ -86,27 +86,14 @@ class ScrollTouchGestures(
lastY = startY
tracker = VelocityTracker.obtain().also { it.addMovement(event) }
listener.onMove(startX, startY)
handler.postDelayed(longPress, HOLD_MS)
handler.postDelayed(longPress, TouchTiming.HOLD_MS)
}
MotionEvent.ACTION_MOVE -> {
val index = event.findPointerIndex(pointerId).takeIf { it >= 0 } ?: return true
tracker?.addMovement(event)
val x = event.getX(index)
val y = event.getY(index)
if (!scrolling && !dragging && hypot(x - startX, y - startY) > slopPx) {
handler.removeCallbacks(longPress)
if (held) {
dragging = true
listener.onButton(PointerGestures.BTN_LEFT, true)
} else {
scrolling = true
vertical = abs(y - startY) >= abs(x - startX)
lastX = startX
lastY = startY
}
}
if (dragging) listener.onMove(x, y)
follow(event, x, y)
for (h in 0 until event.historySize)
sample(event.getHistoricalX(index, h), event.getHistoricalY(index, h), event.getHistoricalEventTime(h))
sample(event.getX(index), event.getY(index), event.eventTime)
}
MotionEvent.ACTION_POINTER_UP -> {
if (event.getPointerId(event.actionIndex) == pointerId) cancel()
@@ -115,7 +102,7 @@ class ScrollTouchGestures(
handler.removeCallbacks(longPress)
if (pointerId == -1 || event.getPointerId(0) != pointerId) return true
tracker?.addMovement(event)
follow(event, event.x, event.y)
follow(event.x, event.y, event.eventTime)
when {
scrolling -> tracker?.takeIf { event.eventTime - movedAt <= FLING_STILL_MS }?.let { t ->
t.computeCurrentVelocity(1000)
@@ -139,9 +126,26 @@ class ScrollTouchGestures(
return true
}
private fun follow(event: MotionEvent, x: Float, y: Float) {
private fun sample(x: Float, y: Float, t: Long) {
if (!scrolling && !dragging && hypot(x - startX, y - startY) > slopPx) {
handler.removeCallbacks(longPress)
if (held) {
dragging = true
listener.onButton(PointerGestures.BTN_LEFT, true)
} else {
scrolling = true
vertical = abs(y - startY) >= abs(x - startX)
lastX = startX
lastY = startY
}
}
if (dragging) listener.onMove(x, y)
follow(x, y, t)
}
private fun follow(x: Float, y: Float, t: Long) {
if (!scrolling || (x == lastX && y == lastY)) return
movedAt = event.eventTime
movedAt = t
if (vertical) listener.onScroll(0f, lastY - y) else listener.onScroll(lastX - x, 0f)
lastX = x
lastY = y
@@ -151,7 +155,7 @@ class ScrollTouchGestures(
releaseClick()
listener.onButton(button, true)
clicked = button
handler.postDelayed(clickUp, CLICK_MS)
handler.postDelayed(clickUp, TouchTiming.CLICK_MS)
}
private fun releaseClick() {
@@ -181,8 +185,6 @@ class ScrollTouchGestures(
return if (pixels < 0) -units else units
}
private const val HOLD_MS = 500L
private const val CLICK_MS = 50L
private const val FLING_TIME_S = 0.45f
private const val FLING_STOP_PX = 40f
private const val FLING_STILL_MS = 60L
@@ -10,7 +10,12 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int) {
KEYBOARD_TRACKPAD("keyboard-trackpad", R.string.second_mode_keyboard_trackpad),
TERMINAL("terminal", R.string.second_mode_terminal),
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls),
CUSTOM_CONTROLS("custom-controls", R.string.input_custom_controls),
CUSTOM_CONTROLS("custom-controls", R.string.input_custom_controls);
companion object {
fun opening(remembered: String?, deckPad: Boolean): SecondScreenMode =
entries.firstOrNull { it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) } ?: if (deckPad) DECK_CONTROLS else KEYBOARD_TRACKPAD
}
}
data class SecondScreenDisplay(val id: Int, val label: String)
@@ -16,13 +16,19 @@ class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
private val handler = Handler(Looper.getMainLooper())
private val hostFile = File(context.filesDir, "session/android-clipboard")
private var active = false
private val androidListener = ClipboardManager.OnPrimaryClipChangedListener { refresh() }
private var published = false
private var shared: String? = null
private var echo: String? = null
private val androidListener = ClipboardManager.OnPrimaryClipChangedListener { refresh(changed = true) }
private val guestListener = object : WaylandCompositor.ClipboardListener {
override fun onGuestClipboardText(text: String) {
handler.post {
if (active && hasFocus() && WaylandCompositor.isClipboardListener(this)) {
val current = clipboard.primaryClip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text
shared = text
published = true
if (current?.toString() != text) {
echo = text
clipboard.setPrimaryClip(ClipData.newPlainText("DroidDeck", text))
}
}
@@ -46,17 +52,23 @@ class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
handler.removeCallbacksAndMessages(null)
}
fun refresh() {
fun refresh(changed: Boolean = false) {
if (!active || !hasFocus()) return
val clip = clipboard.primaryClip
if (clip == null) {
publish(null)
} else if (clip.itemCount > 0) {
publish(clip.getItemAt(0).text?.toString())
if (clip != null && clip.itemCount == 0) return
val text = clip?.getItemAt(0)?.text?.toString()
if (echo != null && text == echo) {
echo = null
return
}
echo = null
if (!changed && published && text == shared) return
publish(text)
}
private fun publish(text: String?) {
published = true
shared = text
WaylandCompositor.setClipboardText(text)
val pending = File(hostFile.parentFile, "android-clipboard.pending")
try {
@@ -244,6 +244,9 @@ class SteamTouchControls(
private fun hit(list: List<Element>, x: Float, y: Float): Element? =
list.filter { reach(it, x, y) <= 1.15f }.minByOrNull { reach(it, x, y) }
/** Whether a finger going down at ([x], [y]) lands on something here, as [onTouchEvent] decides it. */
fun takesTouchAt(x: Float, y: Float): Boolean = editing || menuOpen || hit(live(), x, y) != null
private fun live(): List<Element> =
if (shakenAway) emptyList() else if (options.inputMode == SteamTouchConfig.INPUT_MOUSE) elements.filter { it.type == SteamTouchConfig.THUMB } else elements
@@ -15,6 +15,7 @@ data class TouchGestureConfig(
val longPressAction: String = ACTION_RIGHT_CLICK,
val longPressMouseBehavior: String = MOUSE_BEHAVIOR_HOLD,
val longPressDelay: Int = DEFAULT_DELAY_MS,
val directHoldBehavior: String = MOUSE_BEHAVIOR_CLICK,
val doubleTapEnabled: Boolean = true,
val doubleTapDelay: Int = DEFAULT_DELAY_MS,
val twoFingerDragEnabled: Boolean = true,
@@ -50,6 +51,7 @@ data class TouchGestureConfig(
put(KEY_LONG_PRESS_ACTION, longPressAction)
put(KEY_LONG_PRESS_MOUSE_BEHAVIOR, longPressMouseBehavior)
put(KEY_LONG_PRESS_DELAY, longPressDelay)
put(KEY_DIRECT_HOLD_BEHAVIOR, directHoldBehavior)
put(KEY_DOUBLE_TAP_ENABLED, doubleTapEnabled)
put(KEY_DOUBLE_TAP_DELAY, doubleTapDelay)
put(KEY_TWO_FINGER_DRAG_ENABLED, twoFingerDragEnabled)
@@ -85,6 +87,7 @@ data class TouchGestureConfig(
const val MOUSE_BEHAVIOR_HOLD = "hold"
const val MOUSE_BEHAVIOR_CLICK = "click"
const val MOUSE_BEHAVIOR_NONE = "none"
const val MOUSE_DRAG_MOVEMENT_DIRECT = "direct"
const val MOUSE_DRAG_MOVEMENT_RELATIVE = "relative"
@@ -110,6 +113,7 @@ data class TouchGestureConfig(
private const val KEY_LONG_PRESS_ACTION = "longPressAction"
private const val KEY_LONG_PRESS_MOUSE_BEHAVIOR = "longPressMouseBehavior"
private const val KEY_LONG_PRESS_DELAY = "longPressDelay"
private const val KEY_DIRECT_HOLD_BEHAVIOR = "directHoldBehavior"
private const val KEY_DOUBLE_TAP_ENABLED = "doubleTapEnabled"
private const val KEY_DOUBLE_TAP_DELAY = "doubleTapDelay"
private const val KEY_TWO_FINGER_DRAG_ENABLED = "twoFingerDragEnabled"
@@ -155,6 +159,9 @@ data class TouchGestureConfig(
obj.optString(KEY_LONG_PRESS_MOUSE_BEHAVIOR, MOUSE_BEHAVIOR_HOLD)
),
longPressDelay = obj.optInt(KEY_LONG_PRESS_DELAY, DEFAULT_DELAY_MS),
directHoldBehavior = normalizeDirectHoldBehavior(
obj.optString(KEY_DIRECT_HOLD_BEHAVIOR, MOUSE_BEHAVIOR_CLICK)
),
doubleTapEnabled = obj.optBoolean(KEY_DOUBLE_TAP_ENABLED, true),
doubleTapDelay = obj.optInt(KEY_DOUBLE_TAP_DELAY, DEFAULT_DELAY_MS),
twoFingerDragEnabled = obj.optBoolean(KEY_TWO_FINGER_DRAG_ENABLED, true),
@@ -190,6 +197,10 @@ data class TouchGestureConfig(
}
}
private fun normalizeDirectHoldBehavior(value: String): String {
return if (value == MOUSE_BEHAVIOR_CLICK || value == MOUSE_BEHAVIOR_NONE) value else MOUSE_BEHAVIOR_HOLD
}
private fun normalizeMouseBehavior(value: String): String {
return if (value == MOUSE_BEHAVIOR_CLICK) MOUSE_BEHAVIOR_CLICK else MOUSE_BEHAVIOR_HOLD
}
@@ -0,0 +1,31 @@
package com.droiddeck.launcher.input
import com.droiddeck.launcher.session.SessionPrefs
object TouchRouter {
enum class Route { BLOCKED, GESTURES, SCROLL, OFF, TOUCHPAD, DIRECT }
data class Snapshot(
val uiBlocking: Boolean,
val mode: String,
val scrollLayer: Boolean,
val steamSession: Boolean,
val steamDesktopUi: Boolean,
)
fun decide(s: Snapshot): Route {
if (s.uiBlocking) return Route.BLOCKED
if (s.mode == SessionPrefs.TOUCH_GESTURES) return Route.GESTURES
if (s.scrollLayer) return Route.SCROLL
if (s.mode == SessionPrefs.TOUCH_OFF) return Route.OFF
return if (touchpad(s)) Route.TOUCHPAD else Route.DIRECT
}
fun steamKeyboardZone(s: Snapshot): Boolean = s.steamSession && !s.steamDesktopUi
private fun touchpad(s: Snapshot): Boolean = when (s.mode) {
SessionPrefs.TOUCH_PAD -> true
SessionPrefs.TOUCH_DIRECT -> false
else -> !s.steamSession || s.steamDesktopUi
}
}
@@ -0,0 +1,9 @@
package com.droiddeck.launcher.input
object TouchTiming {
const val HOLD_MS = 500L
const val TAP_MS = 300L
const val CLICK_MS = 30L
const val DOUBLE_TAP_MS = 300L
const val SCROLL_STEP_PX = 36f
}
@@ -4,6 +4,7 @@ import android.os.Handler
import android.os.Looper
import android.view.MotionEvent
import kotlin.math.abs
import kotlin.math.hypot
class TouchpadGestures(
private val slopPx: Float,
@@ -15,6 +16,7 @@ class TouchpadGestures(
private set
var bounds: android.graphics.RectF = android.graphics.RectF(0f, 0f, 1f, 1f)
var sensitivity = 1.15f
var desktop = false
private val handler = Handler(Looper.getMainLooper())
private var lastX = 0f
@@ -27,7 +29,11 @@ class TouchpadGestures(
private var secondDownAt = 0L
private var secondWasTap = false
private var twoFingers = false
private var scrollAnchorX = 0f
private var scrollAnchorY = 0f
private var fingers = 0
private var pinching = false
private var pinchSpan = 0f
private var scrolled = false
private var anchorId = -1
private var anchorStartX = 0f
@@ -52,7 +58,7 @@ class TouchpadGestures(
releaseClick()
listener.onButton(button, true, x, y)
clicked = button
handler.postDelayed(clickUp, CLICK_MS)
handler.postDelayed(clickUp, TouchTiming.CLICK_MS)
}
private fun releaseClick() {
@@ -79,6 +85,20 @@ class TouchpadGestures(
y = py.coerceIn(bounds.top, bounds.bottom)
}
private fun trackMove(px: Float, py: Float) {
val dx = px - lastX
val dy = py - lastY
lastX = px; lastY = py
travelled += abs(dx) + abs(dy)
if (travelled > slopPx) {
handler.removeCallbacks(longPress)
val speed = abs(dx) + abs(dy)
val gain = sensitivity * (1f + minOf(speed / 40f, 1.5f))
place(x + dx * gain, y + dy * gain)
listener.onMove(x, y)
}
}
fun onTouch(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
@@ -86,18 +106,20 @@ class TouchpadGestures(
lastX = event.x; lastY = event.y
downAt = event.eventTime
travelled = 0f; held = false; twoFingers = false; scrolled = false; secondWasTap = false
fingers = 1; pinching = false
anchorId = event.getPointerId(0); moverId = -1; holdDrag = false; scrollLocked = false
if (event.eventTime - lastTapAt < DOUBLE_TAP_MS) {
if (event.eventTime - lastTapAt < TouchTiming.DOUBLE_TAP_MS) {
dragging = true
listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
} else {
dragging = false
handler.postDelayed(longPress, HOLD_MS)
handler.postDelayed(longPress, TouchTiming.HOLD_MS)
}
return true
}
MotionEvent.ACTION_POINTER_DOWN -> {
handler.removeCallbacks(longPress)
fingers = maxOf(fingers, event.pointerCount)
val i = event.actionIndex
if (moverId == -1 && event.getPointerId(i) != anchorId) {
moverId = event.getPointerId(i)
@@ -111,7 +133,9 @@ class TouchpadGestures(
twoFingers = true
secondDownAt = event.eventTime
secondWasTap = true
scrollAnchorX = (event.getX(0) + event.getX(1)) / 2f
scrollAnchorY = (event.getY(0) + event.getY(1)) / 2f
pinchSpan = span(event)
return true
}
MotionEvent.ACTION_MOVE -> {
@@ -146,29 +170,49 @@ class TouchpadGestures(
} else if (holdDrag) {
return true
}
if (twoFingers && event.pointerCount >= 2) {
val mid = (event.getY(0) + event.getY(1)) / 2f
val dy = mid - scrollAnchorY
val steps = (dy / SCROLL_STEP_PX).toInt()
if (steps != 0) {
listener.onWheel(-steps)
scrollAnchorY += steps * SCROLL_STEP_PX
if (twoFingers && event.pointerCount >= 2 && desktop) {
if (fingers >= 3) return true
val span = span(event)
if (!scrolled && !pinching && abs(span - pinchSpan) > slopPx * PINCH_SLOPS) {
pinching = true
secondWasTap = false
pinchSpan = span
}
if (pinching) {
val steps = ((span - pinchSpan) / PINCH_STEP_PX).toInt()
if (steps != 0) {
listener.onZoom(-steps)
pinchSpan += steps * PINCH_STEP_PX
}
return true
}
val midX = (event.getX(0) + event.getX(1)) / 2f
val midY = (event.getY(0) + event.getY(1)) / 2f
val dx = scrollAnchorX - midX
val dy = scrollAnchorY - midY
if (scrolled || abs(dx) + abs(dy) > slopPx) {
listener.onScroll(dx, dy)
scrollAnchorX = midX; scrollAnchorY = midY
scrolled = true
secondWasTap = false
}
return true
}
val dx = event.x - lastX
val dy = event.y - lastY
lastX = event.x; lastY = event.y
travelled += abs(dx) + abs(dy)
if (travelled > slopPx) {
handler.removeCallbacks(longPress)
val speed = (abs(dx) + abs(dy))
val gain = sensitivity * (1f + minOf(speed / 40f, 1.5f))
place(x + dx * gain, y + dy * gain)
listener.onMove(x, y)
if (twoFingers && event.pointerCount >= 2) {
val mid = (event.getY(0) + event.getY(1)) / 2f
val dy = mid - scrollAnchorY
val steps = (dy / TouchTiming.SCROLL_STEP_PX).toInt()
if (steps != 0) {
listener.onWheel(-steps)
scrollAnchorY += steps * TouchTiming.SCROLL_STEP_PX
scrolled = true
secondWasTap = false
}
return true
}
for (h in 0 until event.historySize)
trackMove(event.getHistoricalX(0, h), event.getHistoricalY(0, h))
trackMove(event.x, event.y)
return true
}
MotionEvent.ACTION_POINTER_UP -> {
@@ -194,7 +238,12 @@ class TouchpadGestures(
event.findPointerIndex(anchorId).takeIf { it >= 0 && it != event.actionIndex }?.let {
lastX = event.getX(it); lastY = event.getY(it)
}
if (twoFingers && secondWasTap && event.eventTime - secondDownAt < TAP_MS && !scrolled) {
if (desktop && scrolled && event.pointerCount == 2) listener.onScrollEnd()
if (fingers >= 3) {
if (event.pointerCount == 2 && secondWasTap && !scrolled && event.eventTime - downAt < TouchTiming.TAP_MS * 2)
click(PointerGestures.BTN_MIDDLE)
if (event.pointerCount == 2) secondWasTap = false
} else if (twoFingers && secondWasTap && event.eventTime - secondDownAt < TouchTiming.TAP_MS && !scrolled) {
click(PointerGestures.BTN_RIGHT)
secondWasTap = false
}
@@ -206,29 +255,30 @@ class TouchpadGestures(
when {
dragging -> listener.onButton(PointerGestures.BTN_LEFT, false, x, y)
twoFingers -> {
if (secondWasTap && !scrolled && !cancelled && event.eventTime - downAt < TAP_MS * 2) {
if (secondWasTap && !scrolled && !cancelled && event.eventTime - downAt < TouchTiming.TAP_MS * 2) {
click(PointerGestures.BTN_RIGHT)
}
}
!cancelled && travelled <= slopPx && event.eventTime - downAt < TAP_MS -> {
!cancelled && travelled <= slopPx && event.eventTime - downAt < TouchTiming.TAP_MS -> {
click(PointerGestures.BTN_LEFT)
lastTapAt = event.eventTime
}
}
dragging = false; held = false; twoFingers = false
holdDrag = false; scrollLocked = false; anchorId = -1; moverId = -1
pinching = false; fingers = 0
return true
}
}
return false
}
private fun span(event: MotionEvent): Float =
if (event.pointerCount < 2) 0f else hypot(event.getX(0) - event.getX(1), event.getY(0) - event.getY(1))
companion object {
private const val HOLD_MS = 500L
private const val TAP_MS = 300L
private const val CLICK_MS = 50L
private const val DOUBLE_TAP_MS = 300L
private const val SCROLL_STEP_PX = 36f
private const val PINCH_SLOPS = 3f
private const val PINCH_STEP_PX = 60f
private const val HOLD_DRAG_MOVER_SLOPS = 2f
private const val HOLD_DRAG_ANCHOR_SLOPS = 0.5f
}
@@ -36,7 +36,7 @@ public final class TouchscreenGestures {
private final Output output;
private final float doubleTapSlop;
private TouchGestureConfig gestureConfig = new TouchGestureConfig();
private static final int CLICK_DELAYED_TIME = 50;
private static final int CLICK_DELAYED_TIME = 30;
private Runnable delayedPress, pendingHoldClickRelease;
private Runnable pendingTapPress;
private final ArrayDeque<TapClick> pendingTapClicks = new ArrayDeque<>();
@@ -0,0 +1,205 @@
package com.droiddeck.launcher.input
import android.os.Handler
import android.os.Looper
import android.view.MotionEvent
import kotlin.math.abs
import kotlin.math.hypot
class TwoFingerGestures(private val slopPx: Float, private val listener: Listener) {
interface Listener {
fun cancelTouch()
fun replay(event: MotionEvent)
fun rightClick(x: Float, y: Float)
fun scrollStart(x: Float, y: Float)
fun scroll(dx: Float, dy: Float)
fun scrollEnd()
}
private enum class State { IDLE, PENDING, CANDIDATE, TAPPED, HELD, SCROLLING, PASSING }
private val handler = Handler(Looper.getMainLooper())
private var state = State.IDLE
private var x = 0f
private var y = 0f
private var twoAt = 0L
private var startSpan = 0f
private var lastX = 0f
private var lastY = 0f
private val starts = HashMap<Int, Pair<Float, Float>>()
private val held = ArrayList<MotionEvent>()
private val hold = Runnable {
if (state != State.CANDIDATE) return@Runnable
state = State.HELD
drop()
listener.cancelTouch()
listener.rightClick(x, y)
}
private val release = Runnable {
if (state == State.PENDING) pass(State.IDLE)
}
fun cancel() {
if (state == State.SCROLLING) listener.scrollEnd()
handler.removeCallbacks(hold)
handler.removeCallbacks(release)
drop()
state = State.IDLE
}
fun onTouch(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
cancel()
starts.clear()
x = event.x
y = event.y
note(event, event.actionIndex)
state = State.PENDING
keep(event)
handler.postDelayed(release, LAND_MS)
return true
}
MotionEvent.ACTION_POINTER_DOWN -> {
note(event, event.actionIndex)
when (state) {
State.PENDING -> {
handler.removeCallbacks(release)
keep(event)
if (event.pointerCount != 2) {
pass(State.PASSING)
return true
}
state = State.CANDIDATE
twoAt = event.eventTime
startSpan = span(event)
lastX = midX(event)
lastY = midY(event)
handler.postDelayed(hold, HOLD_MS)
return true
}
State.CANDIDATE -> {
keep(event)
pass(State.PASSING)
return true
}
State.SCROLLING, State.HELD, State.TAPPED -> return true
else -> Unit
}
}
MotionEvent.ACTION_MOVE -> when (state) {
State.PENDING -> {
keep(event)
if (moved(event)) pass(State.IDLE)
return true
}
State.CANDIDATE -> {
if (event.pointerCount == 2 && moved(event)) {
handler.removeCallbacks(hold)
if (abs(span(event) - startSpan) > slopPx * 2) {
keep(event)
pass(State.PASSING)
return true
}
state = State.SCROLLING
drop()
listener.cancelTouch()
lastX = midX(event)
lastY = midY(event)
listener.scrollStart(lastX, lastY)
return true
}
keep(event)
return true
}
State.SCROLLING -> {
if (event.pointerCount >= 2) {
val mx = midX(event)
val my = midY(event)
listener.scroll(lastX - mx, lastY - my)
lastX = mx
lastY = my
}
return true
}
State.TAPPED, State.HELD -> return true
else -> Unit
}
MotionEvent.ACTION_POINTER_UP -> when (state) {
State.CANDIDATE -> {
handler.removeCallbacks(hold)
keep(event)
if (event.eventTime - twoAt < TAP_MS) {
state = State.TAPPED
drop()
return true
}
pass(State.PASSING)
return true
}
State.SCROLLING, State.HELD, State.TAPPED -> return true
else -> Unit
}
MotionEvent.ACTION_UP -> {
val was = state
if (was == State.PENDING) {
keep(event)
pass(State.IDLE)
return true
}
cancel()
when (was) {
State.TAPPED -> {
listener.cancelTouch()
listener.rightClick(x, y)
return true
}
State.SCROLLING, State.HELD -> return true
else -> Unit
}
}
MotionEvent.ACTION_CANCEL -> cancel()
}
return false
}
private fun keep(event: MotionEvent) {
held += MotionEvent.obtain(event)
}
private fun drop() {
held.forEach { it.recycle() }
held.clear()
}
private fun pass(next: State) {
handler.removeCallbacks(release)
handler.removeCallbacks(hold)
state = next
val events = held.toList()
held.clear()
events.forEach {
listener.replay(it)
it.recycle()
}
}
private fun note(event: MotionEvent, index: Int) {
starts[event.getPointerId(index)] = event.getX(index) to event.getY(index)
}
private fun moved(event: MotionEvent): Boolean = (0 until event.pointerCount).any { i ->
val start = starts[event.getPointerId(i)] ?: return@any false
hypot(event.getX(i) - start.first, event.getY(i) - start.second) > slopPx
}
private fun span(event: MotionEvent) = hypot(event.getX(1) - event.getX(0), event.getY(1) - event.getY(0))
private fun midX(event: MotionEvent) = (event.getX(0) + event.getX(1)) / 2f
private fun midY(event: MotionEvent) = (event.getY(0) + event.getY(1)) / 2f
companion object {
const val LAND_MS = 250L
const val TAP_MS = 350L
const val HOLD_MS = 500L
}
}
@@ -180,7 +180,8 @@ object BwrapSpawner {
val env = LinkedHashMap<String, String>()
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } }
if (binds.any { it.guest == "/dev" }) gpu(rootfs, root, env)?.forEach { addBind(it) }
preload(session, rootfs, env).forEach { addBind(it) }
val libc = listOf("/usr/lib/aarch64-linux-gnu/libc.so.6", "/lib/aarch64-linux-gnu/libc.so.6").map { hostPath(binds, root.path, it) }
if (preloadFits(rootfs, libc.firstOrNull { File(it).isFile } ?: libc.first())) preload(session, rootfs, env).forEach { addBind(it) }
zypakShims(binds, root, dir).forEach { addBind(it) }
browserSandboxes(env)
return Plan(root, binds, request.optString("cwd", "/").ifEmpty { "/" }, argv, env)
@@ -188,16 +189,20 @@ object BwrapSpawner {
private const val GPU_DIR = "/run/droiddeck-gpu"
private val LIB_DIRS = listOf("usr/lib/aarch64-linux-gnu", "usr/lib")
private val GPU_LIBS = listOf("libdisplay-info.so.3", "libdisplay-info.so.2", "libSPIRV-Tools.so", "libSPIRV-Tools-opt.so")
private fun runtimeLib(rootfs: String, name: String): File? =
LIB_DIRS.map { File(rootfs, "$it/$name") }.firstOrNull { it.exists() }
private fun gpu(rootfs: String, root: File, env: MutableMap<String, String>): List<Bind>? {
val lib = File(rootfs, "usr/lib")
val driver = File(lib, "libvulkan_freedreno.so")
if (!driver.isFile || !File("/dev/kgsl-3d0").exists()) return null
val driver = runtimeLib(rootfs, "libvulkan_freedreno.so")
if (driver == null || !File("/dev/kgsl-3d0").exists()) return null
if (env.containsKey("VK_ICD_FILENAMES") || env.containsKey("VK_DRIVER_FILES")) return null
if (env["BL_DESKTOP"] == "1" && env["GAMESCOPE_WAYLAND_DISPLAY"] == null) return null
val binds = ArrayList<Bind>()
for (name in listOf("libvulkan_freedreno.so", "libdisplay-info.so.3", "libSPIRV-Tools.so", "libSPIRV-Tools-opt.so")) {
val f = File(lib, name)
if (!f.exists()) { Log.w(TAG, "gpu: the runtime has no $name; apps draw on the CPU"); return null }
val binds = arrayListOf(Bind(driver.canonicalPath, "$GPU_DIR/libvulkan_freedreno.so"))
for (name in GPU_LIBS) {
val f = runtimeLib(rootfs, name) ?: continue
binds.add(Bind(f.canonicalPath, "$GPU_DIR/$name"))
}
val icd = File(root.parentFile, "freedreno_icd.json")
@@ -227,6 +232,27 @@ object BwrapSpawner {
return binds
}
private val GLIBC_RELEASE = Regex("release version 2\\.(\\d+)")
private val GLIBC_NEED = Regex("GLIBC_2\\.(\\d+)")
private val glibcMinors = java.util.concurrent.ConcurrentHashMap<String, Int>()
private fun glibcMinor(file: File, pattern: Regex, pick: (Sequence<Int>) -> Int?): Int? {
val key = "${file.path}:${file.length()}:${file.lastModified()}:${pattern.pattern}"
glibcMinors[key]?.let { return it }
val text = runCatching { String(file.readBytes(), Charsets.ISO_8859_1) }.getOrNull() ?: return null
return pick(pattern.findAll(text).map { it.groupValues[1].toInt() })?.also { glibcMinors[key] = it }
}
internal fun preloadFits(rootfs: String, sandboxLibc: String): Boolean {
val libc = File(sandboxLibc)
if (!libc.isFile) return true
val have = glibcMinor(libc, GLIBC_RELEASE) { it.firstOrNull() } ?: return true
val libs = FileUtils.readString(File(rootfs, "etc/ld.so.preload"))?.lines()
?.map { it.trim() }?.filter { it.startsWith("/") } ?: return true
val need = libs.mapNotNull { File(rootfs + it).takeIf { f -> f.isFile }?.let { f -> glibcMinor(f, GLIBC_NEED) { m -> m.maxOrNull() } } }.maxOrNull() ?: return true
return have >= need
}
private const val PRELOAD_DIR = "/run/droiddeck-preload"
private const val NET_LINK = "etc/droiddeck-net"
@@ -321,7 +347,15 @@ object BwrapSpawner {
catch (e: IOException) { }
if (process.isAlive) {
Log.i(TAG, "sandbox $id: its bwrap is gone; stopping it")
process.destroy()
if (pid > 0) {
runCatching { android.system.Os.kill(pid, android.system.OsConstants.SIGQUIT) }
} else {
process.destroy()
}
try {
if (!process.waitFor(3, java.util.concurrent.TimeUnit.SECONDS)) process.destroyForcibly()
} catch (_: InterruptedException) {
}
}
}, "bwrap-$id-watch").apply { isDaemon = true; start() }
val buffer = ByteArray(16384)
@@ -22,8 +22,8 @@ object DesktopCatalog {
val icon: String, val category: String,
)
fun fetch(url: String = CATALOG_URL): List<Entry>? {
val body = Downloader.downloadString(url) ?: return null
fun fetch(url: String = CATALOG_URL, cancelled: java.util.function.BooleanSupplier? = null): List<Entry>? {
val body = Downloader.downloadString(url, cancelled) ?: return null
return try {
val json = JSONObject(body)
val arr = json.getJSONArray("packages")
@@ -71,9 +71,22 @@ object DesktopCatalog {
}
fun resumeInterrupted(context: Context, listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) {
resumeInterrupted(context, null, listener)
}
fun resumeInterrupted(
context: Context,
cancelled: Downloader.Cancellation?,
listener: LinuxRuntimeInstaller.ProgressListener?,
): String? = synchronized(installLock) {
for (entry in interrupted(context)) {
Log.w(TAG, "finishing the interrupted install of ${entry.id} ${entry.version}")
install(context, entry, listener)?.let { return it }
val problem = if (cancelled == null) {
install(context, entry, listener)
} else {
install(context, entry, cancelled, listener)
}
if (problem != null) return problem
}
null
}
@@ -102,19 +115,27 @@ object DesktopCatalog {
!File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/appmanifest_4427310.acf").isFile
const val DESKTOP_ID = "desktop-kde"
const val EMULATORS_ID = "emulators"
private const val EMULATORS_SCRIPT = "/usr/local/bin/droiddeck-emulators"
fun desktopEntry(context: Context) = Entry(
DESKTOP_ID, context.getString(R.string.content_linux_desktop), 1, BuildConfig.DESKTOP_KDE_TAG, "tar",
BuildConfig.DESKTOP_KDE_URL, BuildConfig.DESKTOP_KDE_SHA256, BuildConfig.DESKTOP_KDE_SIZE, "",
"", "",
)
fun desktopEntry(context: Context): Entry {
val pack = DesktopPack.info(LinuxRuntime.rootDir(context))
return Entry(
DESKTOP_ID, context.getString(R.string.content_linux_desktop), 1, pack?.tag ?: BuildConfig.DESKTOP_KDE_TAG, "tar",
pack?.url ?: BuildConfig.DESKTOP_KDE_URL, pack?.sha256 ?: BuildConfig.DESKTOP_KDE_SHA256,
pack?.size ?: BuildConfig.DESKTOP_KDE_SIZE, "", "", "",
)
}
fun desktopInstalled(context: Context): Boolean = desktopInstalled(LinuxRuntime.rootDir(context))
fun desktopFromPack(root: File): Boolean = DesktopPack.info(root) != null
fun desktopInstalled(root: File): Boolean =
!File(root, DesktopRemoval.PENDING).exists() &&
File(root, "usr/bin/kwin_wayland").isFile &&
FileUtils.readString(File(root, ".droiddeck-pkg-$DESKTOP_ID"))?.trim() == BuildConfig.DESKTOP_KDE_TAG
FileUtils.readString(File(root, ".droiddeck-pkg-$DESKTOP_ID"))?.trim() ==
(DesktopPack.info(root)?.tag ?: BuildConfig.DESKTOP_KDE_TAG)
fun desktopPresent(context: Context): Boolean {
val root = LinuxRuntime.rootDir(context)
@@ -144,12 +165,19 @@ object DesktopCatalog {
}
fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) {
installLocked(context, entry, listener)
installLocked(context, entry, null, listener)
}
private fun installLocked(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
fun install(context: Context, entry: Entry, cancelled: Downloader.Cancellation,
listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) {
installLocked(context, entry, cancelled, listener)
}
private fun installLocked(context: Context, entry: Entry, cancelled: Downloader.Cancellation?,
listener: LinuxRuntimeInstaller.ProgressListener?): String? {
val root = LinuxRuntime.rootDir(context)
if (!root.isDirectory) return context.getString(R.string.deskpkg_runtime_missing)
if (entry.id == EMULATORS_ID && desktopFromPack(root)) return installEmulators(context, entry, cancelled, listener)
if (entry.sha256.isEmpty()) return context.getString(R.string.deskpkg_no_checksum, entry.name)
val download = downloadFile(context, entry)
val journal = journal(root, entry.id)
@@ -166,14 +194,20 @@ object DesktopCatalog {
if (!downloaded(download, entry)) {
val downloading = context.getString(R.string.user_apps_downloading, entry.name)
report.onProgress(LinuxRuntimeInstaller.Step.DOWNLOADING, downloading, 0)
val ok = Downloader.downloadFile(entry.url, download, true, entry.sha256) { f ->
val progress = java.util.function.Consumer<Float> { f ->
report.onProgress(LinuxRuntimeInstaller.Step.DOWNLOADING, downloading, if (f < 0) -1 else Math.round(f * 100f))
}
if (!ok) return context.getString(R.string.user_apps_download_failed)
val ok = if (cancelled == null) {
Downloader.downloadFile(entry.url, download, true, entry.sha256, progress)
} else {
Downloader.downloadFile(entry.url, download, true, entry.sha256, cancelled, progress)
}
if (!ok || cancelled?.getAsBoolean() == true) return context.getString(R.string.user_apps_download_failed)
report.onProgress(LinuxRuntimeInstaller.Step.VERIFYING, context.getString(R.string.rtinst_verifying), -1)
val actual = Hashes.sha256(download)
if (!entry.sha256.equals(actual, ignoreCase = true)) return context.getString(R.string.deskpkg_checksum_mismatch)
}
if (cancelled?.getAsBoolean() == true) return context.getString(R.string.user_apps_download_failed)
report.onProgress(context.getString(R.string.deskpkg_installing, entry.name), -1)
when (entry.kind) {
"appimage" -> {
@@ -192,11 +226,12 @@ object DesktopCatalog {
check(FileUtils.writeString(journal, entryJson(entry).toString())) { "Could not record the package installation" }
keepDownload = true
marker(context, entry.id).delete()
if (entry.id == DESKTOP_ID && desktopFromPack(root)) DesktopPack.prepareInstall(root)
if (!LinuxRuntimeInstaller.extract(context, download, root, report)) return context.getString(R.string.deskpkg_extract_failed)
}
}
if (entry.id == DESKTOP_ID) {
cleanLegacy(context, report)
if (desktopFromPack(root)) DesktopPack.finishInstall(root) else cleanLegacy(context, report)
val pending = File(root, DesktopRemoval.PENDING)
check(!pending.exists() || pending.delete()) { "Could not finish desktop installation" }
}
@@ -214,6 +249,47 @@ object DesktopCatalog {
}
}
private fun installEmulators(context: Context, entry: Entry, cancelled: Downloader.Cancellation?,
listener: LinuxRuntimeInstaller.ProgressListener?): String? {
val release = RuntimeInstallService.holdForPackage(context, context.getString(R.string.deskpkg_installing, entry.name))
val stop = java.util.concurrent.atomic.AtomicBoolean(false)
val finished = java.util.concurrent.atomic.AtomicBoolean(false)
cancelled?.let { token ->
Thread({
try {
while (!finished.get() && !stop.get()) {
if (token.getAsBoolean()) stop.set(true) else Thread.sleep(200)
}
} catch (_: InterruptedException) {
}
}, "emulators-cancel").apply { isDaemon = true; start() }
}
try {
var failure: String? = null
val status = GuestCommand.run(context, listOf("/bin/bash", EMULATORS_SCRIPT, "install"), logName = "emulators",
cancelled = stop) { line ->
when {
line.startsWith("== STEP ") -> {
val stage = context.getString(R.string.deskpkg_installing, line.removePrefix("== STEP "))
RuntimeInstallService.packageProgress(stage, -1)
listener?.onProgress(stage, -1)
}
line.startsWith("== FAIL ") -> failure = line.removePrefix("== FAIL ")
}
}
if (stop.get()) return context.getString(R.string.user_apps_download_failed)
if (failure != null || status != 0) return context.getString(R.string.deskpkg_install_failed)
check(FileUtils.writeString(marker(context, entry.id), entry.version)) { "Could not finish package installation" }
return null
} catch (e: Exception) {
Log.e(TAG, "install ${entry.id}", e)
return e.message ?: context.getString(R.string.deskpkg_install_failed)
} finally {
finished.set(true)
release()
}
}
private fun unzipAppImage(zip: File, target: File): Boolean {
try {
java.util.zip.ZipInputStream(java.io.BufferedInputStream(java.io.FileInputStream(zip))).use { zin ->
@@ -73,10 +73,42 @@ internal object DesktopFileRemoval {
}
}
private val RECORD = Regex("[A-Za-z0-9@._+:-]+")
fun desktopRecords(root: File): Set<String> {
val list = safeFile(root, "usr/share/droiddeck/pacman/desktop-packages.txt") ?: return emptySet()
if (!Files.isRegularFile(list.toPath(), NOFOLLOW_LINKS)) return emptySet()
return list.readLines().mapNotNull { line ->
line.split(' ').takeIf { it.size == 2 }?.let { "${it[0]}-${it[1]}" }?.takeIf { RECORD.matches(it) && it != "." && it != ".." }
}.toSet()
}
fun removeRecords(root: File, records: Set<String>) {
val lib = File(root, "var/lib/pacman")
if (Files.isSymbolicLink(File(root, "var").toPath()) || Files.isSymbolicLink(lib.toPath())) return
val local = File(lib, "local")
if (!local.isDirectory || Files.isSymbolicLink(local.toPath())) return
for (record in records) {
if (!RECORD.matches(record) || record == "." || record == "..") continue
val dir = File(local, record)
if (Files.isSymbolicLink(dir.toPath()) || !dir.isDirectory) continue
for (file in dir.listFiles().orEmpty()) {
if (Files.isSymbolicLink(file.toPath()) || file.isFile) Files.delete(file.toPath())
}
if (!dir.delete()) throw IOException("Cannot remove $dir")
}
for (name in listOf("sync/droiddeck.db", "droiddeck-desktop")) {
val file = File(lib, name)
if (Files.isSymbolicLink(file.toPath()) || file.isFile) Files.delete(file.toPath())
}
}
fun runtimeFiles(root: File): Set<String> = buildSet {
val database = File(root, "var/lib/pacman/local")
if (!database.isDirectory || Files.isSymbolicLink(database.toPath())) throw IOException("Runtime package database missing")
val desktop = desktopRecords(root)
for (pkg in database.listFiles().orEmpty()) {
if (pkg.name in desktop) continue
val files = File(pkg, "files")
if (!pkg.isDirectory || Files.isSymbolicLink(pkg.toPath()) || !files.isFile || Files.isSymbolicLink(files.toPath())) continue
var inFiles = false
@@ -0,0 +1,178 @@
package com.droiddeck.launcher.runtime
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.Hashes
import java.io.File
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.Paths
import java.nio.file.StandardCopyOption
import java.util.zip.GZIPInputStream
import org.json.JSONObject
internal object DesktopPack {
const val INFO = "usr/share/droiddeck/desktop-pack.json"
const val META = "usr/share/droiddeck/desktop"
private const val MANIFEST = "$META/files.tsv.gz"
private const val ORIGINALS = "$META/originals"
private const val STATUS = "var/lib/dpkg/status"
private const val STATUS_BEFORE = "var/lib/dpkg/status.droiddeck"
private const val PACK_STATUS = "$META/dpkg-status"
data class Info(val tag: String, val url: String, val sha256: String, val size: Long)
data class Entry(val kind: Char, val type: Char, val size: Long, val value: String, val path: String) {
companion object {
fun parse(line: String): Entry? {
val parts = line.split('\t', limit = 5)
if (parts.size != 5 || parts[0].length != 1 || parts[1].length != 1) return null
return Entry(parts[0][0], parts[1][0], parts[2].toLongOrNull() ?: return null, parts[3], parts[4])
}
}
}
data class Result(val removed: Int, val restored: Int, val kept: Int)
fun info(root: File): Info? = runCatching {
val json = JSONObject(FileUtils.readString(File(root, INFO)) ?: return null)
Info(json.getString("tag"), json.getString("url"), json.getString("sha256"), json.getLong("size"))
}.getOrNull()
fun installed(root: File): Boolean = File(root, MANIFEST).isFile
fun entries(root: File): List<Entry> =
GZIPInputStream(File(root, MANIFEST).inputStream()).bufferedReader().use { reader ->
reader.lineSequence().mapNotNull(Entry::parse).toList()
}
fun installedSize(root: File): Long =
if (installed(root)) entries(root).filter { it.kind == 'N' && it.type == 'F' }.sumOf { it.size } else 0L
fun prepareInstall(root: File) {
val live = File(root, STATUS)
val before = File(root, STATUS_BEFORE)
if (!before.exists() && live.isFile) Files.copy(live.toPath(), before.toPath(), StandardCopyOption.COPY_ATTRIBUTES)
}
fun finishInstall(root: File) {
for (entry in entries(root).filter { it.kind == 'R' }.sortedByDescending { it.path.length }) {
val file = inside(root, entry.path) ?: continue
if (entry.type == 'D') file.delete() else Files.deleteIfExists(file.toPath())
}
val live = File(root, STATUS)
val packStatus = File(root, PACK_STATUS)
if (live.isFile && !packStatus.exists()) Files.copy(live.toPath(), packStatus.toPath())
val before = File(root, STATUS_BEFORE)
val runtime = File(File(root, ORIGINALS), STATUS)
if (before.isFile && runtime.isFile && live.isFile) {
writeStatus(live, mergeStatus(runtime.readText(), packStatus.readText(), before.readText()))
}
Files.deleteIfExists(before.toPath())
}
internal fun mergeStatus(base: String, target: String, mine: String): String {
val from = stanzas(base)
val into = LinkedHashMap(stanzas(target))
val kept = stanzas(mine)
for ((key, stanza) in kept) {
if (from[key] != stanza && into[key] == from[key]) into[key] = stanza
}
for (key in from.keys) {
if (key !in kept && into[key] == from[key]) into.remove(key)
}
return into.values.joinToString("") { it + "\n\n" }
}
private fun stanzas(text: String): Map<String, String> {
val out = LinkedHashMap<String, String>()
for (stanza in text.split(Regex("\n[ \t]*\n")).map { it.trim('\n') }.filter { it.isNotBlank() }) {
val fields = stanza.lines()
fun field(name: String) = fields.firstOrNull { it.startsWith("$name:") }?.substringAfter(':')?.trim().orEmpty()
out["${field("Package")}:${field("Architecture")}"] = stanza
}
return out
}
private fun writeStatus(file: File, text: String) {
val part = LinuxRuntimeInstaller.partFile(file).toPath()
Files.deleteIfExists(part)
Files.copy(file.toPath(), part, StandardCopyOption.COPY_ATTRIBUTES)
Files.write(part, text.toByteArray(), java.nio.file.StandardOpenOption.TRUNCATE_EXISTING)
Files.move(part, file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
}
fun remove(root: File, progress: (Int) -> Unit = {}): Result {
val entries = entries(root)
var removed = 0
var restored = 0
var kept = 0
val originals = File(root, ORIGINALS)
val live = File(root, STATUS)
val userStatus = if (live.isFile) live.readText() else null
for (entry in entries.filter { it.kind == 'C' || it.kind == 'R' }) {
val file = inside(root, entry.path) ?: continue
if (entry.type == 'D') {
file.mkdirs()
continue
}
if (entry.kind == 'C' && !entry.path.startsWith("var/lib/dpkg/") && !matchesOrMissing(file, entry)) {
kept++
continue
}
val source = inside(originals, entry.path) ?: continue
val sourcePath = source.toPath()
if (!Files.exists(sourcePath, LinkOption.NOFOLLOW_LINKS)) continue
file.parentFile?.mkdirs()
val part = LinuxRuntimeInstaller.partFile(file).toPath()
Files.deleteIfExists(part)
if (Files.isSymbolicLink(sourcePath)) Files.createSymbolicLink(part, Files.readSymbolicLink(sourcePath))
else Files.copy(sourcePath, part, StandardCopyOption.COPY_ATTRIBUTES)
if (Files.isDirectory(file.toPath(), LinkOption.NOFOLLOW_LINKS)) FileUtils.delete(file)
Files.move(part, file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
restored++
}
val added = entries.filter { it.kind == 'N' }
val directories = ArrayList<File>()
added.forEachIndexed { index, entry ->
val file = inside(root, entry.path)
when {
file == null -> kept++
entry.type == 'D' -> directories += file
matches(file, entry) -> { Files.deleteIfExists(file.toPath()); removed++ }
Files.exists(file.toPath(), LinkOption.NOFOLLOW_LINKS) -> kept++
}
if (index % 2000 == 0) progress(index * 100 / added.size.coerceAtLeast(1))
}
for (dir in directories.sortedByDescending { it.path.length }) {
if (Files.isDirectory(dir.toPath(), LinkOption.NOFOLLOW_LINKS) && dir.list()?.isEmpty() == true) dir.delete()
}
val packStatus = File(root, PACK_STATUS)
if (userStatus != null && packStatus.isFile && live.isFile) {
writeStatus(live, mergeStatus(packStatus.readText(), live.readText(), userStatus))
}
FileUtils.delete(File(root, META))
return Result(removed, restored, kept)
}
private fun matchesOrMissing(file: File, entry: Entry) =
!Files.exists(file.toPath(), LinkOption.NOFOLLOW_LINKS) || matches(file, entry)
private fun matches(file: File, entry: Entry): Boolean {
val path = file.toPath()
return when (entry.type) {
'L' -> Files.isSymbolicLink(path) && Files.readSymbolicLink(path).toString() == entry.value
'F' -> Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) && file.length() == entry.size &&
Hashes.sha256(file).equals(entry.value, ignoreCase = true)
else -> false
}
}
internal fun inside(root: File, path: String): File? {
if (path.isEmpty() || path.startsWith("/")) return null
val normal = Paths.get(path).normalize()
if (normal.toString().isEmpty() || normal.startsWith("..")) return null
val parent = normal.parent
val dir = if (parent == null) root else com.droiddeck.launcher.core.ArchivePaths.inside(root, parent.toString()) ?: return null
return File(dir, normal.fileName.toString())
}
}
@@ -18,8 +18,11 @@ internal object DesktopRemoval {
private fun protected(context: Context, root: File) =
DesktopFileRemoval.runtimeFiles(root) + lines(context, "emulators-keep.txt.gzip")
fun installedSize(context: Context): Long =
lines(context, "kde-remove.tsv.gzip").sumOf { line -> line.split('\t').getOrNull(1)?.toLongOrNull() ?: 0L }
fun installedSize(context: Context): Long {
val root = LinuxRuntime.rootDir(context)
if (DesktopPack.info(root) != null) return DesktopPack.installedSize(root)
return lines(context, "kde-remove.tsv.gzip").sumOf { line -> line.split('\t').getOrNull(1)?.toLongOrNull() ?: 0L }
}
fun cleanLegacy(context: Context, listener: LinuxRuntimeInstaller.ProgressListener? = null) {
val root = LinuxRuntime.rootDir(context)
@@ -40,8 +43,12 @@ internal object DesktopRemoval {
Log.i("DesktopRemoval", "LXQt: $result")
}
fun remove(context: Context, listener: LinuxRuntimeInstaller.ProgressListener): String? = try {
fun remove(context: Context, listener: LinuxRuntimeInstaller.ProgressListener): String? {
val root = LinuxRuntime.rootDir(context)
return if (DesktopPack.info(root) != null) removePack(context, root, listener) else removeLegacy(context, root, listener)
}
private fun removeLegacy(context: Context, root: File, listener: LinuxRuntimeInstaller.ProgressListener): String? = try {
val pending = File(root, PENDING)
val marker = File(root, ".droiddeck-pkg-${DesktopCatalog.DESKTOP_ID}")
val installing = DesktopCatalog.interrupted(root).firstOrNull { it.id == DesktopCatalog.DESKTOP_ID }
@@ -50,12 +57,14 @@ internal object DesktopRemoval {
check(version in versions && (installing == null || installing.version in versions)) { context.getString(R.string.desktop_removal_unknown) }
val entries = lines(context, "kde-remove.tsv.gzip").map(DesktopFileRemoval.Entry::parse)
val keep = protected(context, root)
val records = DesktopFileRemoval.desktopRecords(root)
cleanLegacy(context, listener)
FileUtils.writeString(pending, version!!)
check(FileUtils.readString(pending)?.trim() == version) { "Could not reserve desktop removal" }
if (marker.exists() && !marker.delete()) error("Could not clear desktop marker")
val removing = context.getString(R.string.desktop_removing)
val result = DesktopFileRemoval.remove(root, entries, keep) { listener.onProgress(removing, it) }
DesktopFileRemoval.removeRecords(root, records)
for ((asset, path) in com.droiddeck.launcher.session.SessionFiles.DESKTOP_FILES) {
val target = DesktopFileRemoval.safeFile(root, path) ?: continue
if (!isRegularFile(target)) continue
@@ -74,5 +83,29 @@ internal object DesktopRemoval {
e.message ?: context.getString(R.string.deskpkg_install_failed)
}
private fun removePack(context: Context, root: File, listener: LinuxRuntimeInstaller.ProgressListener): String? = try {
val pending = File(root, PENDING)
val marker = File(root, ".droiddeck-pkg-${DesktopCatalog.DESKTOP_ID}")
FileUtils.writeString(pending, DesktopPack.info(root)!!.tag)
check(pending.isFile) { "Could not reserve desktop removal" }
if (marker.exists() && !marker.delete()) error("Could not clear desktop marker")
val removing = context.getString(R.string.desktop_removing)
for ((_, path) in com.droiddeck.launcher.session.SessionFiles.DESKTOP_FILES) {
DesktopFileRemoval.safeFile(root, path)?.takeIf { isRegularFile(it) }?.delete()
}
for (path in DESKTOP_STATE) DesktopPack.inside(root, path)?.let(FileUtils::delete)
val result = if (DesktopPack.installed(root)) DesktopPack.remove(root) { listener.onProgress(removing, it) } else null
DesktopCatalog.discardDesktopInstall(context)
if (!pending.delete()) error("Could not finish desktop removal")
Log.i("DesktopRemoval", "pack: $result")
listener.onProgress(context.getString(R.string.desktop_removed), 100)
null
} catch (e: Exception) {
Log.e("DesktopRemoval", "remove", e)
e.message ?: context.getString(R.string.deskpkg_install_failed)
}
private val DESKTOP_STATE = listOf("var/lib/PackageKit", "var/cache/swcatalog")
private fun isRegularFile(file: File) = java.nio.file.Files.isRegularFile(file.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)
}
@@ -43,7 +43,7 @@ object GuestCommand {
val fastPathKey = if (fastPath && !fakeRoot && linkDir == null && ProotFastPath.enabled(context)) ProotFastPath.key(root, binds) else null
cmd += listOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "LANG=C.UTF-8",
"PATH=/usr/local/bin:/usr/bin:/bin", "XDG_RUNTIME_DIR=${LinuxRuntime.GUEST_RUNTIME_DIR}",
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games", "XDG_RUNTIME_DIR=${LinuxRuntime.GUEST_RUNTIME_DIR}",
"XDG_DATA_HOME=/root/.local/share", "FLATPAK_BWRAP=${FlatpakManager.BWRAP}",
"DROIDDECK_BWRAP_SOCKET=${BwrapSpawner.socket(context)}",
"XDG_DATA_DIRS=/root/.local/share/flatpak/exports/share:/usr/local/share:/usr/share",
@@ -115,7 +115,7 @@ public final class LinuxRuntime {
public static boolean isInstalled(Context context) {
if (LinuxRuntimeInstaller.isRemoving() || LinuxRuntimeInstaller.hasRemovalPending(context)) return false;
File root = rootDir(context);
return new File(root, "usr/bin/gamescope").isFile()
return (new File(root, "usr/bin/gamescope").isFile() || new File(root, "usr/games/gamescope").isFile())
&& (new File(root, SESSION_SCRIPT.substring(1)).isFile()
|| new File(root, LegacyNames.SESSION_SCRIPT.substring(1)).isFile())
&& (patchedProot(context) || rootfsProotReady(context));
@@ -341,9 +341,9 @@ public final class LinuxRuntime {
}
public static String cpuTempSource() {
for (java.util.Map.Entry<String, File> e : new java.util.TreeMap<>(thermalZones()).entrySet()) {
File temp = new File(e.getValue(), "temp");
if (e.getKey().contains("cpu") && !e.getKey().contains("gpu") && temp.canRead()) return temp.getPath();
for (File zone : cpuTempZones()) {
File temp = new File(zone, "temp");
if (temp.canRead()) return temp.getPath();
}
return null;
}
@@ -353,7 +353,7 @@ public final class LinuxRuntime {
return firstReadable(kgsl + "temp", kgsl + "devfreq/temp", thermalZone("gpu"));
}
private static String gpuLoadSource() {
public static String gpuLoadSource() {
String kgsl = "/sys/class/kgsl/kgsl-3d0/";
return firstReadable(kgsl + "gpu_busy_percentage", kgsl + "devfreq/gpu_load");
}
@@ -367,7 +367,7 @@ public final class LinuxRuntime {
"/sys/devices/platform/soc@0/3d00000.gpu/devfreq/3d00000.gpu/cur_freq"},
{gpuTemp, "/sys/class/thermal/thermal_zone28/temp"},
{gpuTemp, "/sys/class/thermal/thermal_zone26/temp"},
{thermalZone("ddr"), "/sys/class/thermal/thermal_zone22/temp"},
{ddrTempSource(), "/sys/class/thermal/thermal_zone22/temp"},
};
for (String[] stat : stats) {
boolean fed = false;
@@ -384,6 +384,36 @@ public final class LinuxRuntime {
return path != null ? path : "none";
}
private static String ddrTempSource() {
return thermalZone("ddr");
}
// MangoHud reads the GPU and DDR temperatures from these zone numbers (bindAdrenoStats). On phones
// where they are CPU zones, their type follows the temperature put there, so they stay out of the
// CPU average.
private static java.util.Map<String, String> replacedZoneTypes() {
java.util.Map<String, String> replaced = new java.util.HashMap<>();
if (gpuTempSource() != null) {
replaced.put("thermal_zone28", "gpu-thermal");
replaced.put("thermal_zone26", "gpu-thermal");
}
if (ddrTempSource() != null) replaced.put("thermal_zone22", "ddr-thermal");
return replaced;
}
/** The zones the session's MangoHud averages for the CPU temperature (all typed cpuN-thermal there). */
public static List<File> cpuTempZones() {
java.util.Map<String, String> replaced = replacedZoneTypes();
List<File> zones = new ArrayList<>();
for (java.util.Map.Entry<String, File> zone : new java.util.TreeMap<>(thermalZones()).entrySet()) {
String type = zone.getKey();
if (type.contains("cpu") && !type.contains("gpu") && !replaced.containsKey(zone.getValue().getName())) {
zones.add(zone.getValue());
}
}
return zones;
}
private static void bindCpuTemps(List<String> cmd, File root) {
File name = new File(root, "etc/droiddeck/cpu-thermal-type");
try {
@@ -391,9 +421,18 @@ public final class LinuxRuntime {
} catch (IOException e) {
return;
}
java.util.Map<String, String> replaced = replacedZoneTypes();
for (java.util.Map.Entry<String, File> zone : thermalZones().entrySet()) {
String type = zone.getKey();
if (type.contains("cpu") && !type.contains("gpu") && !type.matches("cpu\\d-(top-)?thermal")) {
String other = replaced.get(zone.getValue().getName());
if (other != null) {
File typeFile = new File(root, "etc/droiddeck/" + other + "-type");
try {
if (!typeFile.isFile()) Files.write(typeFile.toPath(), (other + "\n").getBytes(StandardCharsets.US_ASCII));
bind(cmd, typeFile.getPath() + ":" + new File(zone.getValue(), "type").getPath());
} catch (IOException ignored) {
}
} else if (type.contains("cpu") && !type.contains("gpu") && !type.matches("cpu\\d-(top-)?thermal")) {
bind(cmd, name.getPath() + ":" + new File(zone.getValue(), "type").getPath());
}
}
@@ -448,12 +487,72 @@ public final class LinuxRuntime {
+ "\\" + host.version + "\\" + host.machine + "\\localdomain\\-1\\";
}
public static void writeAccounts(Context context) throws IOException {
public static synchronized void writeAccounts(Context context) throws IOException {
File root = rootDir(context);
int uid = Process.myUid();
Files.write(new File(root, "etc/passwd").toPath(),
("root:x:" + uid + ":" + uid + ":root:/root:/bin/bash\n").getBytes(StandardCharsets.UTF_8));
Files.write(new File(root, "etc/group").toPath(),
("root:x:" + uid + ":\n").getBytes(StandardCharsets.UTF_8));
mergeAccounts(new File(root, "etc/passwd"), 2,
"root:x:" + uid + ":" + uid + ":root:/root:/bin/bash", "root:x:0:0:root:/root:/bin/bash", uid);
mergeAccounts(new File(root, "etc/group"), 2,
"root:x:" + uid + ":", "root:x:0:", uid);
File group = new File(root, "etc/group");
String groups = new String(Files.readAllBytes(group.toPath()), StandardCharsets.UTF_8);
writeIfChanged(group, groups, withStorageGroups(groups));
}
private static final String[][] STORAGE_GROUPS = {
{"sdcard_rw", "1015"}, {"media_rw", "1023"}, {"everybody", "9997"}};
static String withStorageGroups(String groups) {
StringBuilder out = new StringBuilder();
List<String> present = new ArrayList<>();
for (String line : groups.split("\n")) {
if (line.trim().isEmpty()) continue;
String[] fields = line.split(":", -1);
if (fields.length >= 4) {
for (String[] storage : STORAGE_GROUPS) {
if (fields[0].equals(storage[0])) present.add(storage[0]);
if (!fields[2].equals(storage[1])) continue;
present.add(storage[0]);
if (!java.util.Arrays.asList(fields[3].split(",")).contains("root")) {
fields[3] = fields[3].isEmpty() ? "root" : fields[3] + ",root";
line = String.join(":", fields);
}
}
}
out.append(line).append('\n');
}
for (String[] storage : STORAGE_GROUPS) {
if (!present.contains(storage[0])) {
out.append(storage[0]).append(":x:").append(storage[1]).append(":root\n");
}
}
return out.toString();
}
static String mergedAccounts(String existing, int idField, String own, String zero, int uid) {
StringBuilder out = new StringBuilder(own).append('\n').append(zero).append('\n');
if (existing == null) return out.toString();
String ownId = Integer.toString(uid);
for (String line : existing.split("\n")) {
if (line.trim().isEmpty()) continue;
String[] fields = line.split(":", -1);
if (fields.length <= idField) continue;
if (fields[0].equals("root") || fields[idField].equals("0") || fields[idField].equals(ownId)) continue;
out.append(line).append('\n');
}
return out.toString();
}
private static void mergeAccounts(File file, int idField, String own, String zero, int uid) throws IOException {
String existing = file.isFile() ? new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8) : null;
writeIfChanged(file, existing, mergedAccounts(existing, idField, own, zero, uid));
}
private static void writeIfChanged(File file, String existing, String merged) throws IOException {
if (merged.equals(existing)) return;
File staged = File.createTempFile(file.getName(), ".staged", file.getParentFile());
Files.write(staged.toPath(), merged.getBytes(StandardCharsets.UTF_8));
Files.move(staged.toPath(), file.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING,
java.nio.file.StandardCopyOption.ATOMIC_MOVE);
}
}
@@ -35,7 +35,7 @@ public final class LinuxRuntimeInstaller {
private static final String TAG = "LinuxRuntimeInstaller";
public static final String CATALOG_URL =
"https://raw.githubusercontent.com/Droid-Deck/DroidDeck-Components/main/linuxfs.json";
"https://raw.githubusercontent.com/Droid-Deck/DroidDeck-Components/main/linuxfs-ubuntu.json";
private static final String VERSION_FILE = ".version";
@@ -88,8 +88,20 @@ public final class LinuxRuntimeInstaller {
return v == null ? null : v.trim();
}
private static String catalogUrl() {
if (!com.droiddeck.launcher.BuildConfig.DEBUG) return CATALOG_URL;
try {
Object value = Class.forName("android.os.SystemProperties").getMethod("get", String.class)
.invoke(null, "debug.droiddeck.linuxfs");
if (value instanceof String && ((String) value).startsWith("http")) return (String) value;
} catch (ReflectiveOperationException e) {
Log.w(TAG, "catalog override: " + e);
}
return CATALOG_URL;
}
public static Release fetchRelease() {
String body = Downloader.downloadString(CATALOG_URL);
String body = Downloader.downloadString(catalogUrl());
if (body == null || body.isEmpty()) return null;
try {
JSONObject json = new JSONObject(body);
@@ -292,7 +304,7 @@ public final class LinuxRuntimeInstaller {
recoverInterruptedSwap(root, staging, old);
if (!discard(staging, null) || !staging.mkdirs()) return false;
if (listener != null) listener.onProgress(context.getString(R.string.rtinst_extracting), -1);
if (!extract(context, archive, staging, listener)) {
if (!extract(context, archive, staging, root, listener)) {
RuntimeFileTree.delete(staging, null);
return false;
}
@@ -346,7 +358,11 @@ public final class LinuxRuntimeInstaller {
return false;
}
new File(root, CARRY_MARKER).delete();
try { RuntimeFileTree.dropStaleState(root); }
catch (IOException e) { Log.w(TAG, "could not clear caches left by the previous runtime", e); }
discard(old, null);
try { com.droiddeck.launcher.session.SessionFiles.INSTANCE.stage(context, root, false); }
catch (Exception e) { Log.w(TAG, "could not stage the session files into the new runtime", e); }
return LinuxRuntime.isInstalled(context);
} catch (Exception e) {
Log.e(TAG, "install", e);
@@ -513,6 +529,10 @@ public final class LinuxRuntimeInstaller {
// Packages extract over the live runtime and their archives list a link before the file it
// names, so a kill mid-way must leave neither a truncated file nor a link to a missing one.
public static boolean extract(Context context, File archive, File destination, ProgressListener listener) {
return extract(context, archive, destination, destination, listener);
}
static boolean extract(Context context, File archive, File destination, File linkRoot, ProgressListener listener) {
long entries = 0;
String extracting = context.getString(R.string.rtinst_extracting);
java.util.LinkedHashMap<File, String> links = new java.util.LinkedHashMap<>();
@@ -537,7 +557,7 @@ public final class LinuxRuntimeInstaller {
links.remove(file);
links.put(file, entry.getLinkName());
} else if (entry.isLink()) {
File target = ArchivePaths.inside(destination, entry.getLinkName());
File target = hardLinkTarget(destination, entry.getLinkName());
if (target == null) {
Log.w(TAG, "skipping hard link outside the rootfs: " + entry.getLinkName());
continue;
@@ -548,11 +568,11 @@ public final class LinuxRuntimeInstaller {
try {
Files.createLink(part.toPath(), target.toPath());
} catch (IOException | UnsupportedOperationException e) {
if (target.isFile()) {
if (!l2sLink(target, part, destination, linkRoot) && target.isFile()) {
Files.copy(target.toPath(), part.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
if (part.exists()) place(part, file);
if (Files.exists(part.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)) place(part, file);
} else if (entry.isFile()) {
links.remove(file);
File part = partFile(file);
@@ -589,6 +609,67 @@ public final class LinuxRuntimeInstaller {
}
}
static File hardLinkTarget(File destination, String name) throws IOException {
java.nio.file.Path path = java.nio.file.Paths.get(name).normalize();
java.nio.file.Path last = path.getFileName();
if (last == null || last.toString().isEmpty() || last.toString().equals("..")) return null;
java.nio.file.Path parent = path.getParent();
File dir = parent == null ? destination : ArchivePaths.inside(destination, parent.toString());
return dir == null ? null : new File(dir, last.toString());
}
private static final String L2S = ".l2s.";
static boolean l2sLink(File target, File link) {
return l2sLink(target, link, null, null);
}
static boolean l2sLink(File target, File link, File tree, File linkTree) {
java.nio.file.Path here = tree == null ? null : tree.toPath().toAbsolutePath().normalize();
java.nio.file.Path there = linkTree == null ? here : linkTree.toPath().toAbsolutePath().normalize();
java.util.function.UnaryOperator<java.nio.file.Path> shown = path -> {
java.nio.file.Path p = path.toAbsolutePath().normalize();
return here == null || !p.startsWith(here) ? p : there.resolve(here.relativize(p));
};
java.util.function.UnaryOperator<java.nio.file.Path> actual = path -> {
java.nio.file.Path p = path.toAbsolutePath().normalize();
return there == null || !p.startsWith(there) ? p : here.resolve(there.relativize(p));
};
try {
java.nio.file.Path original = target.toPath().toAbsolutePath().normalize();
java.nio.file.Path intermediate;
if (Files.isSymbolicLink(original)) {
intermediate = actual.apply(Files.readSymbolicLink(original));
if (!intermediate.getFileName().toString().startsWith(L2S) || !Files.isSymbolicLink(intermediate)) return false;
java.nio.file.Path fin = actual.apply(Files.readSymbolicLink(intermediate));
String name = fin.getFileName().toString();
int count = Integer.parseInt(name.substring(name.length() - 4)) + 1;
java.nio.file.Path next = fin.resolveSibling(name.substring(0, name.length() - 4) + String.format(java.util.Locale.ROOT, "%04d", count));
Files.move(fin, next, StandardCopyOption.ATOMIC_MOVE);
Files.delete(intermediate);
Files.createSymbolicLink(intermediate, shown.apply(next));
} else {
if (!Files.isRegularFile(original, java.nio.file.LinkOption.NOFOLLOW_LINKS)) return false;
java.nio.file.Path dir = original.getParent();
String base = L2S + original.getFileName();
int suffix = 1;
do {
intermediate = dir.resolve(base + String.format(java.util.Locale.ROOT, "%04d", suffix++));
} while (Files.exists(intermediate, java.nio.file.LinkOption.NOFOLLOW_LINKS) && suffix < 1000);
java.nio.file.Path fin = dir.resolve(intermediate.getFileName() + ".0002");
Files.move(original, fin, StandardCopyOption.ATOMIC_MOVE);
Files.createSymbolicLink(intermediate, shown.apply(fin));
Files.createSymbolicLink(original, shown.apply(intermediate));
}
Files.deleteIfExists(link.toPath());
Files.createSymbolicLink(link.toPath(), shown.apply(intermediate));
return true;
} catch (IOException | RuntimeException e) {
Log.w(TAG, "l2s link " + link + " -> " + target + ": " + e);
return false;
}
}
static File partFile(File file) {
return new File(file.getParentFile(), ".dd-part-" + Integer.toHexString(file.getName().hashCode()));
}
@@ -1,6 +1,7 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.os.Build
import android.util.Log
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
@@ -37,9 +38,10 @@ object ProotFastPath {
fun hostEnv(key: String): Pair<String, String> = "PROOT_FASTPATH" to key
fun guestEnv(root: File, binds: List<String>, key: String): List<String> = listOf(
fun guestEnv(root: File, binds: List<String>, key: String, sdk: Int = Build.VERSION.SDK_INT): List<String> = listOf(
"PROOT_FP_ROOT=" + root.path,
"PROOT_FP_BINDS=" + binds.joinToString("|"),
"PROOT_FP_KEY=$key",
"PROOT_FP_ANDROID_API=$sdk",
)
}
@@ -0,0 +1,201 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.net.LocalServerSocket
import android.net.LocalSocket
import android.os.ParcelFileDescriptor
import android.os.Process
import android.util.Log
import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.session.OrphanReaper
import com.droiddeck.launcher.session.SessionPrefs
import org.json.JSONObject
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.File
import java.io.FileDescriptor
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.concurrent.atomic.AtomicInteger
object RootSpawner {
private const val TAG = "RootSpawner"
fun socket(context: Context): String = "${context.packageName}.root"
private val seq = AtomicInteger()
@Volatile private var server: LocalServerSocket? = null
@Synchronized
fun start(context: Context) {
if (server != null) return
val app = context.applicationContext
val name = socket(app)
val socket = try {
LocalServerSocket(name)
} catch (e: IOException) {
Log.e(TAG, "cannot listen on $name", e)
return
}
server = socket
Thread({
while (true) {
val client = try { socket.accept() } catch (e: IOException) { Log.e(TAG, "accept", e); break }
Thread({ serve(app, client) }, "root-${seq.get() + 1}").apply { isDaemon = true; start() }
}
}, "root-server").apply { isDaemon = true; start() }
}
private fun serve(context: Context, client: LocalSocket) {
val id = seq.incrementAndGet()
val received = ArrayList<FileDescriptor>()
client.use {
val out = DataOutputStream(client.outputStream)
try {
if (client.peerCredentials.uid != Process.myUid()) {
Log.w(TAG, "refused root for uid ${client.peerCredentials.uid}")
return
}
val input = DataInputStream(client.inputStream)
val kind = input.readUnsignedByte()
client.ancillaryFileDescriptors?.let { received.addAll(it) }
val body = ByteArray(input.readInt()).also { input.readFully(it) }
client.ancillaryFileDescriptors?.let { received.addAll(it) }
if (kind != 'R'.code) return
run(context, JSONObject(String(body, Charsets.UTF_8)), received, client, input, out, id)
} catch (e: Exception) {
Log.e(TAG, "root $id", e)
runCatching {
frame(out, 'E', (e.message ?: e.toString()).toByteArray())
frame(out, 'X', "1".toByteArray())
}
} finally {
received.forEach { fd -> runCatching { android.system.Os.close(fd) } }
}
}
}
private class Stdio(val redirect: ProcessBuilder.Redirect?, val fd: FileDescriptor?, val dup: ParcelFileDescriptor?)
private fun stdio(fd: FileDescriptor?, write: Boolean): Stdio {
if (fd == null) return Stdio(null, null, null)
val dup = try { ParcelFileDescriptor.dup(fd) } catch (e: IOException) { return Stdio(null, fd, null) }
val path = File("/proc/self/fd/${dup.fd}")
val opens = try {
if (write) FileOutputStream(path, true).close() else FileInputStream(path).close()
true
} catch (e: IOException) { false }
if (!opens) return Stdio(null, fd, dup)
val redirect = if (write) ProcessBuilder.Redirect.appendTo(path) else ProcessBuilder.Redirect.from(path)
return Stdio(redirect, fd, dup)
}
private fun pump(from: InputStream, to: OutputStream, name: String) =
Thread({
val buffer = ByteArray(16384)
try {
while (true) {
val n = from.read(buffer)
if (n < 0) break
to.write(buffer, 0, n)
to.flush()
}
} catch (e: IOException) {
} finally {
runCatching { to.close() }
}
}, name).apply { isDaemon = true; start() }
private fun run(context: Context, request: JSONObject, fds: List<FileDescriptor>, client: LocalSocket,
input: DataInputStream, out: DataOutputStream, id: Int) {
val root = LinuxRuntime.rootDir(context)
val argv = request.getJSONArray("argv").let { a -> (0 until a.length()).map { a.getString(it) } }
if (argv.isEmpty()) throw IOException("no command")
val cwd = request.optString("cwd", "/root").ifEmpty { "/root" }
val cmd = LinuxRuntime.prootPrefix(context, root, cwd, true)
cmd.add(1, "--link2symlink")
LinuxRuntime.lastBinds(context).filterNot { it.startsWith("/proc/self/fd/") }.forEach { cmd.add("-b"); cmd.add(it) }
cmd.add("/usr/bin/env")
cmd.add("-i")
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> cmd.add("$k=${e.getString(k)}") } }
cmd.addAll(argv)
val builder = ProcessBuilder(cmd).directory(root)
builder.environment().apply {
clear()
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
val streams = listOf(stdio(fds.getOrNull(0), false), stdio(fds.getOrNull(1), true), stdio(fds.getOrNull(2), true))
try {
builder.redirectInput(streams[0].redirect ?: ProcessBuilder.Redirect.PIPE)
builder.redirectOutput(streams[1].redirect ?: ProcessBuilder.Redirect.PIPE)
builder.redirectError(streams[2].redirect ?: ProcessBuilder.Redirect.PIPE)
val process = builder.start()
val pid = HostProcess.pidOf(process)
OrphanReaper.keep(pid)
Log.i(TAG, "root $id pid $pid: ${argv.joinToString(" ")}")
synchronized(out) { frame(out, 'P', pid.toString().toByteArray()) }
val pumps = ArrayList<Thread>()
if (streams[0].redirect == null) {
val fd = streams[0].fd
if (fd != null) pumps.add(pump(FileInputStream(fd), process.outputStream, "root-$id-in").also { it.isDaemon = true })
else runCatching { process.outputStream.close() }
}
if (streams[1].redirect == null) pumps.add(pump(process.inputStream,
streams[1].fd?.let { FileOutputStream(it) } ?: OutputStream.nullOutputStream(), "root-$id-out"))
if (streams[2].redirect == null) pumps.add(pump(process.errorStream,
streams[2].fd?.let { FileOutputStream(it) } ?: OutputStream.nullOutputStream(), "root-$id-err"))
Thread({
try {
while (true) {
val kind = input.readUnsignedByte()
val body = ByteArray(input.readInt()).also { input.readFully(it) }
if (kind == 'S'.code) String(body).trim().toIntOrNull()?.let { signal(pid, it) }
}
} catch (e: IOException) {
}
if (process.isAlive) {
Log.i(TAG, "root $id: its caller is gone; stopping it")
signal(pid, android.system.OsConstants.SIGHUP)
android.os.Process.sendSignal(pid, android.system.OsConstants.SIGQUIT)
}
}, "root-$id-watch").apply { isDaemon = true; start() }
val status = process.waitFor()
pumps.filter { it.name.endsWith("-out") || it.name.endsWith("-err") }.forEach { it.join(2000) }
OrphanReaper.release(pid)
Log.i(TAG, "root $id exited $status")
runCatching { synchronized(out) { frame(out, 'X', status.toString().toByteArray()) } }
} finally {
streams.forEach { s -> runCatching { s.dup?.close() } }
}
}
private fun signal(top: Int, signal: Int) {
val parents = HashMap<Int, Int>()
File("/proc").listFiles()?.forEach { dir ->
val pid = dir.name.toIntOrNull() ?: return@forEach
val stat = try { File(dir, "stat").readText() } catch (e: IOException) { return@forEach }
val fields = stat.substringAfterLast(')').trim().split(' ')
fields.getOrNull(1)?.toIntOrNull()?.let { parents[pid] = it }
}
val tree = HashSet<Int>()
var grew = true
while (grew) {
grew = false
for ((pid, parent) in parents) {
if (pid !in tree && (parent == top || parent in tree)) { tree.add(pid); grew = true }
}
}
tree.forEach { runCatching { android.os.Process.sendSignal(it, signal) } }
}
private fun frame(out: DataOutputStream, kind: Char, payload: ByteArray) {
out.writeByte(kind.code)
out.writeInt(payload.size)
out.write(payload)
out.flush()
}
}
@@ -0,0 +1,30 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import com.droiddeck.launcher.BuildConfig
object RuntimeAutoUpdate {
private const val PREFS = "runtime-auto-update"
const val MAX_ATTEMPTS = 3
const val RETRY_MS = 10 * 60_000L
fun due(installed: String?, release: String?, attempts: Int, lastAt: Long = 0L, now: Long = lastAt + RETRY_MS): Boolean =
installed != null && !release.isNullOrEmpty() && release != installed && attempts < MAX_ATTEMPTS &&
(attempts == 0 || now - lastAt !in 0 until RETRY_MS)
fun key(appVersion: Int, release: String) = "$appVersion:$release"
fun claim(context: Context, installed: String?, release: String?, now: Long = System.currentTimeMillis()): Boolean {
if (release.isNullOrEmpty()) return false
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val key = key(BuildConfig.VERSION_CODE, release)
synchronized(this) {
val attempts = prefs.getInt(key, 0)
if (!due(installed, release, attempts, prefs.getLong("$key@at", 0L), now)) return false
val edit = prefs.edit()
prefs.all.keys.filterNot { it.startsWith("${BuildConfig.VERSION_CODE}:") }.forEach { edit.remove(it) }
edit.putInt(key, attempts + 1).putLong("$key@at", now).apply()
return true
}
}
}
@@ -80,7 +80,7 @@ public final class RuntimeFileTree {
* be carried.
*/
static java.util.List<String> userPaths(File tree) throws IOException {
java.util.List<String> paths = new java.util.ArrayList<>(java.util.Arrays.asList("root", "opt/appimages/user", "opt/droiddeck-apps"));
java.util.List<String> paths = new java.util.ArrayList<>(java.util.Arrays.asList("root", "opt/appimages/user", "opt/droiddeck-apps", "opt/droiddeck/wincomponents"));
for (String n : children(new File(tree, "usr/local/share/applications"))) {
if (n.endsWith(".desktop") && (n.startsWith("droiddeck-app-") || n.startsWith("droiddeck-appimage-")))
paths.add("usr/local/share/applications/" + n);
@@ -109,10 +109,39 @@ public final class RuntimeFileTree {
static java.util.List<String> existingUserPaths(File from, File to) throws IOException {
java.util.List<String> paths = new java.util.ArrayList<>();
for (String rel : userPaths(from, to)) if (exists(safePath(from, rel).toPath())) paths.add(rel);
for (String rel : userPaths(from, to)) {
if (!exists(safePath(from, rel).toPath())) continue;
if (rel.startsWith("usr/share/applications/") && exists(safePath(to, rel).toPath())) continue;
paths.add(rel);
}
return paths;
}
private static final String[] STALE_HOME_STATE = {
".local/share/droiddeck/pacman", ".cache/droiddeck/pacman-restore.log",
".cache/appstream", ".cache/discover", ".cache/fontconfig", ".cache/kwin", ".cache/ksplash",
".cache/ksvg-elements", ".cache/plasmashell", ".cache/kwinsession.kcache", ".cache/icon-cache.kcache",
};
private static final String[] STALE_HOME_CACHE_PREFIXES = {
"mesa_shader_cache", "ksycoca", "plasma_theme_", "qtshadercache", "event-sound-cache.tdb.",
};
static void dropStaleState(File runtimeRoot) throws IOException {
File home = new File(runtimeRoot, "root");
java.util.List<String> stale = new java.util.ArrayList<>(java.util.Arrays.asList(STALE_HOME_STATE));
for (String n : children(new File(home, ".cache"))) {
for (String prefix : STALE_HOME_CACHE_PREFIXES) {
if (n.startsWith(prefix)) { stale.add(".cache/" + n); break; }
}
}
IOException failed = null;
for (String rel : stale) {
try { delete(safePath(home, rel), null); }
catch (IOException e) { if (failed == null) failed = e; else failed.addSuppressed(e); }
}
if (failed != null) throw failed;
}
private static java.util.List<String> children(File dir) throws IOException {
java.util.List<String> names = new java.util.ArrayList<>();
try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir.toPath())) {
@@ -11,14 +11,15 @@ object RuntimeHealth {
fun brokenLibraryLinks(context: Context): List<String> = brokenLibraryLinks(LinuxRuntime.rootDir(context))
/** A complete runtime has no library link in usr/lib whose target is missing. */
fun brokenLibraryLinks(root: File): List<String> {
val lib = File(root, "usr/lib")
val names = lib.list() ?: return emptyList()
return names.sorted().filter { name ->
val path = File(lib, name).toPath()
Files.isSymbolicLink(path) && !resolves(root, path)
fun brokenLibraryLinks(root: File): List<String> =
listOf("usr/lib", "usr/lib/aarch64-linux-gnu").flatMap { dir ->
val lib = File(root, dir)
val names = lib.list() ?: return@flatMap emptyList()
names.sorted().filter { name ->
val path = File(lib, name).toPath()
Files.isSymbolicLink(path) && !resolves(root, path)
}.map { if (dir == "usr/lib") it else "aarch64-linux-gnu/$it" }
}
}
private fun resolves(root: File, link: Path): Boolean = try {
var path = link
@@ -21,7 +21,7 @@ class GpuMemComponent(private val file: File, private val root: File) : SessionP
thread = Thread({
while (running) {
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
if (running && OverlayShown.check(root)) sample()?.let { write(it) }
if (running && (OverlayShown.check(root) || com.droiddeck.launcher.hud.FusionHudHost.showing)) sample()?.let { write(it) }
}
}, "gpu-mem").apply { isDaemon = true; start() }
}
@@ -1,178 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.Lossless
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import java.util.Locale
import java.util.concurrent.atomic.AtomicInteger
class PerfHud(context: Context) {
var text by mutableStateOf("")
private set
var graph by mutableStateOf(FloatArray(0))
private set
private val context = context.applicationContext
private val frames = AtomicInteger()
private var lastTick = 0L
private var lastFps = 0f
private var running = false
private val handler = Handler(Looper.getMainLooper())
private val samples = FloatArray(GRAPH)
private var graphBase = 0L
private var graphSeen = 0L
@Volatile private var showFps = true
@Volatile private var showBattery = true
@Volatile private var showGraph = true
private val enabled: Boolean
get() = SessionPrefs.hudEnabled(context)
&& !File(Environment.getExternalStorageDirectory(), "Download/droiddeck-no-hud").exists()
private val anyPart: Boolean
get() = showFps || showBattery || showGraph
var onPresentingWindowChanged: (() -> Unit)? = null
private var lastWindow: String? = null
private val listener = object : WaylandCompositor.GameListener {
override fun onGameSurface(window: String?, gpuName: String?) {
if (window != null && window != lastWindow) {
lastWindow = window
handler.post { onPresentingWindowChanged?.invoke() }
}
}
override fun onGameFrame() {
frames.incrementAndGet()
}
}
private val tick = object : Runnable {
override fun run() {
if (!running) return
val now = SystemClock.elapsedRealtime()
val dt = (now - lastTick).coerceAtLeast(1L) / 1000f
lastTick = now
lastFps = frames.getAndSet(0) / dt
text = readout(lastFps)
if (showGraph) publishGraph() else clearGraph()
handler.postDelayed(this, TICK_MS)
}
}
fun refresh() {
readOptions()
if (!enabled || !anyPart) {
stop()
return
}
if (!running) start() else {
if (!showGraph) clearGraph() else publishGraph()
text = readout(lastFps)
}
}
fun start() {
readOptions()
if (!enabled || !anyPart || running) return
running = true
lastTick = SystemClock.elapsedRealtime()
frames.set(0)
graphBase = shownTotal()
graphSeen = graphBase
WaylandCompositor.setGameListener(listener)
handler.postDelayed(tick, TICK_MS)
}
fun stop() {
running = false
handler.removeCallbacks(tick)
WaylandCompositor.clearGameListener(listener)
text = ""
graph = FloatArray(0)
}
private fun readOptions() {
showFps = SessionPrefs.hudShowFps(context)
showBattery = SessionPrefs.hudShowBattery(context)
showGraph = SessionPrefs.hudShowGraph(context)
}
private fun readout(fpsValue: Float): String {
val parts = ArrayList<String>(2)
if (showFps) parts.add(line(fpsValue))
if (showBattery) batteryCelsius(readBatteryDeci())?.let { parts.add(it) }
return parts.joinToString("\n")
}
private fun readBatteryDeci(): Int {
val sticky = runCatching {
context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
}.getOrNull() ?: return 0
return sticky.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)
}
private fun shownTotal(): Long = try { WaylandCompositor.nativeHudFrameTimes(samples) } catch (t: Throwable) { 0L }
private fun clearGraph() {
graphBase = shownTotal()
graphSeen = graphBase
if (graph.isNotEmpty()) graph = FloatArray(0)
}
private fun publishGraph() {
val total = shownTotal()
if (total == graphSeen && graph.isNotEmpty()) return
graphSeen = total
graph = recent(samples, total, graphBase)
}
private fun line(base: Float): String {
val mode = FrameGen.mode(context)
if (mode.engine == FrameGen.ENGINE_OFF) return fps(base)
val lsfg = mode.engine == FrameGen.ENGINE_LSFG
val name = if (lsfg) "LSFG" else "DD-FG"
val label = FrameGen.label(context, mode)
if (lsfg && Lossless.cacheFile(context)?.isFile != true) return context.getString(R.string.hud_fg_needs_lossless, name)
val stats = try { WaylandCompositor.nativeFrameGenStats() } catch (t: Throwable) { null }
val problem = try { WaylandCompositor.nativeFrameGenProblem() } catch (t: Throwable) { -1 }
return when {
problem == 1 -> context.getString(R.string.hud_fg_unsupported, name)
problem == 2 -> context.getString(R.string.hud_fg_failed, name)
stats != null && stats[3] > 1f -> String.format(Locale.US, "%s %.0f → %.0f fps", label, base, stats[3])
else -> context.getString(R.string.hud_fg_starting, label, fps(base))
}
}
private fun fps(value: Float) = String.format(Locale.US, "%.0f fps", value)
companion object {
private const val TICK_MS = 1_000L
private const val GRAPH = 128
internal const val GRAPH_MAX_MS = 50f
internal fun recent(samples: FloatArray, total: Long, base: Long): FloatArray {
val filled = minOf(total, samples.size.toLong()).toInt()
val shown = minOf(filled.toLong(), (total - base).coerceAtLeast(0L)).toInt()
if (shown < 2) return FloatArray(0)
return FloatArray(shown) { samples[filled - shown + it].coerceIn(0f, GRAPH_MAX_MS) }
}
internal fun batteryCelsius(deci: Int): String? =
if (deci <= 0) null else String.format(Locale.US, "%.1f°C", deci / 10f)
}
}
@@ -25,6 +25,8 @@ object SessionFiles {
"usr/local/bin/droiddeck-gpu" to "usr/local/bin/droiddeck-gpu",
"usr/local/bin/droiddeck-desktop-gpu" to "usr/local/bin/droiddeck-desktop-gpu",
"usr/local/bin/droiddeck-desktop-window-rules" to "usr/local/bin/droiddeck-desktop-window-rules",
"usr/local/bin/droiddeck-library-perms" to "usr/local/bin/droiddeck-library-perms",
"usr/local/bin/droiddeck-ime" to "usr/local/bin/droiddeck-ime",
"usr/local/bin/kwin_wayland_wrapper" to "usr/local/bin/kwin_wayland_wrapper",
"usr/lib/firefox/defaults/pref/droiddeck.js" to "usr/lib/firefox/defaults/pref/droiddeck.js",
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
@@ -32,7 +34,7 @@ object SessionFiles {
/** Puts the session's files in place; [startsSession] is true only for the call that starts the Steam session. */
fun stage(context: Context, root: File, startsSession: Boolean = false) {
if (DesktopCatalog.desktopInstalled(root)) try { DesktopCatalog.cleanLegacy(context) }
if (DesktopCatalog.desktopInstalled(root) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) }
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
GameEnvironmentStore.publish(context)
WinComponents.publish(context)
@@ -70,10 +72,21 @@ object SessionFiles {
"usr/local/bin/droiddeck-steam-launch" to "usr/local/bin/droiddeck-steam-launch",
"usr/local/bin/droiddeck-desktop-games" to "usr/local/bin/droiddeck-desktop-games",
"usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks",
"usr/local/bin/droiddeck-downloads" to "usr/local/bin/droiddeck-downloads",
"usr/local/bin/droiddeck-root" to "usr/local/bin/droiddeck-root",
"usr/local/bin/droiddeck-text" to "usr/local/bin/droiddeck-text",
"usr/local/bin/droiddeck-snapd" to "usr/local/bin/droiddeck-snapd",
"usr/local/bin/droiddeck-emulators" to "usr/local/bin/droiddeck-emulators",
"usr/local/bin/droiddeck-snap-run" to "usr/local/bin/droiddeck-snap-run",
"usr/local/bin/droiddeck-snap-confine" to "usr/local/bin/droiddeck-snap-confine",
"usr/local/bin/droiddeck-snapctl" to "usr/local/bin/droiddeck-snapctl",
"usr/local/bin/droiddeck-systemd-run" to "usr/local/bin/systemd-run",
"usr/local/bin/droiddeck-snap-cli" to "usr/local/bin/snap",
"usr/local/bin/droiddeck-steam-shim" to "usr/local/bin/droiddeck-steam-shim",
"usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts",
"usr/local/bin/droiddeck-xbox" to "usr/local/bin/droiddeck-xbox",
"usr/local/bin/droiddeck-store-launch" to "usr/local/bin/droiddeck-store-launch",
"usr/local/bin/droiddeck-gog-maintenance" to "usr/local/bin/droiddeck-gog-maintenance",
"usr/local/bin/droiddeck-battlenet" to "usr/local/bin/droiddeck-battlenet",
"usr/local/bin/droiddeck-epic" to "usr/local/bin/droiddeck-epic",
"usr/local/bin/droiddeck-epic-steam" to "usr/local/bin/droiddeck-epic-steam",
@@ -234,6 +247,7 @@ object SessionFiles {
Log.e(TAG, "could not write steam-compatibility-label")
}
writeCjkFontConfig(root, etc)
writeDesktopStrings(context, File(etc, "droiddeck").apply { mkdirs() })
val droiddeckEtc = File(etc, "droiddeck").apply { mkdirs() }
val stagedSocket = File(droiddeckEtc, "bwrap-socket.staged")
if (!FileUtils.writeString(stagedSocket, BwrapSpawner.socket(context) + "\n")
@@ -241,6 +255,12 @@ object SessionFiles {
stagedSocket.delete()
Log.e(TAG, "could not write bwrap-socket")
}
val stagedRoot = File(droiddeckEtc, "root-socket.staged")
if (!FileUtils.writeString(stagedRoot, com.droiddeck.launcher.runtime.RootSpawner.socket(context) + "\n")
|| !stagedRoot.renameTo(File(droiddeckEtc, "root-socket"))) {
stagedRoot.delete()
Log.e(TAG, "could not write root-socket")
}
BootMovie.syncFromSteam(context)
val startupMovie = BootMovie.prepare(context)
@@ -585,6 +605,28 @@ object SessionFiles {
* The fonts themselves are bind-mounted by LinuxRuntime.bindSystemFonts() into
* /usr/local/share/fonts/android; here we only need to point fontconfig at them.
*/
private val DESKTOP_STRINGS = listOf(
"desktop_restore_title" to R.string.desktop_restore_title,
"desktop_restore_body" to R.string.desktop_restore_body,
"desktop_restore_done_title" to R.string.desktop_restore_done_title,
"desktop_restore_done_body" to R.string.desktop_restore_done_body,
"desktop_restore_failed_title" to R.string.desktop_restore_failed_title,
"desktop_restore_failed_body" to R.string.desktop_restore_failed_body,
)
private fun writeDesktopStrings(context: Context, dir: File) {
val text = DESKTOP_STRINGS.joinToString("") { (key, id) ->
key + "=" + context.getString(id).replace("\\", "\\\\").replace("%", "%%").replace("\n", "\\n") + "\n"
}
val target = File(dir, "strings")
if (FileUtils.readString(target) == text) return
val staged = File(dir, "strings.staged")
if (!FileUtils.writeString(staged, text) || !staged.renameTo(target)) {
staged.delete()
Log.e(TAG, "could not write desktop strings")
}
}
private fun writeCjkFontConfig(root: File, etc: File) {
try {
val confDir = File(etc, "fonts/conf.d").apply { mkdirs() }
@@ -21,6 +21,8 @@ object SessionPrefs {
private const val LEGACY_SUSPEND_DOWNLOADS = "downloads"
private const val STEAM_DOWNLOADS_IN_BACKGROUND = "steamDownloadsInBackground"
private const val DECKY_ZIP_WARNING_SEEN = "deckyZipWarningSeen"
private const val SLOW_USB_WARNING_OFF = "slowUsbWarningOff"
private const val SLOW_USB_DISMISSED = "slowUsbDismissed"
const val CONTROLLER_DECK = "deck"
const val CONTROLLER_XBOX360 = "xbox360"
@@ -84,6 +86,32 @@ 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
fun setDualScreenMode(context: Context, mode: String) {
prefs(context).edit().putString("dualScreenMode", mode).apply()
}
fun secondScreenPanel(context: Context): String? = prefs(context).getString("secondScreenPanel", null)
fun setSecondScreenPanel(context: Context, mode: String) {
prefs(context).edit().putString("secondScreenPanel", mode).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) {
prefs(context).edit().putBoolean("dualScreenSessionControls", on).apply()
}
fun gameStoresEnabled(context: Context): Boolean = prefs(context).getBoolean("gameStoresEnabled", true)
fun setGameStoresEnabled(context: Context, on: Boolean) {
@@ -125,6 +153,30 @@ object SessionPrefs {
prefs(context).edit().putString("storesView", if (view in STORES_VIEWS) view else STORES_VIEWS.first()).apply()
}
fun libraryCardLevel(context: Context): Int = prefs(context).getInt("libraryCardLevel", 2)
fun setLibraryCardLevel(context: Context, level: Int) {
prefs(context).edit().putInt("libraryCardLevel", level).apply()
}
fun libraryShowTitle(context: Context): Boolean = prefs(context).getBoolean("libraryShowTitle", true)
fun setLibraryShowTitle(context: Context, show: Boolean) {
prefs(context).edit().putBoolean("libraryShowTitle", show).apply()
}
fun libraryShowSize(context: Context): Boolean = prefs(context).getBoolean("libraryShowSize", true)
fun setLibraryShowSize(context: Context, show: Boolean) {
prefs(context).edit().putBoolean("libraryShowSize", show).apply()
}
fun railLabels(context: Context): Boolean = prefs(context).getBoolean("railLabels", false)
fun setRailLabels(context: Context, show: Boolean) {
prefs(context).edit().putBoolean("railLabels", show).apply()
}
fun libraryShowUninstalled(context: Context): Boolean = prefs(context).getBoolean("libraryShowUninstalled", false)
fun setLibraryShowUninstalled(context: Context, show: Boolean) {
@@ -195,7 +247,7 @@ object SessionPrefs {
prefs(context).edit().putInt("gameStoresParallel", count.coerceIn(1, 3)).apply()
}
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean(hudKey(context), !mangoappSession(context))
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean(hudKey(context), false)
fun setHudEnabled(context: Context, on: Boolean) {
prefs(context).edit().putBoolean(hudKey(context), on).apply()
@@ -233,6 +285,20 @@ object SessionPrefs {
prefs(context).edit().putInt("hudOpacity", percent.coerceIn(HUD_OPACITY_RANGE)).apply()
}
fun fusionHudConfig(context: Context): String? = prefs(context).getString("fusionHud", null)
fun setFusionHudConfig(context: Context, config: String) {
prefs(context).edit().putString("fusionHud", config).apply()
}
fun fusionHudPosition(context: Context): Pair<Float, Float>? =
prefs(context).getString("fusionHudPos", null)?.split(',')?.mapNotNull { it.toFloatOrNull() }
?.takeIf { it.size == 2 }?.let { it[0] to it[1] }
fun setFusionHudPosition(context: Context, x: Float, y: Float) {
prefs(context).edit().putString("fusionHudPos", "$x,$y").apply()
}
const val HUD_COLOR_MINT = "mint"
val HUD_COLORS = listOf(HUD_COLOR_MINT, "white", "sky", "amber", "violet")
val HUD_OPACITY_RANGE = 30..100
@@ -249,6 +315,18 @@ object SessionPrefs {
prefs(context).edit().putBoolean("lowLatency", on).apply()
}
fun evdevMouse(context: Context): Boolean = prefs(context).getBoolean("evdevMouse", false)
fun setEvdevMouse(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("evdevMouse", on).apply()
}
fun directCursor(context: Context): Boolean = prefs(context).getBoolean("directCursor", false)
fun setDirectCursor(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("directCursor", on).apply()
}
fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false)
fun setBackActionsInverted(context: Context, inverted: Boolean) {
@@ -1009,12 +1087,30 @@ object SessionPrefs {
/** Compositor frame limit that releases buffers to the game unpaced. */
const val FPS_UNPACED = -1
/** The drawer's frame limit slider: its first stop is Off. */
const val FPS_LIMIT_OFF = 15
const val FPS_LIMIT_MAX = 120
/**
* Buffers go back to the game as soon as they are replaced instead of once per refresh;
* Steam's Frame Limit in the Quick Access menu caps games. Mirroring still follows the glasses' refresh rate.
* Steam's Frame Limit in the Quick Access menu caps Steam games, and the drawer's limit caps games
* launched without Steam. Mirroring still follows the glasses' refresh rate.
*/
fun compositorFpsLimit(mirrorRefreshLimit: Int): Int =
if (mirrorRefreshLimit <= 0) FPS_UNPACED else mirrorRefreshLimit
fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0): Int = when {
mirrorRefreshLimit <= 0 && sessionLimit <= 0 -> FPS_UNPACED
mirrorRefreshLimit <= 0 -> sessionLimit
sessionLimit <= 0 -> mirrorRefreshLimit
else -> minOf(mirrorRefreshLimit, sessionLimit)
}
private const val STEAM_UI_FPS = 60f
fun steamUiPacing(context: Context): Boolean = prefs(context).getBoolean("steamUiPacing", true)
fun steamUiFpsLimit(refreshHz: Float): Int {
val steps = ((refreshHz + 0.5f) / STEAM_UI_FPS).toInt()
return if (steps < 2) 0 else (refreshHz / steps + 0.01f).toInt()
}
val upscalerChoices = listOf(
0 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
@@ -1195,7 +1291,7 @@ object SessionPrefs {
resolutionChosen(context, SessionService.MODE_DESKTOP)) SessionService.MODE_DESKTOP
else prefMode(mode)
fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", false)
fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", true)
fun setPipAutoEnter(context: Context, enabled: Boolean) {
prefs(context).edit().putBoolean("pipAutoEnter", enabled).apply()
@@ -1238,7 +1334,8 @@ object SessionPrefs {
}
fun suspendPolicy(context: Context, mode: String): String =
prefs(context).getString("suspendPolicy.${prefMode(mode)}", SUSPEND_MANUAL)
prefs(context).getString("suspendPolicy.${prefMode(mode)}",
if (mode == SessionService.MODE_STEAM) SUSPEND_NATIVE else SUSPEND_MANUAL)
?.let { if (it == LEGACY_SUSPEND_DOWNLOADS) SUSPEND_AUTO else it }
?.takeIf { it in setOf(SUSPEND_AUTO, SUSPEND_NATIVE, SUSPEND_MANUAL, SUSPEND_NEVER) }
?.let { if (mode != SessionService.MODE_STEAM && it == SUSPEND_NATIVE) SUSPEND_AUTO else it }
@@ -1264,6 +1361,18 @@ object SessionPrefs {
prefs(context).edit().putBoolean(DECKY_ZIP_WARNING_SEEN, true).apply()
}
fun slowUsbWarningOff(context: Context): Boolean = prefs(context).getBoolean(SLOW_USB_WARNING_OFF, false)
fun setSlowUsbWarningOff(context: Context) {
prefs(context).edit().putBoolean(SLOW_USB_WARNING_OFF, true).apply()
}
fun slowUsbDismissed(context: Context): Set<String> = prefs(context).getStringSet(SLOW_USB_DISMISSED, null)?.toSet().orEmpty()
fun setSlowUsbDismissed(context: Context, keys: Set<String>) {
prefs(context).edit().putStringSet(SLOW_USB_DISMISSED, keys.toSet()).apply()
}
fun steamDownloadsInBackground(context: Context): Boolean {
val prefs = prefs(context)
return prefs.getBoolean(STEAM_DOWNLOADS_IN_BACKGROUND, false) ||
@@ -334,6 +334,7 @@ class SessionService : Service() {
return START_NOT_STICKY
}
SessionState.mode = intent?.getStringExtra(EXTRA_MODE) ?: MODE_STEAM
SessionState.fpsLimit = 0
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
activityVisible = true
@@ -535,10 +536,6 @@ class SessionService : Service() {
// gamescope's WSI layer and winex11 reuse their per-present window checks for this long.
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=100")
guest.add("WINE_OFFSCREEN_CHECK_MS=100")
// gamescope turns buffers around slower than an uncapped game draws; more images keep it drawing.
// The WSI layer goes back to its default count while Steam's Frame Limit holds the game.
guest.add("GAMESCOPE_WSI_MIN_IMAGE_COUNT=8")
guest.add("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=1")
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
guest.add("BL_LOG=" + sessionLog.path)
guest.add("BL_DEBUG_DIR=" + sessionDir.path)
@@ -546,6 +543,7 @@ class SessionService : Service() {
val fakeInputDir = File(sessionRoot, "dev/input").apply { mkdirs() }
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
SessionState.deckPad = false
SessionState.secondScreenAutoOpened = false
deckBinds = emptyList()
inputSysfs = null
if (controllersOn) {
@@ -756,7 +754,7 @@ class SessionService : Service() {
guest.add("DROIDDECK_BWRAP_SOCKET=" + com.droiddeck.launcher.runtime.BwrapSpawner.socket(this))
guest.add("HOME=/root")
guest.add("USER=root")
guest.add("PATH=/usr/local/bin:/usr/bin:/bin")
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")
guest.add("BL_STEAM_LANGUAGE=" + SteamLanguage.forLocale(
@@ -880,7 +878,7 @@ class SessionService : Service() {
}
private fun addControllerEnvironment(guest: MutableList<String>, fakeInputDir: File, sessionDir: File) {
FakeInputWriter.prepareRingSlots(fakeInputDir, 4)
FakeInputWriter.prepareRingSlots(fakeInputDir, 5)
val builtinPad = SessionPrefs.builtinPad(this)
val hiddenPad = SessionState.mode == MODE_STEAM && !builtinPad &&
!com.droiddeck.launcher.input.PadBridge.anyControllerConnected()
@@ -1882,6 +1880,9 @@ class SessionService : Service() {
}
override fun onTaskRemoved(rootIntent: Intent?) {
if (rootIntent?.component?.className in setOf(
com.droiddeck.launcher.ui.DualScreenActivity::class.java.name,
com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name)) return
if (pipTask || xrActivityVisible) {
Log.i(TAG, "panel task dismissed - retaining the session under its active surface policy")
activityVisible = false
@@ -2178,6 +2179,7 @@ class SessionService : Service() {
fun stop(context: Context) {
if (!SessionState.running) {
SessionState.stopRequested = true
SessionState.installCancellation?.cancel()
return
}
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_STOP))
@@ -37,6 +37,9 @@ object SessionState {
@Volatile
var installing: String? = null
@Volatile
var installCancellation: com.droiddeck.launcher.core.Downloader.Cancellation? = null
@Volatile
var stopRequested = false
@@ -88,6 +91,7 @@ object SessionState {
@Volatile var secondScreenMode = com.droiddeck.launcher.input.SecondScreenMode.NONE
@Volatile var secondScreenDisplay = -1
@Volatile var secondScreenAutoOpened = false
@Volatile
var mode = "steam"
@@ -104,6 +108,10 @@ object SessionState {
@Volatile
var upscaleRatio: Float = 0f
/** Frame limit chosen in the drawer for a game launched without Steam; 0 is off. */
@Volatile
var fpsLimit: Int = 0
@Volatile
var firstFrameSeen = false
@@ -13,11 +13,12 @@ object SettingsReset {
internal val SESSION_KEYS = setOf(
"orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "addedGamesArt",
"dualScreenMode", "dualScreenLauncher", "dualScreenSessionControls",
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "fusionHud", "fusionHudPos", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "picturePosition",
"stretch16x9", "picturePosition", "railLabels",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
@@ -0,0 +1,26 @@
package com.droiddeck.launcher.session
import org.json.JSONObject
import java.io.File
object SteamImportPrompt {
data class Ask(val token: String, val games: List<String>)
private fun folder(root: File) = File(root, "root/.cache/droiddeck")
fun read(root: File): Ask? {
val text = runCatching { File(folder(root), "steam-import.json").readText() }.getOrNull() ?: return null
val json = runCatching { JSONObject(text) }.getOrNull() ?: return null
val token = json.optString("token").takeIf { it.isNotEmpty() } ?: return null
val list = json.optJSONArray("games")
val games = if (list == null) emptyList() else (0 until list.length()).mapNotNull { list.optString(it).takeIf(String::isNotBlank) }
return Ask(token, games)
}
fun answer(root: File, token: String, now: Boolean): Boolean = runCatching {
val dir = folder(root).apply { mkdirs() }
val temp = File(dir, "steam-import.answer.tmp")
temp.writeText(JSONObject().put("token", token).put("choice", if (now) "now" else "later").toString())
temp.renameTo(File(dir, "steam-import.answer"))
}.getOrDefault(false)
}
@@ -0,0 +1,122 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.storage.StorageManager
import com.droiddeck.launcher.frontend.AddedGames
import java.io.File
object UsbLink {
data class Link(val device: String, val mbps: Double, val name: String, val portMbps: Double?, val plug: String = "")
class SlowDrive(val key: String, val name: String, val mbps: Double, val portMbps: Double?) {
val portLimited get() = portMbps != null && portMbps < FAST_MBPS
}
const val FAST_MBPS = 5000.0
fun markShown(context: Context, drive: SlowDrive) = synchronized(this) {
SessionPrefs.setSlowUsbDismissed(context, SessionPrefs.slowUsbDismissed(context) + drive.key)
}
fun stillDue(context: Context, drive: SlowDrive) =
!SessionPrefs.slowUsbWarningOff(context) && drive.key !in SessionPrefs.slowUsbDismissed(context)
fun slowLibrary(context: Context): SlowDrive? {
if (SessionPrefs.slowUsbWarningOff(context)) return null
val mounts = runCatching { File("/proc/self/mounts").readText() }.getOrNull() ?: return null
val sm = context.getSystemService(StorageManager::class.java)
val boot = runCatching { android.provider.Settings.Global.getInt(context.contentResolver, android.provider.Settings.Global.BOOT_COUNT) }.getOrDefault(0)
val drives = libraries(context).mapNotNull { path ->
val link = forPath(path, mounts) ?: return@mapNotNull null
if (link.mbps >= FAST_MBPS) return@mapNotNull null
val volume = runCatching { sm?.getStorageVolume(File(path))?.getDescription(context) }.getOrNull()
SlowDrive(dismissKey(boot, link), link.name.ifBlank { volume.orEmpty() }.ifBlank { File(path).name }, link.mbps, link.portMbps)
}
return synchronized(this) {
val dismissed = SessionPrefs.slowUsbDismissed(context)
val current = dismissed.intersect(drives.map { it.key }.toSet())
if (current != dismissed) SessionPrefs.setSlowUsbDismissed(context, current)
drives.firstOrNull { it.key !in current }
}
}
internal fun dismissKey(boot: Int, link: Link) = "$boot/${link.plug}/${link.device}@${link.mbps}"
private fun libraries(context: Context): List<String> {
val pref = SessionPrefs.gameStorage(context)
val storage = when (pref) {
SessionPrefs.GAME_STORAGE_OFF -> null
"" -> GameStorage.effective(context)?.path
else -> pref
}
val folders = runCatching { AddedGames.roots(context).map { it.host.absolutePath } }.getOrDefault(emptyList())
return (listOfNotNull(storage) + folders).map(::storagePath).filter { external(it) }.distinct()
}
internal fun storagePath(path: String) = if (path.startsWith("/mnt/media_rw/")) "/storage/" + path.removePrefix("/mnt/media_rw/") else path
internal fun external(path: String) = path.startsWith("/storage/") && !path.startsWith("/storage/emulated/") && !path.startsWith("/storage/self/")
fun forPath(path: String, mounts: String, sys: File = File("/sys")): Link? {
val device = mountDevice(rawPath(path), mounts) ?: return null
val block = blockDir(device, sys) ?: return null
val usb = usbDevice(block, sys) ?: return null
val mbps = readSpeed(usb) ?: return null
val name = listOf("manufacturer", "product").mapNotNull { read(File(usb, it)) }.joinToString(" ").trim()
val plug = listOf("busnum", "devnum").mapNotNull { read(File(usb, it)) }.joinToString("-")
return Link(device, mbps, name, portSpeed(usb, sys), plug)
}
internal fun rawPath(path: String) = if (external(path)) "/mnt/media_rw/" + path.removePrefix("/storage/") else path
internal fun mountDevice(path: String, mounts: String): String? {
var best: Pair<String, String>? = null
for (line in mounts.lineSequence()) {
val parts = line.split(' ')
if (parts.size < 2) continue
val point = parts[1].replace("\\040", " ")
if (path != point && !path.startsWith("${point.trimEnd('/')}/")) continue
if (best == null || point.length > best.first.length) best = point to parts[0]
}
val source = best?.second ?: return null
Regex(":(\\d+),(\\d+)$").find(source)?.let { return "${it.groupValues[1]}:${it.groupValues[2]}" }
return if (source.startsWith("/dev/block/") || source.startsWith("/dev/sd")) "name:" + source.substringAfterLast('/') else null
}
internal fun blockDir(device: String, sys: File): File? {
if (device.startsWith("name:")) return File(sys, "class/block/${device.removePrefix("name:")}").takeIf { it.exists() }?.canonicalFile
File(sys, "dev/block/$device").takeIf { it.exists() }?.let { return it.canonicalFile }
return File(sys, "class/block").listFiles()?.firstOrNull { read(File(it, "dev")) == device }?.canonicalFile
}
internal fun usbDevice(block: File, sys: File): File? {
val top = sys.canonicalFile
var dir: File? = block
while (dir != null && dir != top) {
if (File(dir, "speed").isFile && File(dir, "idVendor").isFile) return dir
dir = dir.parentFile
}
return null
}
private fun portSpeed(usb: File, sys: File): Double? {
val bus = read(File(usb, "busnum")) ?: return null
val hub = File(sys, "bus/usb/devices/usb$bus").takeIf { it.exists() }?.canonicalFile ?: return null
val controller = hub.parentFile ?: return null
return controller.listFiles { f -> f.name.matches(Regex("usb\\d+")) }?.mapNotNull { readSpeed(it) }?.maxOrNull()
}
private fun readSpeed(dir: File) = read(File(dir, "speed"))?.toDoubleOrNull()
private fun read(file: File) = runCatching { file.readText().trim() }.getOrNull()?.takeIf { it.isNotEmpty() }
fun generation(mbps: Double) = when {
mbps <= 12 -> "USB 1.1"
mbps < FAST_MBPS -> "USB 2.0"
mbps < 10000 -> "USB 3.2 Gen 1"
mbps < 20000 -> "USB 3.2 Gen 2"
else -> "USB 3.2 Gen 2x2"
}
fun megabytesPerSecond(mbps: Double) = (mbps / 8 * 0.7).toInt()
}
@@ -19,7 +19,7 @@ enum class Bucket { GAMES, GAME_DATA, TOOLS, COMPONENTS, STORES, DESKTOP, SYSTEM
class GameUsage(
val appId: Int, val name: String, val art: File?, val library: String, val internal: Boolean, val lastPlayed: Long,
val game: Long, val prefix: Long, val shaders: Long, val workshop: Long, val shaderDir: File?,
val x64: Boolean = false,
val x64: Boolean = false, val prefixDir: File? = null,
) {
val data: Long get() = prefix + shaders + workshop
val total: Long get() = game + data
@@ -175,14 +175,16 @@ object StorageScan {
}
if (!m.installed) continue
val gameBytes = dir?.let { File(lib.root, "steamapps/common/$it") }?.takeIf { it.isDirectory }?.let { walker.measure(it) } ?: 0
val prefix = File(lib.data, "steamapps/compatdata/${m.appId}").takeIf { it.isDirectory }?.let { walker.measure(it) } ?: 0
val compatRoot = File(lib.data, "steamapps/compatdata").takeIf { it.isDirectory } ?: File(lib.root, "steamapps/compatdata")
val prefixDir = File(compatRoot, m.appId.toString()).takeIf { it.isDirectory }
val prefix = prefixDir?.let { walker.measure(it) } ?: 0
val shaderDir = File(lib.data, "steamapps/shadercache/${m.appId}").takeIf { it.isDirectory }
val shaders = shaderDir?.let { walker.measure(it) } ?: 0
val workshop = File(lib.root, "steamapps/workshop/content/${m.appId}").takeIf { it.isDirectory }?.let { walker.measure(it) } ?: 0
val known = art[lib.x64]?.get(m.appId)
games.add(GameUsage(
m.appId, known?.name ?: m.name, known?.art, lib.label, lib.internal, m.lastPlayed,
gameBytes, prefix, shaders, workshop, shaderDir, lib.x64,
gameBytes, prefix, shaders, workshop, shaderDir, lib.x64, prefixDir,
))
}
}
@@ -140,6 +140,13 @@ object StorageState {
FileOps.delete(dir)
})
fun resetPrefix(context: Context, game: GameUsage) = act(context, "prefix-${game.appId}", { _, fresh ->
val dir = fresh.games.firstOrNull { it.appId == game.appId && it.x64 == game.x64 && it.prefixDir?.path == game.prefixDir?.path }
?.prefixDir ?: error("prefix not found")
check(FileOps.delete(dir)) { "cannot delete $dir" }
true
})
fun removeLeftover(context: Context, l: Leftover) = act(context, "leftover-${l.appId}", { _, fresh ->
val leftover = fresh.leftovers.firstOrNull { it.appId == l.appId && it.prefix?.path == l.prefix?.path && it.shaders?.path == l.shaders?.path }
?: return@act false
@@ -63,7 +63,7 @@ class StoreGameSidecar(
val file = File(folder, FILE_NAME)
val tmp = File(folder, "$FILE_NAME.tmp")
tmp.writeText(toJson().toString(2))
if (!tmp.renameTo(file)) { file.delete(); tmp.renameTo(file) }
if (!tmp.renameTo(file)) java.nio.file.Files.move(tmp.toPath(), file.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING)
}
companion object {
@@ -254,6 +254,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.isInstalled -> Unfinished(store, sidecar.id, folder)
else -> null
}
@@ -30,7 +30,12 @@ object StoreInstalls {
it.write(before.copy(state = StoreGameSidecar.STATE_UPDATING, installVersion = "").toJson().toString(2).toByteArray(Charsets.UTF_8))
it.fd.sync()
}
Files.move(stage.toPath(), StoreGameSidecar.file(folder).toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
val record = StoreGameSidecar.file(folder).toPath()
try {
Files.move(stage.toPath(), record, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
} catch (e: java.nio.file.AtomicMoveNotSupportedException) {
Files.move(stage.toPath(), record, StandardCopyOption.REPLACE_EXISTING)
}
} finally {
stage.delete()
}
@@ -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 }?.let { InstalledStoreGame(it, folder) }
StoreGameSidecar.read(folder)?.takeIf { it.isInstalled || it.store == Store.GOG && 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 ""
@@ -95,6 +95,7 @@ object StoresState {
engine = version
accountsLoaded = true
}
com.droiddeck.launcher.stores.gog.GogMaintenance.checkInstalled(app, onDisk)
}
}
}
@@ -191,7 +192,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.ITCH) com.droiddeck.launcher.stores.itch.ItchCollections.clear()
if (store == Store.ITCH) {
com.droiddeck.launcher.stores.itch.ItchCollections.clear()
com.droiddeck.launcher.stores.itch.ItchUpdates.clear(app)
}
main.post {
if (store == Store.XBOX && StoreAccounts.signedInAs(app, store) != null) return@post
accounts.remove(store); library.remove(store); status.remove(store); problems.remove(store); libraryAsked.remove(store)
@@ -282,6 +286,7 @@ object StoresState {
main.post {
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)
}
})
main.post(onDone)
@@ -31,6 +31,9 @@ data class DownloadEntry(
val stageItemsTotal: Int = 0,
val diskBytes: Long = 0L,
val stagesPassed: Int = 0,
val interruptible: Boolean = true,
val reusedBytes: Long = 0L,
val appliedBytes: Long = 0L,
) {
fun passed(s: DownloadStage): Boolean = state == DownloadState.INSTALLED || (stagesPassed and (1 shl s.ordinal)) != 0
@@ -21,6 +21,11 @@ object DownloadQueue {
fun diskSize(bytes: Long) = update(key) { if (bytes > 0) it.copy(diskBytes = bytes) else it }
fun progress(bytesDone: Long, bytesTotal: Long, detail: String? = null, @Suppress("UNUSED_PARAMETER") speedBps: Long = -1L) = measure(key, bytesDone, bytesTotal, detail?.let(::stripSpeed))
fun log(line: String) = StoresState.logLine(line)
fun interruptible(value: Boolean) = update(key) {
check(value || !cancelled.get()) { "The operation was paused before installer application" }
it.copy(interruptible = value)
}
fun maintenance(reusedBytes: Long, appliedBytes: Long) = update(key) { it.copy(reusedBytes = reusedBytes, appliedBytes = appliedBytes) }
}
private fun stripSpeed(s: String): String = s.replace(Regex("\\s+\\S+ [KMG]B/s\\s*$"), "").trimEnd()
@@ -166,12 +171,13 @@ object DownloadQueue {
fun pause(key: String) {
val item = synchronized(lock) { items[key] } ?: return
synchronized(lock) {
if (!item.entry.interruptible) return
if (item.entry.state == DownloadState.QUEUED) { item.entry = item.entry.copy(state = DownloadState.PAUSED, queuePosition = 0); renumber(); publishLocked(); return }
if (item.entry.state != DownloadState.RUNNING) return
item.pauseRequested = true
item.cancelled.set(true)
item.job?.cancel(deleteFiles = false)
}
item.cancelled.set(true)
item.job?.cancel(deleteFiles = false)
StoresState.logLine("paused \"${item.entry.name}\"")
}
@@ -204,17 +210,19 @@ object DownloadQueue {
val wasRunning: Boolean
synchronized(lock) {
item = items[key] ?: return
if (!item.entry.interruptible) return
wasRunning = item.entry.state == DownloadState.RUNNING
if (wasRunning) {
item.cancelled.set(true)
item.job?.cancel(deleteFiles = true)
}
if (!wasRunning) {
item.entry = item.entry.copy(state = DownloadState.CANCELLED, queuePosition = 0, finishedAt = System.currentTimeMillis())
renumber()
publishLocked()
}
}
if (wasRunning) {
item.cancelled.set(true)
item.job?.cancel(deleteFiles = true)
} else {
if (!wasRunning) {
Thread({ runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }, "store-dl-cancel").start()
}
StoresState.logLine("cancelled \"${item.entry.name}\"")
@@ -45,7 +45,7 @@ object SavedQueue {
val f = File(context.filesDir, FILE)
val tmp = File(context.filesDir, "$FILE.tmp")
tmp.writeText(out.toString())
tmp.renameTo(f)
java.nio.file.Files.move(tmp.toPath(), f.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING)
}.onFailure { Log.w(TAG, "could not save the queue", it) }
}
}
@@ -68,7 +68,12 @@ object SavedQueue {
for ((item, root, paused) in back) {
if (DownloadQueue.entry(key(item)) != null) continue
if (paused) DownloadQueue.holdPaused(key(item))
StoresState.install(app, item, root)
if (item.store == Store.GOG && item.extra.containsKey(com.droiddeck.launcher.stores.gog.GogMaintenance.OPERATION)) {
Thread({
runCatching { com.droiddeck.launcher.stores.gog.GogMaintenance.restore(app, item) }
.onFailure { DownloadQueue.recordFailed(app, DownloadEntry(item.store, item.id, item.title), it.message ?: "GOG recovery failed") }
}, "gog-restore").start()
} else StoresState.install(app, item, root)
}
}
}, "store-queue-restore").start()
@@ -33,6 +33,7 @@ object GogAuth {
@Synchronized
private fun saveAccount(context: Context, accessToken: String, refreshToken: String?, userId: String?) {
GogMaintenance.reset()
var username = ""
runCatching {
val body = StoreNet.get("https://embed.gog.com/userData.json", bearer = accessToken, userAgent = GALAXY_UA)
@@ -28,6 +28,7 @@ object GogBackend : StoreBackend {
}
override fun signOut(context: Context) {
GogMaintenance.reset()
GogPrefs.get(context).edit().remove("library_cache").remove("library_cache_v2").remove("library_synced_at").apply()
}
@@ -53,7 +54,11 @@ object GogBackend : StoreBackend {
StoresState.post {
StoresState.status.remove(store)
when (result) {
is GogLibrary.SyncResult.Ok -> { StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], result.games.map { GogLibrary.toCatalogItem(app, it) }); StoresState.problems.remove(store) }
is GogLibrary.SyncResult.Ok -> {
StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], result.games.map { GogLibrary.toCatalogItem(app, it) })
StoresState.problems.remove(store)
GogMaintenance.checkInstalled(app, StoresState.installed)
}
is GogLibrary.SyncResult.Failed -> StoresState.problems[store] = result.message
GogLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = StoresState.notSignedInLine(store)
GogLibrary.SyncResult.Busy -> {}
@@ -0,0 +1,187 @@
package com.droiddeck.launcher.stores.gog
import android.content.Context
import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.StoreNet
import org.json.JSONArray
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
import java.util.zip.GZIPInputStream
import java.util.zip.InflaterInputStream
internal object GogContent {
const val SYSTEM = "https://content-system.gog.com"
const val CDN = "https://gog-cdn-fastly.gog.com/content-system"
fun token(context: Context) = GogAuth.validToken(context) ?: error("Sign in to GOG and retry")
fun builds(id: String, token: String): JSONObject {
val result = json("$SYSTEM/products/$id/os/windows/builds?generation=2", token)
if (result.optJSONArray("items")?.length() != 0) return result
return json("$SYSTEM/products/$id/os/windows/builds?generation=1", token)
}
fun product(id: String, token: String): JSONObject = json("https://api.gog.com/products/$id?expand=downloads", token)
fun downloadFilename(url: String): String = java.net.URLDecoder.decode(URL(url).path.substringAfterLast('/').replace("+", "%2B"), "UTF-8")
fun resolveDownload(download: GogOfflineDownload, token: String): GogOfflineDownload = download.copy(parts = download.parts.map { part ->
val resolved = GogDownloadManager.resolveRedirect(part.url, token) ?: error("The GOG download link is unavailable")
val connection = URL(resolved).openConnection() as HttpURLConnection
try {
connection.requestMethod = "HEAD"
connection.connectTimeout = 20_000; connection.readTimeout = 30_000
check(connection.responseCode in 200..299) { "GOG download metadata failed (HTTP ${connection.responseCode})" }
val disposition = connection.getHeaderField("Content-Disposition").orEmpty()
val supplied = Regex("filename=\"?([^\";]+)", RegexOption.IGNORE_CASE).find(disposition)?.groupValues?.get(1).orEmpty()
val remote = downloadFilename(resolved).takeIf { it.endsWith(".exe", true) || it.endsWith(".bin", true) }.orEmpty()
val name = part.name.ifBlank { supplied.ifBlank { remote } }
check(name.isNotBlank()) { "GOG did not provide the installer part filename" }
part.copy(name = name, size = connection.contentLengthLong.coerceAtLeast(0))
} finally { connection.disconnect() }
})
fun json(url: String, token: String? = null): JSONObject {
require(URL(url).protocol == "https") { "GOG metadata requires HTTPS" }
val connection = URL(url).openConnection() as HttpURLConnection
try {
connection.connectTimeout = 20_000; connection.readTimeout = 30_000
connection.setRequestProperty("User-Agent", GogAuth.GALAXY_UA)
if (token != null && URL(url).host.let { it == "gog.com" || it.endsWith(".gog.com") }) connection.setRequestProperty("Authorization", "Bearer $token")
check(connection.responseCode in 200..299) { "GOG metadata request failed (HTTP ${connection.responseCode})" }
val raw = connection.inputStream.readBytes()
val text = when {
raw.size > 1 && raw[0] == 0x78.toByte() -> InflaterInputStream(raw.inputStream()).bufferedReader().use { it.readText() }
raw.size > 1 && raw[0] == 0x1f.toByte() && raw[1] == 0x8b.toByte() -> GZIPInputStream(raw.inputStream()).bufferedReader().use { it.readText() }
else -> raw.toString(Charsets.UTF_8)
}
return JSONObject(text)
} finally { connection.disconnect() }
}
fun snapshot(old: GogInstallRecord, build: GogBuild, token: String,
metadata: (String, String?) -> JSONObject = ::json): GogInstallRecord {
check(build.link.isNotBlank()) { "GOG build manifest is unavailable" }
val manifest = metadata(build.link, token)
val files = JSONArray()
val depots = if (build.generation == 1) manifest.optJSONObject("product")?.optJSONArray("depots") ?: manifest.optJSONArray("depot") else manifest.optJSONArray("depots")
check(depots != null) { "GOG build has no depot list" }
val resolvedLanguage = StoreLanguage.pick(StoreLanguage.codesFromDepots(depots), old.language)
val selectedBitness = if (depots.objects().any { it.optJSONArray("osBitness")?.strings()?.contains("64") == true }) "64" else "32"
val owned = if (old.products.any { it != old.id }) StoreNet.get("https://embed.gog.com/user/data/games", bearer = token)?.let { JSONObject(it).optJSONArray("owned")?.strings()?.toSet() } else emptySet()
val products = old.products.filter { it == old.id || owned?.contains(it) == true }
check(old.products.all { it == old.id || owned?.contains(it) == true }) { "Could not confirm ownership of installed GOG DLC" }
for (depot in depots.objects()) {
if (depot.has("redist")) continue
val ids = depot.optJSONArray("gameIDs")?.strings() ?: listOf(depot.optString("productId", old.id))
val product = ids.firstOrNull { it in products } ?: continue
val languages = depot.optJSONArray("languages")?.strings().orEmpty()
if (!languageSelected(languages, resolvedLanguage)) continue
val bitness = depot.optJSONArray("osBitness")?.strings().orEmpty()
if (bitness.isNotEmpty() && selectedBitness !in bitness) continue
val hash = depot.optString("manifest")
val content = when {
hash.isNotEmpty() && build.generation == 2 -> metadata("$CDN/v2/meta/${cdnPath(hash)}", null)
hash.isNotEmpty() -> {
val timestamp = manifest.getJSONObject("product").getString("timestamp")
metadata("$CDN/v1/manifests/$product/windows/$timestamp/$hash", token)
}
depot.has("files") -> JSONObject().put("depot", depot)
else -> error("GOG depot manifest is missing")
}
val entries = content.getJSONObject("depot").optJSONArray(if (build.generation == 2) "items" else "files") ?: error("GOG depot files are missing")
for (entry in entries.objects()) {
val type = entry.optString("type")
check(type != "DepotLink") { "This GOG build contains unsupported file links" }
val support = depot.optBoolean("support") || entry.optBoolean("support") || entry.optJSONArray("flags")?.strings()?.contains("support") == true
val relative = entry.getString("path").replace('\\', '/').trimEnd('/').let { if (build.generation == 1) it.trimStart('/') else it }
val path = if (support) (if (build.generation == 1) "support/$relative" else "support/$product/$relative") else relative
val directory = type == "DepotDirectory" || entry.has("directory")
val chunks = entry.optJSONArray("chunks") ?: JSONArray()
val size = if (build.generation == 2) chunks.objects().sumOf { it.optLong("size") } else entry.optLong("size")
files.put(JSONObject().put("path", path).put("size", size).put("directory", directory)
.put("md5", entry.optString("md5").ifBlank { entry.optString("hash") }.takeIf { it.matches(Regex("[a-fA-F0-9]{32}")) }.orEmpty())
.put("sha256", entry.optString("sha256")).put("chunks", chunks).put("product", product)
.put("offset", entry.optLong("offset")).put("remotePath", entry.optString("url").substringBefore('?')))
}
}
check(files.length() > 0) { "GOG build contains no matching files" }
return old.copy(source = "depot", generation = build.generation, build = build.id, version = build.version,
branch = build.branch, language = resolvedLanguage, manifest = sanitize(manifest), files = files, products = products, verified = true)
}
fun languageSelected(list: List<String>, selected: String): Boolean = list.any { it.equals("Neutral", true) } || StoreLanguage.depotMatchesResolved(list.toTypedArray(), selected)
fun cdnPath(hash: String): String {
require(hash.matches(Regex("[a-fA-F0-9]{32,64}"))) { "Invalid GOG content hash" }
return "${hash.take(2)}/${hash.substring(2, 4)}/$hash"
}
fun links(record: GogInstallRecord, token: String, patches: Boolean = false): JSONObject {
val out = JSONObject()
for (id in record.products) {
val path = if (record.generation == 1) "/windows/${record.manifest.optJSONObject("product")?.optString("timestamp")}/" else "/"
val query = "_version=2&" + (if (record.generation == 1) "type=depot" else "generation=2") + "&path=${java.net.URLEncoder.encode(path, "UTF-8")}" + if (patches) "&root=%2Fpatches%2Fstore" else ""
val response = json("$SYSTEM/products/$id/secure_link?$query", token)
val bases = response.optJSONArray("urls")?.objects().orEmpty().mapNotNull { item ->
val params = item.optJSONObject("parameters")
var url = item.optString("url_format")
params?.keys()?.forEach { key -> url = url.replace("{$key}", params.getString(key)) }
url.takeIf { it.startsWith("https://") }
}
check(bases.isNotEmpty()) { "GOG refused a download link" }
out.put(id, JSONArray(bases))
}
return out
}
fun patches(old: GogInstallRecord, target: GogInstallRecord, token: String): JSONArray {
if (old.generation != 2 || target.generation != 2 || old.build.isBlank() || old.build == target.build) return JSONArray()
return runCatching {
val index = json("$SYSTEM/products/${old.id}/patches?_version=4&from_build_id=${old.build}&to_build_id=${target.build}", token)
val meta = json(index.getString("link"), token)
if (meta.optString("algorithm") != "xdelta3") return@runCatching JSONArray()
val result = JSONArray()
for (depot in meta.getJSONArray("depots").objects()) {
if (depot.optString("productId") !in target.products || !languageSelected(depot.optJSONArray("languages")?.strings().orEmpty(), target.language)) continue
val data = json("$CDN/v2/patches/meta/${cdnPath(depot.getString("manifest"))}")
for (item in data.getJSONObject("depot").getJSONArray("items").objects()) if (item.optString("type") == "DepotDiff")
result.put(JSONObject(item.toString()).put("product", depot.getString("productId")))
}
result
}.getOrElse { JSONArray() }
}
fun setupFiles(record: GogInstallRecord, token: String): Pair<JSONArray, JSONObject>? {
if (!record.manifest.optBoolean("scriptInterpreter")) return null
if (record.files.objects().none { file -> record.products.any { file.optString("path").substringAfterLast('/') == "goggame-$it.script" } }) return null
val index = json("$SYSTEM/dependencies/repository?generation=2")
val repository = json(index.getString("repository_manifest"))
val depot = repository.getJSONArray("depots").objects().firstOrNull { it.optString("dependencyId") == "ISI" }
?: error("GOG setup interpreter is unavailable")
val content = json("$CDN/v2/dependencies/meta/${cdnPath(depot.getString("manifest"))}")
val files = JSONArray()
for (entry in content.getJSONObject("depot").getJSONArray("items").objects()) {
if (entry.optString("type") != "DepotFile") continue
val chunks = entry.getJSONArray("chunks")
files.put(JSONObject().put("path", "support/" + entry.getString("path").replace('\\', '/'))
.put("size", chunks.objects().sumOf { it.getLong("size") }).put("md5", entry.optString("md5"))
.put("chunks", chunks).put("product", "redist"))
}
val response = json("$SYSTEM/open_link?generation=2&_version=2&path=%2Fdependencies%2Fstore%2F", token)
val bases = GogDownloadManager.parseCdnUrls(response.toString())
check(bases.isNotEmpty()) { "GOG setup download links are unavailable" }
return files to JSONObject().put("redist", JSONArray(bases))
}
fun sanitize(value: JSONObject): JSONObject {
val result = JSONObject()
for (key in value.keys()) {
if (key.lowercase() in setOf("clientsecret", "access_token", "refresh_token", "link", "urls", "url")) continue
val v = value.get(key)
result.put(key, when (v) { is JSONObject -> sanitize(v); is JSONArray -> JSONArray((0 until v.length()).map { i -> v.get(i).let { if (it is JSONObject) sanitize(it) else it } }); else -> v })
}
return result
}
}
@@ -106,7 +106,7 @@ public final class GogDownloadManager {
String builds1Json = httpGet(builds1Url, null);
if (builds1Json == null) builds1Json = httpGet(builds1Url, token);
if (builds1Json == null) throw new InstallException("No builds available for this game");
Gen1Outcome one = runGen1(ctx, game, token, builds1Json, installPath, cb, cancelled);
Gen1Outcome one = runGen1(ctx, game, token, builds1Json, installPath, cb, cancelled, lang);
if (one.result != null || cancelled.get()) return one.result;
if (!"NO_CS_BUILDS".equals(one.error)) throw new InstallException("Download failed: " + one.error);
cb.onProgress("No Galaxy builds; fetching the installer…", 12);
@@ -250,6 +250,11 @@ public final class GogDownloadManager {
if (anyFailed.get()) { out.error = "one or more chunks failed to download"; return out; }
cb.onProgress("Finishing…", 96);
try {
GogMaintenance.captureDepot(game.gameId, installPath, gm.buildId, buildsJson, manifest, new JSONArray(depotJsons), resolved);
} catch (Exception e) {
cb.onLog("gog: maintenance inventory not recorded: " + e.getMessage());
}
writeFile(new File(installPath, MARKER), ("{\"gameId\":\"" + game.gameId + "\",\"buildId\":\"" + gm.buildId + "\"}").getBytes("UTF-8"));
deleteCounted(new File(installPath, ".gog_chunks"), cb);
String clientId = manifest.optString("clientId", null);
@@ -279,7 +284,7 @@ public final class GogDownloadManager {
String buildId = null, manifestUrl = null;
for (int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
if ("windows".equals(item.optString("os"))) {
if ("windows".equals(item.optString("os")) && (item.isNull("branch") || item.optString("branch").isEmpty())) {
buildId = item.optString("build_id");
manifestUrl = item.optString("link");
if (manifestUrl == null || manifestUrl.isEmpty()) manifestUrl = item.optString("meta_url");
@@ -328,7 +333,7 @@ public final class GogDownloadManager {
private static final class Gen1Outcome { Result result; String error; }
private static Gen1Outcome runGen1(Context ctx, GogGame game, String token, String buildsJson, File installPath, Callback cb, AtomicBoolean cancelled) {
private static Gen1Outcome runGen1(Context ctx, GogGame game, String token, String buildsJson, File installPath, Callback cb, AtomicBoolean cancelled, String language) {
Gen1Outcome out = new Gen1Outcome();
try {
JSONObject builds = new JSONObject(buildsJson);
@@ -346,6 +351,15 @@ public final class GogDownloadManager {
String manifestStr = decompressBytes(raw);
if (manifestStr == null) { out.error = "manifest decompress failed"; return out; }
JSONObject manifest = new JSONObject(manifestStr);
if (manifest.has("product")) {
try {
out.result = GogMaintenance.installContent(ctx, game, installPath, builds, language, cb, cancelled);
if (out.result == null && !cancelled.get()) out.error = "no usable public Windows build";
} catch (Exception e) {
out.error = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage();
}
return out;
}
JSONArray depots = manifest.optJSONArray("depot");
if (depots == null) { out.error = "no depot array"; return out; }
List<Gen1File> files = new ArrayList<>();
@@ -472,6 +486,7 @@ public final class GogDownloadManager {
String exe = pickExe(installPath, null, game.title);
if (exe.isEmpty()) throw new InstallException("The installer was extracted but no game executable was found");
cb.onLog("gog: installer extracted natively; game exe " + exe);
GogMaintenance.captureOffline(game.gameId, installPath, downloads);
return new Result(exe, "", total);
} catch (InstallerException e) {
throw e;
@@ -576,13 +591,13 @@ public final class GogDownloadManager {
return cleaned.isEmpty() ? "game" : cleaned;
}
private static String resolveRedirect(String url, String token) {
static String resolveRedirect(String url, String token) {
try {
if (url.startsWith("/")) url = "https://www.gog.com" + url;
for (int hop = 0; hop < 5; hop++) {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); conn.setInstanceFollowRedirects(false);
if (token != null) conn.setRequestProperty("Authorization", "Bearer " + token);
if (token != null && (new URL(url).getHost().equals("gog.com") || new URL(url).getHost().endsWith(".gog.com"))) conn.setRequestProperty("Authorization", "Bearer " + token);
int code = conn.getResponseCode();
String location = conn.getHeaderField("Location");
if (code == 301 || code == 302 || code == 303 || code == 307 || code == 308) {
@@ -686,6 +701,7 @@ public final class GogDownloadManager {
cb.onBytes(shown, planned, speedBps.get());
}
@Override public void onLog(String line) { cb.onLog(line); }
@Override public void onMaintenance(long networkBytes, long reusedBytes, long appliedBytes) {}
@Override public void onComplete(boolean success, boolean wasCancelled, boolean linkExpiry, String error, long bytesWritten, int filesDone) {
okRef.set(success); linkExpiryRef.set(linkExpiry); errRef.set(error == null ? "" : error); latch.countDown();
}
@@ -0,0 +1,58 @@
package com.droiddeck.launcher.stores.gog
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.io.RandomAccessFile
import java.security.MessageDigest
internal object GogEstimate {
data class Size(val download: Long, val required: Long)
private data class Chunk(val file: File, val offset: Long)
fun range(file: File, offset: Long, size: Long, md5: String): Boolean {
if (!file.isFile || offset < 0 || size < 0 || file.length() < offset + size || !md5.matches(Regex("[a-fA-F0-9]{32}"))) return false
return runCatching {
RandomAccessFile(file, "r").use { input ->
input.seek(offset)
val digest = MessageDigest.getInstance("MD5"); val buffer = ByteArray(64 * 1024); var left = size
while (left > 0) { val n = input.read(buffer, 0, minOf(left, buffer.size.toLong()).toInt()); check(n > 0); digest.update(buffer, 0, n); left -= n }
digest.digest().joinToString("") { "%02x".format(it) }.equals(md5, true)
}
}.getOrDefault(false)
}
fun calculate(folder: File, old: GogInstallRecord, target: GogInstallRecord, patches: JSONArray, reuseChunks: Boolean = true): Size {
val reusable = HashMap<Pair<String, Long>, MutableList<Chunk>>()
for (file in old.files.objects()) {
val source = GogFiles.inside(folder, file.getString("path")); var offset = 0L
for (chunk in file.optJSONArray("chunks")?.objects().orEmpty()) {
reusable.getOrPut(chunk.optString("md5").lowercase() to chunk.optLong("size")) { ArrayList() }.add(Chunk(source, offset))
offset += chunk.optLong("size")
}
}
var download = 0L; var required = 0L
for (file in target.files.objects()) {
if (file.optBoolean("directory") || GogFiles.matches(folder, file)) continue
val chunks = file.optJSONArray("chunks")?.objects().orEmpty()
val stamp = MessageDigest.getInstance("MD5").digest(file.getString("path").toByteArray()).joinToString("") { "%02x".format(it) }
val stage = File(GogFiles.dir(folder), "stage/$stamp")
var offset = 0L
var cost = if (chunks.isEmpty()) file.getLong("size") else chunks.sumOf { chunk ->
val size = chunk.getLong("size"); val hash = chunk.getString("md5")
val exists = reuseChunks && (range(stage, offset, size, hash) || reusable[hash.lowercase() to size].orEmpty().any { range(it.file, it.offset, size, hash) })
offset += size
if (exists) 0L else chunk.optLong("compressedSize")
}
val patch = patches.objects().firstOrNull { it.optString("path_target").replace('\\', '/') == file.getString("path") }
if (reuseChunks && patch != null) {
val source = GogFiles.inside(folder, patch.getString("path_source").replace('\\', '/'))
val delta = patch.getJSONArray("chunks").objects().sumOf { it.optLong("compressedSize") }
if (delta < cost && source.isFile && GogFiles.hash(source).equals(patch.getString("md5_source"), true)) cost = delta
}
download = Math.addExact(download, cost)
required = Math.addExact(required, maxOf(0, file.getLong("size") - stage.length()) + cost)
}
return Size(download, required)
}
}
@@ -0,0 +1,115 @@
package com.droiddeck.launcher.stores.gog
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.atomic.AtomicBoolean
import java.util.zip.InflaterInputStream
internal object GogFallback {
fun transfer(folder: File, plan: JSONObject, handle: DownloadQueue.JobHandle?, stop: AtomicBoolean,
callback: GogDownloadManager.Callback? = null) {
val stageRoot = File(GogFiles.dir(folder), "stage").apply { mkdirs() }
val files = plan.getJSONArray("files")
GogFiles.validate(files, folder)
var wire = 0L
fun progress(n: Int) { wire += n; handle?.progress(wire, plan.optLong("downloadBytes").coerceAtLeast(wire)); callback?.onBytes(wire, plan.optLong("downloadBytes").coerceAtLeast(wire), 0) }
for ((index, item) in files.objects().withIndex()) {
if (stop.get()) return
val destination = GogFiles.inside(folder, item.getString("path"))
if (item.optBoolean("directory")) { java.nio.file.Files.createDirectories(destination.toPath()); continue }
if (GogFiles.matches(folder, item)) continue
val stage = File(stageRoot, java.security.MessageDigest.getInstance("MD5").digest(item.getString("path").toByteArray()).joinToString("") { "%02x".format(it) })
val chunks = item.optJSONArray("chunks")?.objects().orEmpty()
FileOutputStream(stage).use { output ->
if (chunks.isNotEmpty()) {
for (chunk in chunks) {
if (stop.get()) return
val packed = File(stageRoot, "${stage.name}.packed")
val urls = endpoints(plan.getJSONObject("links"), item.getString("product"), GogContent.cdnPath(chunk.getString("compressedMd5")))
download(urls, packed, chunk.getLong("compressedSize"), stop, ::progress)
check(GogFiles.hash(packed).equals(chunk.getString("compressedMd5"), true)) { "GOG compressed chunk checksum mismatch" }
val digest = java.security.MessageDigest.getInstance("MD5")
var count = 0L
packed.inputStream().buffered().use { raw ->
raw.mark(2); val first = raw.read(); raw.reset()
val stored = chunk.getLong("size") == chunk.getLong("compressedSize") && chunk.getString("md5").equals(chunk.getString("compressedMd5"), true)
val input = if (!stored && first == 0x78) InflaterInputStream(raw) else raw
val buffer = ByteArray(64 * 1024)
while (true) {
if (stop.get()) return
val n = input.read(buffer); if (n < 0) break
count += n; check(count <= chunk.getLong("size")) { "GOG chunk exceeds expected size" }
digest.update(buffer, 0, n); output.write(buffer, 0, n)
}
}
check(count == chunk.getLong("size") && digest.digest().joinToString("") { "%02x".format(it) }.equals(chunk.getString("md5"), true)) { "GOG chunk checksum mismatch" }
packed.delete()
}
} else if (item.getLong("size") > 0) {
val remote = item.getString("remotePath")
val urls = if (remote.startsWith("https://")) listOf(remote) else endpoints(plan.getJSONObject("links"), item.getString("product"), remote.trimStart('/'))
val range = item.getLong("offset")
val raw = File(stageRoot, "${stage.name}.range")
download(urls, raw, item.getLong("size"), stop, ::progress, range)
raw.inputStream().use { it.copyTo(output) }; raw.delete()
}
output.fd.sync()
}
if (stop.get()) return
check(stage.length() == item.getLong("size")) { "GOG file size mismatch" }
if (item.optString("md5").isNotBlank()) check(GogFiles.hash(stage).equals(item.getString("md5"), true)) { "GOG file checksum mismatch" }
if (item.optString("sha256").isNotBlank()) check(GogFiles.hash(stage, "SHA-256").equals(item.getString("sha256"), true)) { "GOG file checksum mismatch" }
destination.parentFile!!.mkdirs()
GogFiles.inside(folder, item.getString("path"))
GogFiles.replace(stage, destination)
handle?.stage(DownloadStage.INSTALL); handle?.stageProgress((index + 1).toLong(), files.length().toLong())
callback?.onProgress("Downloading: ${destination.name}", ((index + 1) * 100 / files.length()))
}
val targetPaths = files.objects().mapTo(HashSet()) { it.getString("path").lowercase(java.util.Locale.ROOT) }
for (old in plan.optJSONArray("oldFiles")?.objects().orEmpty()) {
if (stop.get()) return
if (old.getString("path").lowercase(java.util.Locale.ROOT) !in targetPaths && GogFiles.matches(folder, old))
check(GogFiles.inside(folder, old.getString("path")).delete()) { "Could not remove obsolete GOG file" }
}
}
fun endpoints(links: JSONObject, product: String, path: String): List<String> = links.getJSONArray(product).strings().map { base ->
if (base.contains("{GALAXY_PATH}")) base.replace("{GALAXY_PATH}", path)
else base.substringBefore('?').trimEnd('/') + "/" + path + if ('?' in base) "?" + base.substringAfter('?') else ""
}
fun download(urls: List<String>, destination: File, size: Long, stop: AtomicBoolean, progress: (Int) -> Unit, range: Long? = null) {
var failure: Throwable? = null
for (attempt in 0..2) for (url in urls) {
if (stop.get()) return
val connection = URL(url).openConnection() as HttpURLConnection
try {
check(URL(url).protocol == "https" || URL(url).host in setOf("127.0.0.1", "localhost"))
connection.connectTimeout = 20_000; connection.readTimeout = 30_000
if (range != null) connection.setRequestProperty("Range", "bytes=$range-${range + size - 1}")
check(connection.responseCode == if (range == null) 200 else 206) { "GOG download failed (HTTP ${connection.responseCode})" }
FileOutputStream(destination).use { output ->
connection.inputStream.use { input ->
val buffer = ByteArray(64 * 1024); var count = 0L
while (true) {
if (stop.get()) return
val n = input.read(buffer); if (n < 0) break
count += n; check(size <= 0 || count <= size) { "GOG response exceeds expected size" }
output.write(buffer, 0, n); progress(n)
}
check(size <= 0 || count == size) { "Incomplete GOG download" }
}
output.fd.sync()
}
return
} catch (e: Exception) { failure = e }
finally { connection.disconnect() }
}
throw failure ?: IllegalStateException("No GOG download URL")
}
}
@@ -0,0 +1,176 @@
package com.droiddeck.launcher.stores.gog
import com.droiddeck.launcher.stores.StoreGameSidecar
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.StandardCopyOption
import java.security.MessageDigest
import java.util.Locale
internal enum class GogOperation { UPDATE, REPAIR, PATCH, REFRESH }
internal data class GogInstallRecord(
val id: String,
val source: String,
val generation: Int = 0,
val build: String = "",
val version: String = "",
val branch: String = "",
val language: String = "en-US",
val products: List<String> = listOf(id),
val manifest: JSONObject = JSONObject(),
val files: JSONArray = JSONArray(),
val verified: Boolean = true,
) {
fun json() = JSONObject().put("schema", 1).put("id", id).put("source", source)
.put("generation", generation).put("build", build).put("version", version).put("branch", branch)
.put("language", language).put("products", JSONArray(products)).put("manifest", manifest)
.put("files", files).put("verified", verified)
fun write(folder: File) = GogFiles.write(File(GogFiles.dir(folder), "installed.json"), json())
companion object {
fun parse(o: JSONObject): GogInstallRecord {
require(o.optInt("schema") == 1) { "Unsupported GOG installation record" }
return GogInstallRecord(o.getString("id"), o.getString("source"), o.optInt("generation"),
o.optString("build"), o.optString("version"), o.optString("branch"), o.optString("language", "en-US"),
o.optJSONArray("products")?.strings().orEmpty().ifEmpty { listOf(o.getString("id")) },
o.optJSONObject("manifest") ?: JSONObject(), o.optJSONArray("files") ?: JSONArray(), o.optBoolean("verified", true))
}
fun read(folder: File): GogInstallRecord? = GogFiles.read(File(GogFiles.dir(folder), "installed.json"))?.let(::parse)
fun authenticBuild(folder: File, id: String): String = GogFiles.read(File(folder, "goggame-$id.id"))?.optString("buildId").orEmpty()
.ifBlank { GogFiles.read(File(folder, "goggame-$id.info"))?.optString("buildId").orEmpty() }
fun migrate(folder: File, sidecar: StoreGameSidecar): GogInstallRecord {
read(folder)?.let { require(it.id == sidecar.id); return it }
val legacy = GogFiles.read(File(folder, "_gog_manifest.json"))
val info = GogFiles.read(File(folder, "goggame-${sidecar.id}.info"))
val build = authenticBuild(folder, sidecar.id).ifBlank { legacy?.optString("buildId").orEmpty().ifBlank { sidecar.installVersion } }
val ids = folder.listFiles().orEmpty().mapNotNull { Regex("goggame-([0-9]+)\\.info").matchEntire(it.name)?.groupValues?.get(1) }
return GogInstallRecord(sidecar.id, if (legacy != null || sidecar.installVersion.isNotBlank()) "depot" else "offline",
legacy?.optInt("generation", if (build.isNotBlank()) 2 else 0) ?: if (build.isNotBlank()) 2 else 0,
build, info?.optString("versionName").orEmpty(), language = sidecar.extra[com.droiddeck.launcher.stores.StoreLanguage.EXTRA] ?: "en-US",
products = (listOf(sidecar.id) + ids).distinct()).also { it.write(folder) }
}
}
}
internal object GogFiles {
fun dir(folder: File): File = inside(folder, ".droiddeck-gog").apply { mkdirs() }
fun journal(folder: File): File = File(dir(folder), "operation.json")
fun inside(root: File, raw: String): File {
val path = raw.replace('\\', '/')
require(path.isNotBlank() && !path.startsWith('/') && ':' !in path && '\u0000' !in path &&
path.split('/').none { it.isEmpty() || it == "." || it == ".." }) { "Invalid GOG path: $raw" }
val base = root.canonicalFile
var out = base
for (part in path.split('/')) {
out = File(out, part)
require(!Files.isSymbolicLink(out.toPath())) { "GOG path is a symbolic link: $raw" }
}
require(out.canonicalFile.toPath().startsWith(base.toPath())) { "GOG path leaves installation" }
return out
}
fun read(file: File): JSONObject? {
require(!Files.isSymbolicLink(file.toPath())) { "GOG metadata is a symbolic link" }
return if (!file.exists()) null else JSONObject(file.readText())
}
fun write(file: File, value: JSONObject) {
require(!Files.isSymbolicLink(file.toPath()))
file.parentFile!!.mkdirs()
val tmp = File.createTempFile(".gog-", ".stage", file.parentFile)
try {
FileOutputStream(tmp).use { it.write(value.toString().toByteArray(Charsets.UTF_8)); it.fd.sync() }
replace(tmp, file)
} finally { tmp.delete() }
}
fun replace(from: File, to: File) {
require(!Files.isSymbolicLink(to.toPath()))
try { Files.move(from.toPath(), to.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) }
catch (_: java.nio.file.AtomicMoveNotSupportedException) { Files.move(from.toPath(), to.toPath(), StandardCopyOption.REPLACE_EXISTING) }
}
fun hash(file: File, algorithm: String = "MD5"): String {
val digest = MessageDigest.getInstance(algorithm)
file.inputStream().use { input -> val buffer = ByteArray(128 * 1024); while (true) { val n = input.read(buffer); if (n < 0) break; digest.update(buffer, 0, n) } }
return digest.digest().joinToString("") { "%02x".format(it) }
}
fun matches(folder: File, file: JSONObject): Boolean {
val f = inside(folder, file.getString("path"))
if (!Files.isRegularFile(f.toPath(), LinkOption.NOFOLLOW_LINKS) || f.length() != file.getLong("size")) return false
val md5 = file.optString("md5")
if (md5.matches(Regex("[a-fA-F0-9]{32}"))) return hash(f).equals(md5, true)
val sha = file.optString("sha256")
if (sha.isNotBlank()) return hash(f, "SHA-256").equals(sha, true)
val chunks = file.optJSONArray("chunks")?.objects().orEmpty()
var offset = 0L
return chunks.isNotEmpty() && chunks.all { chunk ->
val result = GogEstimate.range(f, offset, chunk.getLong("size"), chunk.getString("md5"))
offset += chunk.getLong("size"); result
} || f.length() == 0L
}
fun validate(files: JSONArray, folder: File) {
val paths = HashSet<String>()
val components = HashMap<String, String>()
for (file in files.objects()) {
val path = file.getString("path").replace('\\', '/')
inside(folder, path)
require(!path.startsWith(".droiddeck-", true) && path != StoreGameSidecar.FILE_NAME) { "GOG content overlaps launcher metadata" }
require(paths.add(path.lowercase(Locale.ROOT))) { "GOG paths differ only by case: $path" }
var parent = folder
var relative = ""
for (part in path.split('/')) {
relative = if (relative.isEmpty()) part else "$relative/$part"
val previous = components.putIfAbsent(relative.lowercase(Locale.ROOT), relative)
require(previous == null || previous == relative) { "GOG directory paths differ only by case: $path" }
require(parent.list()?.none { it != part && it.equals(part, true) } != false) { "An existing path differs only by case: $path" }
parent = File(parent, part)
}
}
}
}
internal fun JSONArray.objects(): List<JSONObject> = (0 until length()).map { getJSONObject(it) }
internal fun JSONArray.strings(): List<String> = (0 until length()).map { optString(it) }
internal data class GogBuild(val id: String, val version: String, val generation: Int, val branch: String, val link: String) {
companion object {
fun select(builds: JSONObject, pinned: String = "", branch: String = ""): GogBuild? {
val items = builds.optJSONArray("items")?.objects().orEmpty().filter { it.optString("os", "windows") == "windows" }
val item = if (pinned.isNotBlank()) items.firstOrNull { it.optString("build_id") == pinned || it.optString("legacy_build_id") == pinned }
else items.firstOrNull { it.optString("branch").let { b -> (if (b == "null") "" else b) == branch } }
return item?.let { GogBuild(it.optString("build_id"), it.optString("version_name"), it.optInt("generation", 2),
it.optString("branch").let { b -> if (b == "null") "" else b },
it.optString("link").ifBlank { it.optString("meta_url").ifBlank { it.optJSONArray("urls")?.optJSONObject(0)?.optString("url").orEmpty() } }) }
}
}
}
internal data class GogOfflinePart(val id: String, val name: String, val url: String, val size: Long, val md5: String)
internal data class GogOfflineDownload(val id: String, val name: String, val version: String, val language: String, val parts: List<GogOfflinePart>) {
val size: Long get() = parts.sumOf { it.size }
companion object {
fun parse(downloads: JSONObject, kind: String): List<GogOfflineDownload> = downloads.optJSONArray(kind)?.objects().orEmpty()
.filter { it.optString("os") == "windows" }.mapNotNull { entry ->
val files = entry.optJSONArray("files")?.objects().orEmpty()
val parts = files.mapNotNull { f ->
val url = f.optString("downlink").ifBlank { f.optString("manualUrl") }
if (url.isBlank()) null else GogOfflinePart(f.optString("id"), f.optString("filename"), url, f.optLong("size"), f.optString("md5"))
}
if (parts.isEmpty()) null else GogOfflineDownload(entry.optString("id").ifBlank { parts.first().id },
entry.optString("name", "GOG download"), entry.optString("version"), entry.optString("language"), parts)
}
}
}
@@ -0,0 +1,415 @@
package com.droiddeck.launcher.stores.gog
import android.content.Context
import androidx.compose.runtime.mutableStateMapOf
import com.droiddeck.launcher.agent.AgentGuest
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.*
import com.droiddeck.launcher.stores.download.*
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.io.RandomAccessFile
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
internal object GogMaintenance {
enum class State { UNKNOWN, CHECKING, CURRENT, AVAILABLE, FAILED }
data class Check(val state: State, val version: String = "", val reason: String = "")
data class Proposal(val folder: File, val before: GogInstallRecord, val target: GogInstallRecord,
val operation: GogOperation, val downloadBytes: Long, val diskBytes: Long, val patch: GogOfflineDownload? = null, val deltas: JSONArray = JSONArray(), val fullFiles: Boolean = false)
val checks = mutableStateMapOf<String, Check>()
private val workers = Executors.newFixedThreadPool(2)
private val checkedAt = java.util.concurrent.ConcurrentHashMap<String, Long>()
private val inFlight = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()
@Volatile private var account = ""
private val revision = java.util.concurrent.atomic.AtomicLong()
private const val HELPER = "/usr/local/bin/droiddeck-gog-maintenance"
const val OPERATION = "gogOperation"
const val FOLDER = "gogFolder"
fun reset() {
revision.incrementAndGet()
account = ""; checkedAt.clear()
StoresState.post { checks.clear() }
}
fun checkInstalled(context: Context, games: List<InstalledStoreGame>) {
val user = StoreAccounts.displayName(context, Store.GOG).orEmpty()
if (user != account) { reset(); account = user }
if (user.isBlank()) return
games.filter { it.sidecar.store == Store.GOG && it.sidecar.isInstalled }.forEach { check(context, it) }
}
fun check(context: Context, game: InstalledStoreGame, force: Boolean = false) {
val key = game.folder.absolutePath
if (!force && System.currentTimeMillis() - (checkedAt[key] ?: 0) < 30 * 60_000) return
if (!inFlight.add(key)) return
val owner = revision.get()
StoresState.post { checks[game.sidecar.id] = Check(State.CHECKING) }
workers.execute {
val result = runCatching {
var old = GogInstallRecord.migrate(game.folder, game.sidecar)
if (!old.verified || GogFiles.journal(game.folder).exists()) Check(State.UNKNOWN, reason = "Finish or recover the GOG maintenance operation first")
else {
val token = GogContent.token(context)
if (old.source == "depot") {
val builds = GogContent.builds(old.id, token)
if (old.files.length() == 0 && old.build.isNotBlank()) GogBuild.select(builds, pinned = old.build)?.let { old = old.copy(branch = it.branch, generation = it.generation) }
val latest = GogBuild.select(builds, branch = old.branch)
when { latest == null -> Check(State.UNKNOWN, reason = "No build is available on the installed branch")
old.build.isBlank() -> Check(State.UNKNOWN, latest.version, "The installed build is unknown")
latest.id == old.build -> Check(State.CURRENT, old.version)
else -> Check(State.AVAILABLE, latest.version) }
} else {
val downloads = GogContent.product(old.id, token).getJSONObject("downloads")
val installer = offlineInstaller(downloads, old.language)
if (old.version.isBlank()) Check(State.UNKNOWN, installer.version, "The installed version is unknown")
else Check(if (old.version == installer.version) State.CURRENT else State.AVAILABLE, installer.version)
}
}
}.getOrElse { Check(State.FAILED, reason = it.message ?: "GOG update check failed") }
if (revision.get() == owner && (result.state == State.CURRENT || result.state == State.AVAILABLE)) checkedAt[key] = System.currentTimeMillis()
inFlight.remove(key)
StoresState.post { if (revision.get() == owner) checks[game.sidecar.id] = result }
}
}
fun offlinePatches(context: Context, game: InstalledStoreGame): List<GogOfflineDownload> =
GogOfflineDownload.parse(GogContent.product(game.sidecar.id, GogContent.token(context)).getJSONObject("downloads"), "patches")
internal fun offlineInstaller(downloads: JSONObject, language: String): GogOfflineDownload {
val installers = GogOfflineDownload.parse(downloads, "installers")
return installers.firstOrNull { it.language.equals(language, true) }
?: installers.firstOrNull { !it.language.equals("Neutral", true) && StoreLanguage.depotAccepted(arrayOf(it.language), language) }
?: installers.firstOrNull { it.language.equals("Neutral", true) }
?: error("No Windows offline installer is available for the installed language ($language)")
}
fun prepare(context: Context, game: InstalledStoreGame, operation: GogOperation, patch: GogOfflineDownload? = null, resume: Boolean = false): Proposal {
val folder = game.folder.canonicalFile
var old = GogInstallRecord.migrate(folder, game.sidecar)
val journal = GogFiles.read(GogFiles.journal(folder))
require(journal == null || journal.optString("folder") == folder.path) { "GOG recovery folder does not match" }
if (journal != null && journal.optString("phase") in setOf("patch-starting", "patch-applying", "patch-uncertain") && operation != GogOperation.REFRESH) error("The patch was interrupted. Inspect the installer result or use a full offline refresh; it will not be rerun automatically.")
require(journal == null || operation == GogOperation.REFRESH || journal.optString("operation") == operation.name) { "Resume the existing GOG operation or select a full offline refresh" }
val token = GogContent.token(context)
if (operation == GogOperation.PATCH) {
if (old.source == "depot" && old.manifest.length() == 0 && old.build.isNotBlank()) {
val exact = GogBuild.select(GogContent.builds(old.id, token), pinned = old.build)
?: error("The installed GOG setup manifest is unavailable; use a full offline refresh")
old = GogContent.snapshot(old, exact, token)
}
check(patch != null) { "Select a GOG patch" }
if (resume) require(journal?.optString("downloadVersion") == patch.version) { "The selected patch changed; select it again in Offline patches" }
val selected = GogContent.resolveDownload(patch, token)
return Proposal(folder, old, old.copy(source = "offline", version = selected.version, verified = false), operation, selected.size,
selected.size + folder.walkTopDown().onEnter { !java.nio.file.Files.isSymbolicLink(it.toPath()) && it.name != ".droiddeck-gog" }.filter { it.isFile }.sumOf { it.length() }, selected)
}
if (operation == GogOperation.REFRESH || old.source != "depot") {
require(operation != GogOperation.REPAIR) { "This offline installation has no depot manifest. Use a full offline refresh to restore its files." }
val download = GogContent.resolveDownload(offlineInstaller(GogContent.product(old.id, token).getJSONObject("downloads"), old.language), token)
if (resume) require(journal?.optString("downloadId") == download.id && journal.optString("downloadVersion") == download.version) { "The previous offline installer is no longer available; select a new full offline refresh" }
if (old.products.any { it != old.id }) {
val pinned = journal?.optJSONObject("target")?.optString("build").orEmpty()
val build = GogBuild.select(GogContent.builds(old.id, token), pinned = pinned, branch = old.branch)
?: error("No depot build is available to preserve installed DLC during this refresh. Use Update instead.")
val target = GogContent.snapshot(old, build, token)
GogFiles.validate(target.files, folder)
val native = GogNative.isAvailable()
val remaining = GogEstimate.calculate(folder, old, target, JSONArray(), reuseChunks = native)
return Proposal(folder, old, target, GogOperation.REFRESH, Math.addExact(download.size, remaining.download),
Math.addExact(Math.multiplyExact(download.size, 3), remaining.required), download, fullFiles = !native)
}
val target = old.copy(source = "offline", build = "", generation = 0, version = download.version, manifest = JSONObject(), files = JSONArray(), verified = true)
return Proposal(folder, old, target, GogOperation.REFRESH, download.size, download.size * 3, download)
}
require(old.verified || operation != GogOperation.REPAIR) { "The patched installation must be reconciled before repair" }
val pinned = journal?.optJSONObject("target")?.let(GogInstallRecord::parse)
val builds = GogContent.builds(old.id, token)
if (old.files.length() == 0 && old.build.isNotBlank()) GogBuild.select(builds, pinned = old.build)?.let { old = old.copy(branch = it.branch, generation = it.generation) }
val build = GogBuild.select(builds,
pinned = pinned?.build ?: if (operation == GogOperation.REPAIR) old.build.ifBlank { error("The installed GOG build is unknown; update it first") } else "",
branch = pinned?.branch ?: old.branch) ?: error("The requested GOG build is no longer available")
val target = GogContent.snapshot(old, build, token)
GogFiles.validate(target.files, folder)
var before = journal?.optJSONObject("before")?.let(GogInstallRecord::parse) ?: old
if (before.files.length() == 0 && before.build.isNotBlank()) {
val historical = GogBuild.select(builds, pinned = before.build)
if (historical != null) before = runCatching { GogContent.snapshot(before, historical, token) }.getOrDefault(before)
}
val deltas = GogContent.patches(before, target, token)
val native = GogNative.isAvailable()
val size = GogEstimate.calculate(folder, before, target, deltas, reuseChunks = native)
return Proposal(folder, before, target, operation, size.download, size.required, deltas = deltas, fullFiles = !native)
}
fun resume(context: Context, game: InstalledStoreGame): Proposal {
val journal = GogFiles.read(GogFiles.journal(game.folder)) ?: error("GOG operation journal is missing")
val operation = GogOperation.valueOf(journal.getString("operation"))
val patch = if (operation == GogOperation.PATCH) offlinePatches(context, game)
.firstOrNull { it.id == journal.optString("downloadId") } ?: error("The selected GOG patch is no longer available") else null
return prepare(context, game, operation, patch, resume = true)
}
fun recoverPatch(context: Context, game: InstalledStoreGame) {
val folder = game.folder.canonicalFile
check(!DownloadQueue.isActive(game.key)) { "Wait for the GOG operation to finish" }
val journal = GogFiles.read(GogFiles.journal(folder)) ?: error("GOG patch journal is missing")
require(journal.optString("folder") == folder.path && journal.optString("operation") == GogOperation.PATCH.name)
require(journal.optString("phase") in setOf("patch-starting", "patch-applying", "patch-uncertain"))
RandomAccessFile(GogFiles.inside(folder, ".droiddeck-gog/lease"), "rw").use { lease ->
val lock = runCatching { lease.channel.tryLock() }.getOrNull() ?: error("Close the patch installer before verifying its result")
lock.use {
ensureIdle(context, folder)
val before = GogInstallRecord.parse(journal.getJSONObject("before"))
val buildId = GogInstallRecord.authenticBuild(folder, before.id).ifBlank { before.build }
check(buildId.isNotBlank()) { "The resulting build is unknown. Use a full offline refresh." }
val token = GogContent.token(context)
val build = GogBuild.select(GogContent.builds(before.id, token), pinned = buildId)
?: error("The resulting build manifest is unavailable. Use a full offline refresh.")
val target = GogContent.snapshot(before, build, token)
GogFiles.validate(target.files, folder)
check(target.files.objects().all { it.optBoolean("directory") || GogFiles.matches(folder, it) }) {
"The files do not match the reported build. Use a full offline refresh to recover."
}
val sidecar = StoreGameSidecar.parse(journal.getJSONObject("sidecar").toString()) ?: error("The original GOG settings are missing")
target.write(folder)
StoreInstalls.complete(context, folder, sidecar.copy(installVersion = target.build, state = StoreGameSidecar.STATE_INSTALLED))
check(GogFiles.journal(folder).delete()) { "Could not finish the GOG recovery record" }
}
}
checkedAt.remove(folder.path)
DownloadQueue.dismiss(game.key)
StoresState.notifyLibraryChanged(context)
StoresState.post { checks.remove(game.sidecar.id) }
}
fun enqueue(context: Context, game: InstalledStoreGame, proposal: Proposal) {
val app = context.applicationContext
require(game.folder.canonicalFile == proposal.folder)
check(!DownloadQueue.isActive("gog:${game.sidecar.id}")) { "GOG maintenance is already queued" }
check(!StoreInstallRoot.insufficientSpace(proposal.diskBytes, StoreInstallRoot.availableBytes(proposal.folder))) { "Not enough free space for GOG maintenance" }
val journal = JSONObject().put("schema", 1).put("folder", proposal.folder.path).put("operation", proposal.operation.name)
.put("before", proposal.before.json()).put("target", proposal.target.json()).put("sidecar", game.sidecar.toJson()).put("phase", "download")
proposal.patch?.let { journal.put("downloadId", it.id).put("downloadVersion", it.version) }
GogFiles.write(GogFiles.journal(proposal.folder), journal)
val item = CatalogItem(Store.GOG, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover,
extra = mapOf(OPERATION to proposal.operation.name, FOLDER to proposal.folder.path))
SavedQueue.remember(app, item, null)
enqueueJob(app, item, proposal)
}
private fun enqueueJob(context: Context, item: CatalogItem, proposal: Proposal) {
DownloadQueue.enqueue(context, DownloadEntry(Store.GOG, item.id, item.title, cover = item.tallImageUrl,
bytesTotal = proposal.downloadBytes, location = StoreInstallRoot.labelFor(context, proposal.folder))) { Job(context, proposal) }
}
fun restore(context: Context, item: CatalogItem) {
val folder = File(item.extra[FOLDER] ?: error("Missing GOG recovery folder")).canonicalFile
require(StoreInstallRoot.gameFolders(context).any { it.canonicalFile == folder }) { "GOG recovery folder is unavailable" }
val sidecar = StoreGameSidecar.read(folder) ?: error("GOG installation record is missing")
require(sidecar.store == Store.GOG && sidecar.id == item.id)
val journal = GogFiles.read(GogFiles.journal(folder)) ?: error("GOG operation journal is missing")
val operation = GogOperation.valueOf(journal.getString("operation"))
if (journal.optString("phase") in setOf("patch-starting", "patch-applying", "patch-uncertain")) {
DownloadQueue.recordFailed(context, DownloadEntry(Store.GOG, item.id, item.title), "The patch result needs recovery; open Offline patches")
return
}
val game = InstalledStoreGame(sidecar, folder)
SavedQueue.remember(context, item, null)
enqueueJob(context, item, resume(context, game))
}
private class Job(val app: Context, val proposal: Proposal) : DownloadQueue.DownloadJob {
val cancelled = AtomicBoolean(false)
@Volatile var applyingPatch = false
@Volatile private var running = false
@Volatile private var deleteCaches = false
override fun cancel(deleteFiles: Boolean) {
if (applyingPatch) return
deleteCaches = deleteCaches || deleteFiles
cancelled.set(true)
if (!running && deleteCaches) cleanCaches()
}
override fun run(handle: DownloadQueue.JobHandle): String? {
running = true
try { return perform(handle) }
finally {
running = false; applyingPatch = false; handle.interruptible(true)
if (deleteCaches) cleanCaches()
}
}
private fun cleanCaches() {
for (name in listOf("stage", "downloads", "extracted")) {
val root = GogFiles.inside(proposal.folder, ".droiddeck-gog/$name")
if (root.exists()) java.nio.file.Files.walk(root.toPath()).use { paths ->
paths.sorted(java.util.Comparator.reverseOrder()).forEach { java.nio.file.Files.deleteIfExists(it) }
}
}
}
private fun perform(handle: DownloadQueue.JobHandle): String? {
val folder = proposal.folder
val journal = GogFiles.read(GogFiles.journal(folder)) ?: error("GOG operation journal is missing")
val sidecar = StoreGameSidecar.parse(journal.getJSONObject("sidecar").toString()) ?: error("GOG previous installation is missing")
if (proposal.operation == GogOperation.PATCH) {
val result = GogOffline.apply(app, proposal, handle, cancelled, onApplying = { applyingPatch = true; handle.interruptible(false) })
applyingPatch = false; handle.interruptible(true)
if (!result || cancelled.get()) return null
} else {
RandomAccessFile(GogFiles.inside(folder, ".droiddeck-gog/lease"), "rw").use { lease ->
val lock = runCatching { lease.channel.tryLock() }.getOrNull() ?: error("Close the GOG game before updating it")
lock.use {
ensureIdle(app, folder)
sidecar.copy(state = StoreGameSidecar.STATE_UPDATING).write(folder)
GogFiles.write(GogFiles.journal(folder), journal.put("phase", "applying"))
if (proposal.operation == GogOperation.REFRESH) {
GogOffline.refresh(app, proposal, handle, cancelled)
if (!cancelled.get() && proposal.target.source == "depot") transfer(app, proposal, handle, cancelled)
} else transfer(app, proposal, handle, cancelled)
if (cancelled.get()) return null
}
}
}
if (cancelled.get()) return null
val target = GogInstallRecord.read(folder)?.takeIf { proposal.operation == GogOperation.PATCH || proposal.operation == GogOperation.REFRESH && proposal.target.source != "depot" } ?: proposal.target
check(target.verified) { "The patch completed, but its resulting version could not be verified. Inspect the game or use a full offline refresh." }
target.write(folder)
StoreInstalls.complete(app, folder, sidecar.copy(installVersion = target.build.ifBlank { target.version }, state = StoreGameSidecar.STATE_INSTALLED))
check(GogFiles.journal(folder).delete()) { "Could not finish the GOG recovery record" }
runCatching { cleanCaches() }.onFailure { handle.log("gog: completed; could not remove expendable cache: ${it.message}") }
checkedAt.remove(folder.path)
StoresState.post { checks.remove(sidecar.id) }
return folder.path
}
}
private fun ensureIdle(context: Context, folder: File) {
val game = AddedGames.single(context, folder.path) ?: return
check(SessionState.gameId != (game.appId and 0xffffffffL).toString()) { "Close the GOG game before maintenance" }
if (SessionState.running) {
val id = (game.steamAppId?.toLong() ?: game.appId) and 0xffffffffL
val guest = AddedGames.guestPath(context, folder) ?: error("The GOG folder is unavailable to Linux")
if (SessionState.suspended || AgentGuest.hello(context) == null) {
val root = AddedGames.guestPath(context, SessionPrefs.activeSteamRoot(context)) ?: error("The Steam folder is unavailable to Linux")
val rc = GuestCommand.run(context, listOf("/usr/bin/env", "STEAM_COMPAT_CLIENT_INSTALL_PATH=$root", HELPER, "idle", guest, id.toString(), game.guestExe),
extraBinds = StoreInstallRoot.externalBindSpecs(context), logName = "gog-idle", onLine = StoresState::logLine)
check(rc == 0) { "Close the GOG game before maintenance" }
return
}
val request = JSONObject().put("kind", "exec").put("argv", JSONArray(listOf(HELPER, "idle", guest, id.toString(), game.guestExe))).put("timeout", 15)
val result = AgentGuest.call(context, request, 20_000, trusted = true)
check(result.optBoolean("ok") && result.optInt("exitCode", -1) == 0) { "Close the GOG game before maintenance" }
}
}
private fun transfer(context: Context, proposal: Proposal, handle: DownloadQueue.JobHandle?, stop: AtomicBoolean, callback: GogDownloadManager.Callback? = null) {
val token = GogContent.token(context)
var patches = proposal.deltas
var previousWire = 0L
for (attempt in 0..4) {
if (stop.get()) return
val links = GogContent.links(proposal.target, GogContent.token(context))
val patchLinks = if (patches.length() > 0) runCatching { GogContent.links(proposal.target, token, patches = true) }.getOrElse { patches = JSONArray(); JSONObject() } else JSONObject()
val plan = JSONObject().put("files", proposal.target.files).put("oldFiles", proposal.before.files)
.put("patches", patches).put("links", links).put("patchLinks", patchLinks).put("downloadBytes", proposal.downloadBytes)
val optimized = GogNative.isAvailable()
val remaining = GogEstimate.calculate(proposal.folder, proposal.before, proposal.target, patches, reuseChunks = optimized).required
check(!StoreInstallRoot.insufficientSpace(remaining, StoreInstallRoot.availableBytes(proposal.folder))) { "Not enough free space for remaining GOG maintenance" }
handle?.diskSize(remaining)
if (!optimized) {
try { GogFallback.transfer(proposal.folder, plan, handle, stop, callback); return }
catch (e: Exception) {
if (stop.get()) return
if (attempt == 4 || Regex("HTTP (401|403|404|500)").find(e.message.orEmpty()) == null) throw e
handle?.log("gog: refreshing file-download links; verified replacements are retained")
continue
}
}
val latch = CountDownLatch(1)
var runWire = 0L
var success = false; var expired = false; var failure = "GOG download failed"
val listener = object : GogNative.Listener {
override fun onProgress(bytesDone: Long, bytesTotal: Long, filesDone: Int, filesTotal: Int, file: String, fileBytes: Long, verified: Boolean) {
handle?.stage(if (verified) DownloadStage.VERIFY else DownloadStage.INSTALL)
handle?.stageProgress(filesDone.toLong(), filesTotal.toLong(), filesDone, filesTotal)
callback?.onStage(if (verified) "verify" else "install", filesDone.toLong(), filesTotal.toLong(), filesDone, filesTotal)
}
override fun onBytes(bytesDone: Long, bytesTotal: Long) {
runWire = bytesDone
handle?.progress(previousWire + bytesDone, (previousWire + bytesTotal).coerceAtLeast(previousWire + bytesDone))
callback?.onBytes(previousWire + bytesDone, (previousWire + bytesTotal).coerceAtLeast(previousWire + bytesDone), 0)
}
override fun onLog(line: String) { handle?.log(line); callback?.onLog(line) }
override fun onMaintenance(networkBytes: Long, reusedBytes: Long, appliedBytes: Long) { handle?.maintenance(reusedBytes, appliedBytes) }
override fun onComplete(ok: Boolean, cancelled: Boolean, linkExpiry: Boolean, error: String, bytesWritten: Long, filesDone: Int) {
success = ok; expired = linkExpiry; failure = error; latch.countDown()
}
}
val native = GogNative.start(2, arrayOf(plan.toString()), emptyArray(), proposal.folder.path, emptyArray(), "", 1, 1, false, "gog maintenance", listener)
check(native != 0L) { "GOG native engine could not start" }
try { while (!latch.await(200, TimeUnit.MILLISECONDS)) if (stop.get()) GogNative.cancel(native) }
finally { GogNative.release(native) }
if (stop.get()) return
if (success) {
for (file in proposal.target.files.objects()) if (!file.optBoolean("directory") && file.optString("md5").isBlank() && file.optString("sha256").isBlank())
file.put("sha256", GogFiles.hash(GogFiles.inside(proposal.folder, file.getString("path")), "SHA-256"))
return
}
if (!expired || attempt == 4) error(failure)
previousWire += runWire
handle?.log("gog: refreshing expired download links; validated files and chunks are retained")
}
}
@JvmStatic
fun installContent(context: Context, game: GogGame, folder: File, builds: JSONObject, language: String,
callback: GogDownloadManager.Callback, cancelled: AtomicBoolean): GogDownloadManager.Result? {
val build = GogBuild.select(builds) ?: return null
folder.mkdirs()
val old = GogInstallRecord(game.gameId, "depot", language = language)
val target = GogContent.snapshot(old, build, GogContent.token(context))
GogFiles.validate(target.files, folder)
val bytes = target.files.objects().sumOf { it.optJSONArray("chunks")?.objects()?.sumOf { c -> c.optLong("compressedSize") }?.takeIf { n -> n > 0 } ?: it.optLong("size") }
val disk = target.files.objects().sumOf { it.optLong("size") }
check(!StoreInstallRoot.insufficientSpace(disk, StoreInstallRoot.availableBytes(folder))) { "Not enough free space for GOG installation" }
callback.onSizes(bytes, disk)
transfer(context, Proposal(folder, old, target, GogOperation.UPDATE, bytes, disk), null, cancelled, callback)
if (cancelled.get()) return null
target.write(folder)
val result = GogDownloadManager.Result(GogDownloadManager.pickExe(folder, null, game.title), build.id, disk)
result.language = target.language
result.dependencies = target.manifest.optJSONArray("dependencies")?.strings().orEmpty()
result.dependenciesRead = true
return result
}
@JvmStatic
fun captureDepot(id: String, folder: File, build: String, buildsJson: String, manifest: JSONObject, depots: JSONArray, language: String) {
val selected = GogBuild.select(JSONObject(buildsJson), pinned = build)
val files = JSONArray()
for (depot in depots.strings()) for (item in JSONObject(depot).getJSONObject("depot").getJSONArray("items").objects()) {
val chunks = item.optJSONArray("chunks") ?: continue
files.put(JSONObject().put("path", item.getString("path").replace('\\', '/')).put("size", chunks.objects().sumOf { it.optLong("size") })
.put("md5", item.optString("md5")).put("chunks", chunks).put("product", id))
}
GogFiles.validate(files, folder)
GogInstallRecord(id, "depot", 2, build, selected?.version.orEmpty(), selected?.branch.orEmpty(), language,
manifest = GogContent.sanitize(manifest), files = files).write(folder)
}
@JvmStatic
fun captureOffline(id: String, folder: File, downloads: JSONObject) {
val selected = GogOfflineDownload.parse(downloads, "installers").firstOrNull() ?: return
GogInstallRecord(id, "offline", version = selected.version, language = selected.language).write(folder)
}
}
@@ -15,6 +15,8 @@ object GogNative {
fun onBytes(bytesDone: Long, bytesTotal: Long)
fun onMaintenance(networkBytes: Long, reusedBytes: Long, appliedBytes: Long)
fun onLog(line: String)
fun onComplete(success: Boolean, cancelled: Boolean, linkExpiry: Boolean, error: String, bytesWritten: Long, filesDone: Int)
@@ -26,7 +28,7 @@ object GogNative {
fun isAvailable(): Boolean {
available?.let { return it }
val ok = try {
StoresNative.ensureLoaded() && nativeProbe() == 1
StoresNative.ensureLoaded() && nativeProbe() == 2
} catch (t: Throwable) {
Log.w(TAG, "native GOG engine unavailable: ${t.javaClass.simpleName}: ${t.message}")
false
@@ -0,0 +1,200 @@
package com.droiddeck.launcher.stores.gog
import android.content.Context
import com.droiddeck.launcher.agent.AgentGuest
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
internal object GogOffline {
private const val HELPER = "/usr/local/bin/droiddeck-gog-maintenance"
internal data class Layout(val source: File, val prefix: String)
internal fun layout(extracted: File, installed: File, id: String, executable: String): Layout {
val nested = executable.startsWith("app/", true) && !File(installed, "goggame-$id.info").isFile
return Layout(extracted, if (nested) "app/" else "")
}
internal fun validateDepotInstaller(extracted: File, target: GogInstallRecord) {
if (target.source != "depot") return
val builds = listOf(extracted, File(extracted, "app")).map { GogInstallRecord.authenticBuild(it, target.id) }.filter { it.isNotBlank() }
require(builds.isNotEmpty() && builds.all { it == target.build } && target.build.isNotBlank()) {
"The offline installer does not identify the selected depot build. Use Update to preserve installed DLC."
}
}
private fun download(context: Context, proposal: GogMaintenance.Proposal, handle: DownloadQueue.JobHandle, stop: AtomicBoolean): File {
val patch = proposal.patch ?: error("GOG download selection is missing")
val root = File(GogFiles.dir(proposal.folder), "downloads").apply { mkdirs() }
var first: File? = null; var bytes = 0L
for ((index, part) in patch.parts.withIndex()) {
if (stop.get()) return first ?: File(root, "cancelled")
val resolved = GogDownloadManager.resolveRedirect(part.url, GogContent.token(context)) ?: error("The GOG download link is unavailable")
val serverName = GogContent.downloadFilename(resolved).takeIf { it.endsWith(".exe", true) || it.endsWith(".bin", true) }
val name = part.name.ifBlank { serverName ?: error("GOG did not provide the installer part filename") }
require('/' !in name && '\\' !in name && name !in setOf(".", "..")) { "Invalid GOG installer filename" }
val file = GogFiles.inside(root, name)
val receipt = File(root, "part-$index.json")
val saved = GogFiles.read(receipt)
val complete = file.isFile && (part.size <= 0 || file.length() == part.size) && when {
part.md5.isNotBlank() -> GogFiles.hash(file).equals(part.md5, true)
saved?.optString("id") == part.id && saved.optString("filename") == name -> GogFiles.hash(file, "SHA-256") == saved.optString("sha256")
else -> false
}
if (!complete) {
val staging = GogFiles.inside(root, "$name.partial")
GogFallback.download(listOf(resolved), staging, part.size, stop, { n -> bytes += n; handle.progress(bytes, proposal.downloadBytes.coerceAtLeast(bytes)) })
if (stop.get()) return first ?: file
if (part.md5.isNotBlank()) check(GogFiles.hash(staging).equals(part.md5, true)) { "GOG installer checksum mismatch" }
GogFiles.replace(staging, file)
GogFiles.write(receipt, JSONObject().put("id", part.id).put("filename", name).put("sha256", GogFiles.hash(file, "SHA-256")))
}
if (index == 0) { check(file.extension.equals("exe", true)) { "GOG patch has no setup executable" }; first = file }
}
return first ?: error("GOG download has no files")
}
fun refresh(context: Context, proposal: GogMaintenance.Proposal, handle: DownloadQueue.JobHandle, stop: AtomicBoolean) {
val installer = download(context, proposal, handle, stop)
if (stop.get()) return
val extracted = File(GogFiles.dir(proposal.folder), "extracted").apply { mkdirs() }
val source = AddedGames.guestPath(context, installer) ?: error("The GOG installer is not visible to Linux")
val target = AddedGames.guestPath(context, extracted) ?: error("The GOG staging folder is not visible to Linux")
handle.stage(DownloadStage.INSTALL, "Extracting the full offline installer")
val rc = GuestCommand.run(context, listOf("/usr/local/bin/droiddeck-innoextract", "--gog", "--silent", "-d", target, source),
extraBinds = StoreInstallRoot.externalBindSpecs(context), cancelled = stop, logName = "gog-refresh", onLine = handle::log)
if (stop.get()) return
check(rc == 0) { "GOG installer extraction failed (exit $rc)" }
applyRefresh(proposal, extracted, handle, stop)
}
internal fun applyRefresh(proposal: GogMaintenance.Proposal, extracted: File, handle: DownloadQueue.JobHandle?, stop: AtomicBoolean) {
validateDepotInstaller(extracted, proposal.target)
val sidecar = StoreGameSidecar.read(proposal.folder) ?: error("The original GOG settings are missing")
val layout = layout(extracted, proposal.folder, proposal.before.id, sidecar.exe)
val files = layout.source.walkTopDown().onEnter { directory ->
check(!java.nio.file.Files.isSymbolicLink(directory.toPath())) { "GOG installer contains a symbolic link" }
directory.parentFile != extracted || directory.name !in setOf("tmp", "commonappdata", "userappdata", "localappdata")
}.filter { it != layout.source && it != File(extracted, "app") }.map { file ->
check(!java.nio.file.Files.isSymbolicLink(file.toPath()))
val relative = file.relativeTo(layout.source).invariantSeparatorsPath.removePrefix("app/")
JSONObject().put("path", layout.prefix + relative)
.put("size", if (file.isDirectory) 0 else file.length()).put("directory", file.isDirectory)
.put("md5", if (file.isDirectory) "" else GogFiles.hash(file)).put("product", proposal.before.id) to file
}.toList().groupBy { it.first.getString("path") }.map { (_, entries) ->
check(entries.size == 1 || entries.all { it.first.getBoolean("directory") }) { "GOG installer has conflicting file locations" }
entries.first()
}
check(files.any { !it.first.getBoolean("directory") }) { "GOG installer contained no game files" }
val inventory = JSONArray(files.map { it.first })
GogFiles.validate(inventory, proposal.folder)
val executable = sidecar.exe.replace('\\', '/')
check(files.any { !it.first.getBoolean("directory") && it.first.getString("path").equals(executable, true) } ||
proposal.before.verified && proposal.before.files.length() > 0 &&
proposal.before.files.objects().none { it.getString("path").equals(executable, true) } && GogFiles.inside(proposal.folder, executable).isFile) {
"The offline installer did not extract the game's executable. No installed files were changed."
}
val installed = proposal.target.copy(files = inventory)
GogFiles.write(File(GogFiles.dir(proposal.folder), "refresh-target.json"), installed.json())
for ((index, entry) in files.withIndex()) {
if (stop.get()) return
val (file, sourceFile) = entry
val destination = GogFiles.inside(proposal.folder, file.getString("path"))
if (file.getBoolean("directory")) java.nio.file.Files.createDirectories(destination.toPath()) else {
destination.parentFile!!.mkdirs()
GogFiles.replace(sourceFile, destination)
}
handle?.stageProgress((index + 1).toLong(), files.size.toLong())
}
if (proposal.target.source != "depot") {
val targetPaths = files.mapTo(HashSet()) { it.first.getString("path").lowercase(java.util.Locale.ROOT) }
for (old in proposal.before.files.objects()) if (old.getString("path").lowercase(java.util.Locale.ROOT) !in targetPaths && GogFiles.matches(proposal.folder, old))
check(GogFiles.inside(proposal.folder, old.getString("path")).delete())
installed.write(proposal.folder)
}
}
fun apply(context: Context, proposal: GogMaintenance.Proposal, handle: DownloadQueue.JobHandle, stop: AtomicBoolean, onApplying: () -> Unit): Boolean {
check(GogFiles.read(GogFiles.journal(proposal.folder))?.optString("phase") in setOf("download", "patch-ready")) {
"The patch result needs recovery. Inspect the installer or use a full offline refresh; the patch will not be run again."
}
val installer = download(context, proposal, handle, stop)
if (stop.get()) return false
val setup = GogContent.setupFiles(proposal.before, GogContent.token(context))
if (setup != null) {
GogFallback.transfer(proposal.folder, JSONObject().put("files", setup.first).put("links", setup.second)
.put("downloadBytes", setup.first.objects().sumOf { it.getJSONArray("chunks").objects().sumOf { chunk -> chunk.getLong("compressedSize") } }), handle, stop)
if (stop.get()) return false
}
val added = AddedGames.single(context, proposal.folder.path) ?: error("The GOG game shortcut is unavailable")
val id = (added.steamAppId?.toLong() ?: added.appId) and 0xffffffffL
val folder = AddedGames.guestPath(context, proposal.folder) ?: error("The GOG folder is unavailable to Linux")
val executable = AddedGames.guestPath(context, installer) ?: error("The GOG patch is unavailable to Linux")
context.startActivity(android.content.Intent(context, com.droiddeck.launcher.SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, if (SessionState.running) SessionState.mode else SessionService.MODE_DESKTOP)
.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK or android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP or android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP))
val deadline = System.currentTimeMillis() + 120_000
while (AgentGuest.hello(context) == null && System.currentTimeMillis() < deadline) { if (stop.get()) return false; Thread.sleep(250) }
check(AgentGuest.hello(context) != null) { "The Linux session did not become ready; open it and retry" }
val journal = GogFiles.read(GogFiles.journal(proposal.folder)) ?: error("GOG patch journal is missing")
journal.put("phase", "patch-ready")
File(GogFiles.dir(proposal.folder), "patch-status.json").delete()
GogFiles.write(GogFiles.journal(proposal.folder), journal)
val request = JSONObject().put("kind", "exec").put("timeout", 15)
.put("env", JSONObject().put("DROIDDECK_GOG_DESKTOP", if (SessionState.mode == SessionService.MODE_DESKTOP) "1" else "0"))
.put("argv", JSONArray(listOf(HELPER, "start", folder, id.toString(), executable, added.guestExe)))
if (stop.get()) return false
onApplying()
val response = AgentGuest.call(context, request, 20_000, trusted = true)
check(response.optBoolean("ok") && response.optInt("exitCode", -1) == 0) { "The GOG patch installer could not start; inspect the GOG log" }
handle.stage(DownloadStage.INSTALL, "Use the Linux session to finish or cancel the patch installer")
var nextStatus = System.currentTimeMillis() + 5_000
while (true) {
val status = GogFiles.read(File(GogFiles.dir(proposal.folder), "patch-status.json"))
if (status?.optString("state") in setOf("done", "failed", "uncertain")) {
check(status?.optString("state") == "done") { status?.optString("reason") ?: "GOG patch failed" }
break
}
check(SessionState.running) { "The patch session ended. Its result needs recovery; the patch will not be rerun automatically." }
check(!SessionState.suspended) { "The patch session was suspended. Resume it and verify recovery before retrying." }
if (System.currentTimeMillis() >= nextStatus) {
val query = JSONObject().put("kind", "exec").put("timeout", 5).put("argv", JSONArray(listOf(HELPER, "status", folder)))
val answer = AgentGuest.call(context, query, 10_000, trusted = true)
check(answer.optBoolean("ok") && answer.optInt("exitCode", -1) == 0) { "The patch helper could not be reached. Resume the Linux session and verify recovery." }
nextStatus = System.currentTimeMillis() + 5_000
}
Thread.sleep(500)
}
val info = GogFiles.read(File(proposal.folder, "goggame-${proposal.before.id}.info"))
val version = info?.optString("versionName").orEmpty()
val build = GogInstallRecord.authenticBuild(proposal.folder, proposal.before.id)
var record = proposal.target.copy(build = build, version = version, files = JSONArray(), manifest = JSONObject(), verified = false)
record.write(proposal.folder)
if (build.isNotBlank()) {
record = runCatching {
val token = GogContent.token(context)
val target = GogBuild.select(GogContent.builds(record.id, token), pinned = build)
val snapshot = target?.let { GogContent.snapshot(record, it, token) }
snapshot?.takeIf { it.files.objects().all { f -> f.optBoolean("directory") || GogFiles.matches(proposal.folder, f) } } ?: record
}.getOrDefault(record)
}
record.write(proposal.folder)
if (!record.verified) {
val before = StoreGameSidecar.read(proposal.folder) ?: error("The GOG installation record is missing")
before.copy(installVersion = "", state = StoreGameSidecar.STATE_UPDATING).write(proposal.folder)
val operation = GogFiles.read(GogFiles.journal(proposal.folder))!!
GogFiles.write(GogFiles.journal(proposal.folder), operation.put("phase", "patch-uncertain"))
}
return true
}
}
@@ -0,0 +1,45 @@
package com.droiddeck.launcher.stores.itch
import java.io.File
import java.io.FileInputStream
import java.nio.file.Files
internal object ItchArchives {
private val PACKED = setOf("zip", "7z", "rar", "tar", "gz", "bz2", "xz")
fun kind(file: File, filename: String): String {
val extension = filename.substringAfterLast('.', "").lowercase()
if (extension == "exe") return "exe"
return signature(file) ?: extension
}
private fun signature(file: File): String? {
val head = runCatching { FileInputStream(file).use { input -> ByteArray(300).also { input.read(it) } } }.getOrNull()
?: return null
fun at(i: Int, vararg bytes: Int) = bytes.indices.all { head.getOrNull(i + it) == bytes[it].toByte() }
return when {
at(0, 0x50, 0x4B) -> "zip"
at(0, 0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C) -> "7z"
at(0, 0x52, 0x61, 0x72, 0x21) -> "rar"
at(0, 0x1F, 0x8B) -> "gz"
at(0, 0x42, 0x5A, 0x68) -> "bz2"
at(0, 0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00) -> "xz"
at(257, 0x75, 0x73, 0x74, 0x61, 0x72) -> "tar"
else -> null
}
}
fun inner(folder: File): File? {
val found = ArrayList<File>()
fun walk(dir: File, depth: Int) {
val files = dir.listFiles() ?: return
for (file in files) {
if (Files.isSymbolicLink(file.toPath())) continue
if (file.isFile && signature(file) in PACKED) found.add(file)
else if (file.isDirectory && depth < 2 && !file.name.startsWith(".")) walk(file, depth + 1)
}
}
walk(folder, 0)
return found.maxByOrNull { it.length() }
}
}
@@ -0,0 +1,114 @@
package com.droiddeck.launcher.stores.itch
import com.droiddeck.launcher.stores.StoreNet
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.atomic.AtomicBoolean
internal object ItchBuilds {
private const val BASE = "https://api.itch.io"
private const val MAX_STEPS = 4
class Step(val buildId: Long, val patchFile: Long, val patchSize: Long, val signatureFile: Long)
fun buildId(upload: JSONObject): String {
val value = upload.opt("build_id") ?: upload.opt("buildId")
return when (value) {
is Number -> value.toLong().takeIf { it > 0 }?.toString().orEmpty()
is String -> value.takeIf { it.all(Char::isDigit) }?.toLongOrNull()?.takeIf { it > 0 }?.toString().orEmpty()
else -> ""
}
}
fun path(key: String, from: String, to: String, downloadKeyId: String): List<Step>? {
val fromId = from.toLongOrNull() ?: return null
val toId = to.toLongOrNull() ?: return null
val reply = ItchApi.get("/builds/$fromId/upgrade-paths/$toId" + keyQuery(downloadKeyId), key) ?: return null
return steps(reply, fromId, toId) { filesOf(key, it, downloadKeyId) }
}
fun steps(reply: JSONObject, fromId: Long, toId: Long, filesFor: (JSONObject) -> JSONArray?): List<Step>? {
val builds = (reply.optJSONObject("upgrade_path") ?: reply.optJSONObject("upgradePath"))?.optJSONArray("builds") ?: return null
val ids = (0 until builds.length()).mapNotNull { builds.optJSONObject(it) }
val after = ids.filter { it.optLong("id") != fromId }
if (after.isEmpty() || after.size > MAX_STEPS || after.last().optLong("id") != toId) return null
val steps = after.map { build ->
val files = filesFor(build) ?: return null
val patch = pick(files, "patch") ?: return null
val signature = pick(files, "signature")
Step(build.optLong("id"), patch.optLong("id"), patch.optLong("size"), signature?.optLong("id") ?: 0L)
}
return steps.takeIf { it.last().signatureFile > 0 }
}
fun fileUrl(buildId: Long, fileId: Long, downloadKeyId: String): String =
"$BASE/wharf/builds/$buildId/files/$fileId/download" + keyQuery(downloadKeyId)
fun download(url: String, key: String, target: File, cancelled: AtomicBoolean, progress: (Long) -> Unit): Boolean {
val first = open(url, key)
try {
val code = first.responseCode
val location = first.getHeaderField("Location")
if (code in 300..399 && location != null) {
first.disconnect()
val next = URL(URL(url), location).toString()
if (!next.startsWith("https://")) return false
return save(open(next, null), target, cancelled, progress)
}
return save(first, target, cancelled, progress)
} finally {
runCatching { first.disconnect() }
}
}
private fun save(conn: HttpURLConnection, target: File, cancelled: AtomicBoolean, progress: (Long) -> Unit): Boolean {
try {
if (conn.responseCode !in 200..299) return false
var done = 0L
val buffer = ByteArray(128 * 1024)
conn.inputStream.use { input ->
FileOutputStream(target).use { out ->
while (true) {
if (cancelled.get()) return false
val read = input.read(buffer)
if (read < 0) break
out.write(buffer, 0, read)
done += read
progress(done)
}
}
}
return true
} finally {
runCatching { conn.disconnect() }
}
}
private fun open(url: String, key: String?): HttpURLConnection =
(URL(url).openConnection() as HttpURLConnection).apply {
connectTimeout = 30_000
readTimeout = 60_000
instanceFollowRedirects = false
setRequestProperty("User-Agent", StoreNet.BROWSER_UA)
setRequestProperty("Accept", "*/*")
if (key != null) setRequestProperty("Authorization", "Bearer $key")
}
private fun filesOf(key: String, build: JSONObject, downloadKeyId: String): JSONArray? =
build.optJSONArray("files")
?: ItchApi.get("/builds/${build.optLong("id")}" + keyQuery(downloadKeyId), key)?.optJSONObject("build")?.optJSONArray("files")
private fun pick(files: JSONArray, type: String): JSONObject? {
val all = (0 until files.length()).mapNotNull { files.optJSONObject(it) }
.filter { it.optString("type") == type && it.optString("state", "uploaded") == "uploaded" }
return all.firstOrNull { subType(it) == "optimized" } ?: all.firstOrNull { subType(it) == "default" }
}
private fun subType(file: JSONObject): String = file.optString("sub_type", file.optString("subType", "default"))
private fun keyQuery(downloadKeyId: String): String = if (downloadKeyId.isBlank()) "" else "?download_key_id=$downloadKeyId"
}
@@ -13,6 +13,7 @@ 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
@@ -25,6 +26,7 @@ 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(
@@ -33,6 +35,10 @@ internal class ItchInstaller(
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()
override fun run(handle: DownloadQueue.JobHandle): String? {
val key = ItchAuth.key(app)
@@ -40,7 +46,10 @@ internal class ItchInstaller(
val downloadKeyId = item.extra["downloadKeyId"].orEmpty()
if (downloadKeyId.isBlank() && !item.isFree) throw IllegalStateException(app.getString(R.string.stores_itch_not_owned))
val gameId = ItchGame.resolveId(item) ?: throw IllegalStateException(app.getString(R.string.stores_itch_no_game))
val resuming = StoreGameSidecar.read(folder)?.let { it.state == StoreGameSidecar.STATE_INSTALLING && it.id == item.id } == true
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.ITCH, item.id, item.title, item.imageUrl, item.imageUrl)
handle.stage(DownloadStage.MANIFEST)
val uploads = ItchApi.uploads(key, gameId, downloadKeyId)
@@ -53,19 +62,38 @@ internal class ItchInstaller(
val scratch = StoreInstallRoot.scratchDir(app, Store.ITCH, item.id)
scratch.mkdirs()
val archive = File(scratch, filename.ifBlank { "download.bin" })
val buildId = ItchBuilds.buildId(upload)
val exe = try {
handle.stage(DownloadStage.DOWNLOAD)
download(key, downloadKeyId, uploadId, upload.optString("updated_at", upload.optString("updatedAt")), archive, size, handle)
if (cancelled.get()) return null
handle.stage(DownloadStage.INSTALL)
install(archive, filename, handle, resuming)
var patched = updating && !resuming && previous?.isInstalled == true &&
patch(key, downloadKeyId, uploadId, buildId, size, scratch, handle)
if (cancelled.get()) {
if (patched) dropCaches(scratch)
return null
}
var picked: String? = null
if (patched) {
picked = install(archive, filename, handle, resuming, true)
if (picked == null) {
if (cancelled.get()) return null
handle.log("itch.io: the patched copy of ${item.title} has no exe, doing a full update")
patched = false
}
}
if (!patched) {
handle.stage(DownloadStage.DOWNLOAD)
download(key, downloadKeyId, uploadId, upload.optString("updated_at", upload.optString("updatedAt")), archive, size, handle)
if (cancelled.get()) return null
handle.stage(DownloadStage.INSTALL)
picked = install(archive, filename, handle, resuming, false)
}
picked
} catch (t: Throwable) {
if (!cancelled.get()) StoreInstalls.discard(app, folder, listOf(scratch))
if (!cancelled.get()) dropCaches(scratch)
throw t
}
if (exe == null) {
if (cancelled.get()) return null
StoreInstalls.discard(app, folder, listOf(scratch))
dropCaches(scratch)
throw IllegalStateException(app.getString(R.string.stores_itch_no_exe))
}
archive.delete()
@@ -75,20 +103,34 @@ internal class ItchInstaller(
id = item.id,
title = item.title,
exe = exe,
args = previous?.args.orEmpty(),
env = previous?.env.orEmpty(),
installVersion = upload.optString("updated_at", upload.optString("updatedAt")),
installedAt = System.currentTimeMillis(),
cover = item.imageUrl,
hero = item.imageUrl,
extra = mapOf("gameId" to gameId, "downloadKeyId" to downloadKeyId, "uploadId" to uploadId),
extra = mapOf("gameId" to gameId, "downloadKeyId" to downloadKeyId, "uploadId" to uploadId, "buildId" to buildId),
cloud = false,
)
StoreInstalls.complete(app, folder, sidecar) { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) }
ItchUpdates.applied(app, item.key)
return folder.path
}
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
if (deleteFiles) StoreInstalls.discard(app, folder, listOf(StoreInstallRoot.scratchDir(app, Store.ITCH, item.id)))
if (deleteFiles) dropCaches(StoreInstallRoot.scratchDir(app, Store.ITCH, 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(key: String, downloadKeyId: String, uploadId: String, version: String, target: File, expected: Long,
@@ -157,66 +199,114 @@ internal class ItchInstaller(
}
}
private fun install(archive: File, filename: String, handle: DownloadQueue.JobHandle, resuming: Boolean): String? {
folder.mkdirs()
private fun patch(key: String, downloadKeyId: String, uploadId: String, buildId: String, fullSize: Long, scratch: File, handle: DownloadQueue.JobHandle): Boolean {
val installed = previous?.extra.orEmpty()
val from = installed["buildId"].orEmpty()
if (installed["uploadId"] != uploadId || from.isBlank() || buildId.isBlank() || from == buildId) return false
val out = File(folder, ItchStaging.DIR)
ItchStaging.delete(out)
scratch.mkdirs()
val outcome = try {
ItchPatch.run(app, key, downloadKeyId, from, buildId, fullSize, folder, out, scratch, handle, cancelled)
} catch (t: Exception) {
ItchPatch.Outcome.Failed("${t.javaClass.simpleName} ${t.message}")
}
when (outcome) {
ItchPatch.Outcome.Applied -> {
handle.log("itch.io: patched ${item.title} from build $from to $buildId")
return true
}
ItchPatch.Outcome.Cancelled -> Unit
is ItchPatch.Outcome.Failed -> handle.log("itch.io: no patch for ${item.title}, doing a full update (${outcome.reason})")
}
ItchStaging.delete(out)
return false
}
private fun install(archive: File, filename: String, handle: DownloadQueue.JobHandle, resuming: Boolean, patched: Boolean = false): String? {
work = if (updating) File(folder, ItchStaging.DIR) else folder
if (updating && !patched) ItchStaging.delete(work)
work.mkdirs()
if (resuming) clearPartialInstall()
when (val kind = sniff(archive, filename)) {
"zip" -> unzip(archive, handle)
"7z" -> sevenZip(archive, handle)
"rar" -> unrar(archive, handle)
"exe" -> copy(archive, File(folder, filename.ifBlank { "game.exe" }))
"tar" -> untar(archive, null, handle)
"gz", "bz2", "xz" -> untar(archive, kind, handle) ?: single(archive, kind, handle)
else -> copy(archive, File(folder, filename.ifBlank { "game" }))
val exe = try {
if (!patched) 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)
if (cancelled.get()) break
inner.delete()
picked = StoreExe.pick(work, inner.name.substringBeforeLast('.').takeIf { it.endsWith(".exe", ignoreCase = true) }, item.title)
passes++
}
picked
} catch (t: Throwable) {
if (updating) ItchStaging.delete(work)
throw t
}
val hint = filename.substringBeforeLast('.')
val exe = StoreExe.pick(folder, hint.ifBlank { null }, item.title)
if (exe.isBlank()) {
handle.log("itch.io: 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 sniff(file: File, filename: String): String {
val extension = filename.substringAfterLast('.', "").lowercase()
if (extension == "exe") return "exe"
val head = runCatching { FileInputStream(file).use { input -> ByteArray(300).also { input.read(it) } } }.getOrNull()
?: return extension
fun at(i: Int, vararg bytes: Int) = bytes.indices.all { head.getOrNull(i + it) == bytes[it].toByte() }
return when {
at(0, 0x50, 0x4B) -> "zip"
at(0, 0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C) -> "7z"
at(0, 0x52, 0x61, 0x72, 0x21) -> "rar"
at(0, 0x1F, 0x8B) -> "gz"
at(0, 0x42, 0x5A, 0x68) -> "bz2"
at(0, 0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00) -> "xz"
at(257, 0x75, 0x73, 0x74, 0x61, 0x72) -> "tar"
else -> extension
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(folder, name.replace('\\', '/'))
val root = folder.canonicalPath
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
}
// No JVM library reads RAR5; the runtime's bsdtar (libarchive) does.
private fun unrar(archive: File, handle: DownloadQueue.JobHandle) {
if (!LinuxRuntime.isInstalled(app)) throw IllegalStateException(app.getString(R.string.stores_itch_archive, "rar"))
val binds = if (listOf(app.filesDir, app.cacheDir).any { folder.absolutePath.startsWith(it.absolutePath + "/") }) null
else listOf(folder.absolutePath)
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) { line ->
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", folder.absolutePath)) { line ->
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)
@@ -233,28 +323,31 @@ internal class ItchInstaller(
val total = archive.length()
var written = 0L
val buffer = ByteArray(64 * 1024)
SevenZFile.builder().setFile(archive).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)
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)
}
}
}
}
@@ -0,0 +1,124 @@
package com.droiddeck.launcher.stores.itch
import android.content.Context
import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
internal object ItchPatch {
private const val DIR = "/usr/local/lib/droiddeck-butler"
sealed interface Outcome {
data object Applied : Outcome
data object Cancelled : Outcome
data class Failed(val reason: String) : Outcome
}
fun ready(context: Context): Boolean {
if (!AddonPack.BUTLER.available || !LinuxRuntime.isInstalled(context)) return false
if (!AddonPack.BUTLER.installed(context)) {
AddonPack.BUTLER.ensure(context)
return false
}
return stage(context)
}
private val stageLock = Any()
private fun stage(context: Context): Boolean = synchronized(stageLock) { stageLocked(context) }
private fun stageLocked(context: Context): Boolean {
val pack = AddonPack.BUTLER.dir(context)
val root = File(LinuxRuntime.rootDir(context), DIR.removePrefix("/"))
val packaged = File(pack, "version").readText()
if (runCatching { File(root, "version").readText() }.getOrNull() == packaged && File(root, "butler").isFile) return true
root.mkdirs()
pack.listFiles().orEmpty().filter { it.isFile && it.name != "version" && it.name != AddonPack.COMPLETE }.forEach { source ->
val staged = File(root, source.name + ".staged")
source.inputStream().use { input -> staged.outputStream().use { input.copyTo(it) } }
staged.setExecutable(true, false)
check(staged.renameTo(File(root, source.name)))
}
File(root, "version").writeText(packaged)
return true
}
fun run(
app: Context, key: String, downloadKeyId: String, from: String, to: String, fullSize: Long, installed: File, out: File, scratch: File,
handle: DownloadQueue.JobHandle, cancelled: AtomicBoolean,
): Outcome {
if (!ready(app)) return Outcome.Failed("the patch tool is not ready")
val steps = ItchBuilds.path(key, from, to, downloadKeyId) ?: return Outcome.Failed("no patch path from build $from to $to")
if (fullSize > 0 && steps.sumOf { it.patchSize } > fullSize) return Outcome.Failed("the patches are larger than a full download")
val dir = File(scratch, "patches").apply { deleteRecursively(); mkdirs() }
try {
handle.stage(DownloadStage.DOWNLOAD)
val total = steps.sumOf { it.patchSize }
var finished = 0L
val patches = steps.mapIndexed { index, step ->
val file = File(dir, "$index.pwr")
val base = finished
val ok = ItchBuilds.download(ItchBuilds.fileUrl(step.buildId, step.patchFile, downloadKeyId), key, file, cancelled) {
handle.progress(base + it, total)
}
if (cancelled.get()) return Outcome.Cancelled
if (!ok) return Outcome.Failed("build ${step.buildId}: the patch did not download")
finished += step.patchSize
file
}
val last = steps.last()
val signature = File(dir, "final.sig")
val got = ItchBuilds.download(ItchBuilds.fileUrl(last.buildId, last.signatureFile, downloadKeyId), key, signature, cancelled) {}
if (cancelled.get()) return Outcome.Cancelled
if (!got) return Outcome.Failed("build ${last.buildId}: the signature did not download")
handle.stage(DownloadStage.INSTALL)
return apply(app, patches, signature, installed, out, scratch, cancelled)
} finally {
StoreInstalls.deleteTree(dir)
}
}
private fun apply(app: Context, patches: List<File>, signature: File, installed: File, out: File, scratch: File, cancelled: AtomicBoolean): Outcome {
var source = installed
var intermediate: File? = null
try {
patches.forEachIndexed { index, patch ->
val finalStep = index == patches.lastIndex
val target = if (finalStep) out else File(scratch, "patched-$index")
ItchStaging.delete(target)
target.mkdirs()
val staging = File(scratch, "butler-staging-$index").apply { deleteRecursively(); mkdirs() }
val args = mutableListOf("$DIR/butler", "apply", "--assume-yes", "--staging-dir", staging.absolutePath, "-d", target.absolutePath)
if (finalStep) args += listOf("--signature", signature.absolutePath)
args += listOf(patch.absolutePath, source.absolutePath)
val binds = listOf(installed, out, scratch).map { it.absolutePath }
.filter { path -> listOf(app.filesDir, app.cacheDir).none { path.startsWith(it.absolutePath + "/") } }
.distinct().takeIf { it.isNotEmpty() }
val tail = ArrayDeque<String>()
val code = try {
GuestCommand.run(app, args, logName = "itch-butler", extraBinds = binds, fastPath = true, cancelled = cancelled) { line ->
if (!line.startsWith("proot ")) {
if (tail.size == 4) tail.removeFirst()
tail.addLast(line)
}
}
} finally {
StoreInstalls.deleteTree(staging)
}
if (cancelled.get()) return Outcome.Cancelled
if (code != 0) return Outcome.Failed("butler exited $code: ${tail.joinToString(" | ")}")
intermediate?.let { StoreInstalls.deleteTree(it) }
intermediate = if (finalStep) null else target
source = target
}
return Outcome.Applied
} finally {
intermediate?.let { StoreInstalls.deleteTree(it) }
}
}
}
@@ -0,0 +1,30 @@
package com.droiddeck.launcher.stores.itch
import java.io.File
import java.nio.file.Files
internal object ItchStaging {
const val DIR = ".droiddeck-update"
const val RECORD = ".droiddeck-store.json"
fun merge(from: File, to: File, top: Boolean = true) {
for (child in from.listFiles().orEmpty()) {
if (top && child.name == RECORD) continue
val dest = File(to, child.name)
val destPath = dest.toPath()
if (child.isDirectory && !Files.isSymbolicLink(child.toPath()) && dest.isDirectory && !Files.isSymbolicLink(destPath)) {
merge(child, dest, false)
continue
}
if (Files.isSymbolicLink(destPath) || dest.exists()) {
delete(dest)
}
Files.move(child.toPath(), destPath)
}
}
fun delete(file: File) {
if (!Files.isSymbolicLink(file.toPath()) && file.isDirectory) file.listFiles().orEmpty().forEach { delete(it) }
file.delete()
}
}
@@ -0,0 +1,187 @@
package com.droiddeck.launcher.stores.itch
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.JSONArray
import org.json.JSONObject
import java.util.concurrent.atomic.AtomicBoolean
internal class ItchUpdate(val uploadId: String, val updatedAt: String, val filename: String, val replaced: Boolean)
internal object ItchUpdates {
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, ItchUpdate>()
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(uploads: JSONArray?, uploadId: String, version: String): ItchUpdate? {
if (uploads == null || version.isBlank()) return null
val current = ItchUploads.byId(uploads, uploadId)
if (current != null) {
val stamp = ItchUploads.updatedAt(current)
return if (stamp > version) ItchUpdate(uploadId, stamp, ItchUploads.filename(current), false) else null
}
val next = ItchUploads.newestWindows(uploads) ?: return null
val stamp = ItchUploads.updatedAt(next)
if (uploadId.isBlank() && stamp <= version) return null
return ItchUpdate(next.optString("id"), stamp, ItchUploads.filename(next), uploadId.isNotBlank())
}
internal fun encode(found: Map<String, ItchUpdate>): String = JSONObject().also { out ->
for ((key, u) in found) out.put(key, JSONObject().put("uploadId", u.uploadId).put("updatedAt", u.updatedAt).put("filename", u.filename).put("replaced", u.replaced))
}.toString()
internal fun decode(raw: String?): Map<String, ItchUpdate> {
val json = runCatching { JSONObject(raw.orEmpty()) }.getOrNull() ?: return emptyMap()
val out = LinkedHashMap<String, ItchUpdate>()
for (key in json.keys()) {
val u = json.optJSONObject(key) ?: continue
val id = u.optString("uploadId")
if (id.isBlank()) continue
out[key] = ItchUpdate(id, u.optString("updatedAt"), 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(ItchPrefs.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) {
ItchPrefs.get(app).edit().putString(KEY_FOUND, encode(available.toMap())).apply()
}
fun check(context: Context) {
val app = context.applicationContext
if (!running.compareAndSet(false, true)) return
val started = generation
Thread({
try {
restore(app)
val prefs = ItchPrefs.get(app)
if (System.currentTimeMillis() - prefs.getLong(KEY_AT, 0L) < THROTTLE_MS) return@Thread
val key = ItchAuth.key(app)
if (key.isBlank()) return@Thread
val games = StoresState.installed.toList().filter { it.sidecar.store == Store.ITCH && it.sidecar.isInstalled }
val found = LinkedHashMap<String, ItchUpdate>()
val answered = HashSet<String>()
val snapshot = HashMap<String, Pair<String, String>>()
var failed = false
games.forEachIndexed { i, game ->
if (i > 0) Thread.sleep(GAP_MS)
val extra = game.sidecar.extra
snapshot[game.key] = game.sidecar.installVersion to extra["uploadId"].orEmpty()
val gameId = extra["gameId"].orEmpty()
if (gameId.isNotEmpty()) {
val uploads = ItchApi.uploads(key, gameId, extra["downloadKeyId"].orEmpty())
if (uploads == null) failed = true
else {
answered += game.key
evaluate(uploads, extra["uploadId"].orEmpty(), game.sidecar.installVersion)?.let { found[game.key] = it }
}
} else failed = true
}
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 (snapshot[k] != now.sidecar.installVersion to now.sidecar.extra["uploadId"].orEmpty()) 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("itch.io: checked ${games.size} installed games, ${found.size} with updates")
} finally {
running.set(false)
}
}, "itch-updates").start()
}
fun checkGame(context: Context, game: InstalledStoreGame) {
val app = context.applicationContext
if (checkingKey != null) return
checkingKey = game.key
val started = generation
val version = game.sidecar.installVersion
val uploadId = game.sidecar.extra["uploadId"].orEmpty()
Thread({
try {
val key = ItchAuth.key(app)
val extra = game.sidecar.extra
val gameId = extra["gameId"].orEmpty()
val uploads = if (key.isBlank() || gameId.isEmpty()) null else ItchApi.uploads(key, gameId, extra["downloadKeyId"].orEmpty())
val found = evaluate(uploads, uploadId, version)
StoresState.post {
if (started != generation) return@post
val now = StoresState.installed.firstOrNull { it.key == game.key }
if (uploads != null && now != null && now.sidecar.installVersion == version && now.sidecar.extra["uploadId"].orEmpty() == uploadId) {
if (found != null) available[game.key] = found else available.remove(game.key)
save(app)
}
val text = when {
uploads == 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("itch.io: checked ${game.sidecar.title}, ${if (found != null) "update available" else "up to date"}")
} finally {
StoresState.post { checkingKey = null }
}
}, "itch-update-check").start()
}
fun start(context: Context, game: InstalledStoreGame, update: ItchUpdate) {
val app = context.applicationContext
if (StoresState.uninstalling.containsKey(game.key)) return
val root = game.folder.parentFile?.parentFile ?: return
val extra = game.sidecar.extra + ("uploadId" to update.uploadId)
val item = CatalogItem(
Store.ITCH, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover,
isFree = extra["downloadKeyId"].isNullOrBlank(), owned = true, extra = extra,
)
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++
ItchPrefs.get(app).edit().remove(KEY_AT).remove(KEY_FOUND).apply()
StoresState.post { available.clear() }
}
}
@@ -18,6 +18,14 @@ internal object ItchUploads {
return candidates.maxWithOrNull(compareBy({ it.optString("updated_at", it.optString("updatedAt")) }, { it.optLong("id") }))
}
fun newestWindows(uploads: JSONArray?): JSONObject? {
if (uploads == null) return null
val windows = (0 until uploads.length()).mapNotNull { uploads.optJSONObject(it) }
.filter { it.optString("storage") != "external" && !it.optBoolean("demo") && windows(it) }
val games = windows.filter { it.optString("type") in GAME_TYPES }
return games.ifEmpty { windows }.maxWithOrNull(compareBy({ updatedAt(it) }, { it.optLong("id") }))
}
fun windows(upload: JSONObject): Boolean {
val platforms = upload.optJSONObject("platforms")
if (platforms != null) {
@@ -52,6 +60,8 @@ internal object ItchUploads {
return (0 until uploads.length()).mapNotNull { uploads.optJSONObject(it) }.firstOrNull { it.optString("id") == id }
}
fun updatedAt(upload: JSONObject): String = upload.optString("updated_at", upload.optString("updatedAt"))
fun size(upload: JSONObject): Long = upload.optLong("size", upload.optLong("size_bytes"))
fun filename(upload: JSONObject): String = upload.optString("filename").substringAfterLast('/')
@@ -0,0 +1,158 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
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.runtime.staticCompositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.CommitTextCommand
import androidx.compose.ui.text.input.DeleteAllCommand
import androidx.compose.ui.text.input.EditCommand
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.ImeOptions
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.PlatformTextInputService
import androidx.compose.ui.text.input.SetSelectionCommand
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.input.TextInputService
import androidx.compose.ui.text.input.TextInputSession
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
class TypingRequest(
initial: TextFieldValue,
val imeOptions: ImeOptions,
private val onValue: (TextFieldValue) -> Unit,
private val onImeAction: (ImeAction) -> Unit,
private val onClose: () -> Unit = {},
) {
var value by mutableStateOf(initial)
fun send(next: TextFieldValue) {
value = next
onValue(next)
}
fun action() = onImeAction(imeOptions.imeAction)
fun close() = onClose()
companion object {
internal fun editsFor(next: TextFieldValue): List<EditCommand> = listOf(
DeleteAllCommand(),
CommitTextCommand(next.text, 1),
SetSelectionCommand(next.selection.start, next.selection.end),
)
}
}
internal val LocalBottomTyping = staticCompositionLocalOf { false }
internal class BottomScreenTextInput(private val fallback: TextInputService) : PlatformTextInputService {
private var session: TextInputSession? = null
override fun startInput(
value: TextFieldValue, imeOptions: ImeOptions,
onEditCommand: (List<EditCommand>) -> Unit, onImeActionPerformed: (ImeAction) -> Unit,
) {
session?.let { fallback.stopInput(it) }
session = null
if (DualScreenPanel.attached) DualScreenPanel.startTyping(TypingRequest(value, imeOptions, { onEditCommand(TypingRequest.editsFor(it)) }, onImeActionPerformed))
else session = fallback.startInput(value, imeOptions, onEditCommand, onImeActionPerformed)
}
override fun stopInput() {
session?.let { fallback.stopInput(it) }
session = null
DualScreenPanel.stopTyping()
}
override fun showSoftwareKeyboard() {
val active = session
if (active != null) active.showSoftwareKeyboard() else DualScreenPanel.showTyping()
}
override fun hideSoftwareKeyboard() {
val active = session
if (active != null) active.hideSoftwareKeyboard() else DualScreenPanel.hideTyping()
}
override fun updateState(oldValue: TextFieldValue?, newValue: TextFieldValue) {
val active = session
if (active != null) active.updateState(oldValue, newValue) else DualScreenPanel.updateTyping(newValue)
}
}
@Composable
internal fun TypingPanel(request: TypingRequest, onDone: () -> Unit) {
val colors = MaterialTheme.colorScheme
var field by remember(request) { mutableStateOf(request.value) }
LaunchedEffect(request.value) {
if (request.value.text != field.text) field = request.value
}
val focus = remember { FocusRequester() }
val keyboard = LocalSoftwareKeyboardController.current
LaunchedEffect(request) {
kotlinx.coroutines.delay(120)
runCatching { focus.requestFocus() }
keyboard?.show()
}
val options = request.imeOptions
val secret = options.keyboardType == KeyboardType.Password || options.keyboardType == KeyboardType.NumberPassword
Column(
Modifier.fillMaxSize().background(colors.background).padding(horizontal = 20.dp, vertical = 14.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text(stringResource(R.string.dual_typing_title), fontSize = 15.sp, fontWeight = FontWeight.SemiBold,
color = colors.onSurfaceVariant, modifier = Modifier.weight(1f))
Button(onClick = onDone, modifier = Modifier.testTag("dual-typing-done")) { Text(stringResource(R.string.dual_typing_done)) }
}
OutlinedTextField(
value = field,
onValueChange = { next ->
field = next
request.send(next)
},
singleLine = options.singleLine,
maxLines = if (options.singleLine) 1 else 4,
textStyle = MaterialTheme.typography.titleLarge,
visualTransformation = if (secret) PasswordVisualTransformation() else VisualTransformation.None,
keyboardOptions = KeyboardOptions(
capitalization = options.capitalization, autoCorrect = options.autoCorrect,
keyboardType = options.keyboardType, imeAction = options.imeAction,
),
keyboardActions = KeyboardActions(onAny = {
request.action()
onDone()
}),
modifier = Modifier.fillMaxWidth().focusRequester(focus).testTag("dual-typing-field"),
)
}
}
@@ -33,6 +33,9 @@ import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.layout.layout
import kotlinx.coroutines.delay
import androidx.compose.runtime.setValue
import androidx.compose.runtime.getValue
@@ -40,6 +43,20 @@ import androidx.compose.runtime.getValue
/** A grid of cards with a game page that floods out of the opened card and drains back into it. */
internal val LocalDetailFloor = compositionLocalOf<() -> Float> { { Float.MAX_VALUE } }
/** How far the host reaches past the page's padding, so a game page can paint to the screen edge and still inset its content. */
internal class DetailInset(val horizontal: Dp, val top: Dp)
internal val LocalDetailInset = compositionLocalOf { DetailInset(0.dp, 0.dp) }
private fun Modifier.bleed(horizontal: Dp, top: Dp): Modifier =
if (horizontal == 0.dp && top == 0.dp) this else layout { measurable, constraints ->
val h = horizontal.roundToPx()
val t = top.roundToPx()
val placeable = measurable.measure(
Constraints.fixed(constraints.maxWidth + h * 2, if (constraints.hasBoundedHeight) constraints.maxHeight + t else constraints.minHeight),
)
layout(constraints.maxWidth, placeable.height - t) { placeable.place(-h, -t) }
}
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
@Composable
internal fun CardDetailHost(
@@ -48,6 +65,8 @@ internal fun CardDetailHost(
gridScrolled: () -> Boolean,
onDetailFocus: (Boolean) -> Unit,
modifier: Modifier = Modifier,
bleedHorizontal: Dp = 0.dp,
bleedTop: Dp = 0.dp,
wrap: @Composable (key: String, content: @Composable () -> Unit) -> Unit = { _, content -> content() },
grid: @Composable () -> Unit,
detail: @Composable (key: String) -> Unit,
@@ -86,7 +105,7 @@ internal fun CardDetailHost(
val gridAlpha by animateFloatAsState(if (covering) 0f else 1f, if (covering) Motion.tw(320, 80) else Motion.tw(300, 100), label = "gridFade")
val fade = with(density) { 14.dp.toPx() }
Box(
modifier.clipToBounds()
modifier.bleed(bleedHorizontal, bleedTop).clipToBounds()
.onGloballyPositioned { viewportAt = it.positionInRoot(); viewportH = it.size.height }
.graphicsLayer { compositingStrategy = androidx.compose.ui.graphics.CompositingStrategy.Offscreen }
.drawWithContent {
@@ -100,7 +119,7 @@ internal fun CardDetailHost(
) {
CompositionLocalProvider(LocalFrontFocus provides if (covering) null else ff) {
Column(
modifier = Modifier.fillMaxSize()
modifier = Modifier.fillMaxSize().padding(horizontal = bleedHorizontal).padding(top = bleedTop)
.graphicsLayer { scaleX = gridScale; scaleY = gridScale; alpha = gridAlpha }
.focusProperties { enter = { if (coveringNow.value) FocusRequester.Cancel else FocusRequester.Default } }
.focusGroup(),
@@ -111,7 +130,7 @@ internal fun CardDetailHost(
val body: @Composable () -> Unit = {
Column(
Modifier.fillMaxSize().pointerInput(Unit) { detectTapGestures { } }
.verticalScroll(detailScroll).padding(top = 4.dp, bottom = 16.dp),
.verticalScroll(detailScroll).padding(bottom = 16.dp),
) {
Column(
Modifier.fillMaxWidth()
@@ -120,7 +139,7 @@ internal fun CardDetailHost(
.focusGroup(),
) {
val floor = { viewportAt.y + viewportH - with(density) { 16.dp.toPx() } - detailScroll.value }
CompositionLocalProvider(LocalDetailFloor provides floor) { detail(key) }
CompositionLocalProvider(LocalDetailFloor provides floor, LocalDetailInset provides DetailInset(bleedHorizontal, bleedTop + 4.dp)) { detail(key) }
}
}
}
@@ -43,6 +43,7 @@ class DeckControlsPanel(
private val customLayout: List<InputSurfaceElement>? = null,
private val inputRole: InputRole = InputRole.SECONDARY,
private val portraitDock: Boolean = false,
private val onMenu: (() -> Unit)? = null,
) : LinearLayout(context) {
private enum class Tab(val label: Int) { GAMEPAD(R.string.deck_tab_gamepad), GRIPS(R.string.deck_tab_grips), LEFT(R.string.deck_tab_left), RIGHT(R.string.deck_tab_right), BOTH(R.string.deck_tab_both) }
@@ -144,6 +145,10 @@ class DeckControlsPanel(
addView(tabs, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, dp(44)))
}
addView(centre, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f))
onMenu?.let {
addView(menuButton(context, it))
addView(space(dp(8)))
}
if (SessionState.mode == SessionService.MODE_STEAM) {
addView(roundButton("STEAM", context.getString(R.string.deck_open_steam_menu), onSteamMenu, wide = true))
addView(space(dp(8)))
@@ -304,39 +309,35 @@ class DeckControlsPanel(
show()
}
private fun roundButton(label: String, description: String, onClick: () -> Unit, wide: Boolean = false) =
TextView(context).apply {
text = label
contentDescription = description
textSize = if (wide) 13f else 20f
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
letterSpacing = if (wide) 0.08f else 0f
gravity = Gravity.CENTER
setTextColor(TEXT)
background = outline(CORNER_PILL, SURFACE)
setPadding(if (wide) dp(16) else 0, 0, if (wide) dp(16) else 0, 0)
minWidth = dp(44)
layoutParams = LayoutParams(if (wide) LayoutParams.WRAP_CONTENT else dp(44), dp(44))
setOnClickListener {
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
onClick()
}
/** Whether a finger going down at ([x], [y]) lands on one of the panel's controls. */
fun takesTouchAt(x: Float, y: Float): Boolean = controlUnder(this, x, y)
// Every control here takes the touches it gets: buttons and tabs (clickable), the scrolling tab strip,
// and the drawn surfaces, pads and face buttons. The layouts around them do not.
private fun controlUnder(view: View, x: Float, y: Float): Boolean {
if (view.visibility != VISIBLE || x < 0f || y < 0f || x >= view.width || y >= view.height) return false
if (view.isClickable || view is HorizontalScrollView || view is Surface || view is DirectionPad || view is FaceButtons) return true
val group = view as? ViewGroup ?: return false
return (group.childCount - 1 downTo 0).any { i ->
val child = group.getChildAt(i)
controlUnder(child, x + group.scrollX - child.x, y + group.scrollY - child.y)
}
}
private fun roundButton(label: String, description: String, onClick: () -> Unit, wide: Boolean = false) =
roundButton(context, label, description, onClick, wide)
private fun space(width: Int) = View(context).apply { layoutParams = LayoutParams(width, 1) }
private fun outline(radius: Float, fill: Int) = GradientDrawable().apply {
cornerRadius = radius * resources.displayMetrics.density
setColor(fill)
setStroke(dp(1), LINE)
}
private fun outline(radius: Float, fill: Int) = outline(context, radius, fill)
private fun filled(radius: Float, fill: Int) = GradientDrawable().apply {
cornerRadius = radius * resources.displayMetrics.density
setColor(fill)
}
private fun dp(value: Int): Int = (value * resources.displayMetrics.density + 0.5f).toInt()
private fun dp(value: Int): Int = dp(context, value)
private abstract class Surface(context: Context) : View(context) {
protected val density = resources.displayMetrics.density
@@ -743,5 +744,47 @@ class DeckControlsPanel(
private val TEXT = Color.rgb(0xF2, 0xF4, 0xF7)
private val TEXT_DIM = Color.rgb(0x7A, 0x80, 0x8A)
private val KNOB = Color.rgb(0x2A, 0x2D, 0x33)
internal fun dp(context: Context, value: Int): Int = (value * context.resources.displayMetrics.density + 0.5f).toInt()
internal fun outline(context: Context, radius: Float, fill: Int) = GradientDrawable().apply {
cornerRadius = radius * context.resources.displayMetrics.density
setColor(fill)
setStroke(dp(context, 1), LINE)
}
internal fun roundButton(context: Context, label: String, description: String, onClick: () -> Unit, wide: Boolean = false) =
TextView(context).apply {
text = label
contentDescription = description
textSize = if (wide) 13f else 20f
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
letterSpacing = if (wide) 0.08f else 0f
gravity = Gravity.CENTER
setTextColor(TEXT)
background = outline(context, CORNER_PILL, SURFACE)
setPadding(if (wide) dp(context, 16) else 0, 0, if (wide) dp(context, 16) else 0, 0)
minWidth = dp(context, 44)
layoutParams = LinearLayout.LayoutParams(if (wide) LinearLayout.LayoutParams.WRAP_CONTENT else dp(context, 44), dp(context, 44))
setOnClickListener {
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
onClick()
}
}
internal fun menuButton(context: Context, onClick: () -> Unit) = android.widget.ImageView(context).apply {
setImageResource(R.drawable.ic_stat_session)
setColorFilter(TEXT)
contentDescription = context.getString(R.string.touch_droiddeck_menu)
scaleType = android.widget.ImageView.ScaleType.CENTER_INSIDE
val pad = dp(context, 11)
setPadding(pad, pad, pad, pad)
background = outline(context, CORNER_PILL, SURFACE)
layoutParams = LinearLayout.LayoutParams(dp(context, 44), dp(context, 44))
setOnClickListener {
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
onClick()
}
}
}
}
@@ -174,7 +174,7 @@ private fun DesktopDock(
val pal = LocalPalette.current
val narrow = LocalNarrowPane.current
val available = s.emulators.filter { !it.installed }
val flatpaks = com.droiddeck.launcher.store.StoreState.installed
val flatpaks = com.droiddeck.launcher.store.StoreState.installed.filter { f -> apps.none { it.key == "flatpak:${f.id}" } }
val keys = installed.map { "emu:${it.id}" } + apps.map { "user:${it.key}" } + flatpaks.map { "flatpak:${it.id}" }
var lastAt by remember { mutableStateOf<Rect?>(null) }
var dockAt by remember { mutableStateOf<Rect?>(null) }
@@ -0,0 +1,371 @@
package com.droiddeck.launcher.ui
import android.app.ActivityOptions
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
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.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
class DualPanelModel(
val keys: List<String>,
val selected: String,
val badges: Set<String>,
val storeDownloads: Int,
val running: String?,
val theme: String,
val appScale: Int,
val onSelect: (String) -> Unit,
val onResume: () -> Unit,
)
object DualScreenPanel {
var model by mutableStateOf<DualPanelModel?>(null)
private var displayId = -1
private var activity: DualScreenActivity? = null
set(value) { field = value; available = value != null || launching }
private var launching = false
set(value) { field = value; available = value || activity != null }
private var ownerTask = -1
private var ownerYielded = false
var typing by mutableStateOf<TypingRequest?>(null)
private set
var typingShown by mutableStateOf(false)
private set
val shownOn: Int get() = if (activity != null || launching) displayId else -1
val attached: Boolean get() = activity != null
var available by mutableStateOf(false)
private set
fun startTyping(request: TypingRequest) {
typing = request
typingShown = true
}
fun stopTyping() {
typing = null
typingShown = false
}
fun stopTyping(request: TypingRequest) {
if (typing === request) stopTyping()
}
fun showTyping() {
if (typing != null) typingShown = true
}
fun finishTyping() {
val request = typing
hideTyping()
request?.close()
}
fun hideTyping() {
typingShown = false
}
fun updateTyping(value: TextFieldValue) {
val request = typing ?: return
if (request.value != value) request.value = value
}
fun show(context: Context, display: Int, task: Int) {
if (shownOn == display) { ownerTask = task; return }
hide()
displayId = display
ownerTask = task
ownerYielded = false
launching = true
val intent = Intent(context, DualScreenActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION)
runCatching {
context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle())
}.onFailure { launching = false; displayId = -1 }
}
fun hide() {
stopTyping()
launching = false
displayId = -1
activity?.finishAndRemoveTask()
activity = null
}
fun hide(task: Int) {
if (ownerTask == task || ownerTask < 0) hide()
}
internal fun attach(host: DualScreenActivity): Boolean {
if (!launching && activity == null) return false
if (activity !== host) activity?.finishAndRemoveTask()
activity = host
launching = false
return true
}
// The panel resumes when an app opens over the owner on the primary screen; pulling the owner back would hide that app.
fun yieldTo(task: Int, app: Boolean) {
if (ownerTask == task) ownerYielded = app
}
internal fun returnFocus(context: Context) {
if (ownerYielded) return
val task = ownerTask.takeIf { it >= 0 } ?: return
runCatching { (context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager).moveTaskToFront(task, 0) }
}
internal fun reclaimFocus(context: Context) {
if (ownerYielded) return
val task = ownerTask.takeIf { it >= 0 } ?: return
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
runCatching {
manager.appTasks.firstOrNull {
@Suppress("DEPRECATION")
(if (android.os.Build.VERSION.SDK_INT >= 29) it.taskInfo.taskId else it.taskInfo.persistentId) == task
}?.moveToFront() ?: manager.moveTaskToFront(task, 0)
}
}
internal fun detach(host: DualScreenActivity) {
if (activity === host) {
activity = null
displayId = -1
}
}
}
class DualScreenActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!DualScreenPanel.attach(this)) {
finishAndRemoveTask()
return
}
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
applyImmersiveMode()
setContent {
val model = DualScreenPanel.model
val request = DualScreenPanel.typing
val typingOn = request != null && DualScreenPanel.typingShown
LaunchedEffect(typingOn) { acceptFocus(typingOn) }
DroidDeckTheme(model?.theme, appScale = model?.appScale ?: com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE) {
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)) {
if (request != null && typingOn) TypingPanel(request) { if (DualScreenPanel.typing === request) DualScreenPanel.finishTyping() }
else if (model != null) DualPanelContent(model)
}
}
}
}
private fun acceptFocus(on: Boolean) {
if (on) {
unfocusPending = false
window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
runCatching { (getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager).moveTaskToFront(taskId, 0) }
} else {
unfocusPending = true
DualScreenPanel.returnFocus(this)
window.decorView.postDelayed({
if (!unfocusPending || DualScreenPanel.typingShown) return@postDelayed
if (window.decorView.hasWindowFocus()) DualScreenPanel.returnFocus(this) else dropFocus()
}, 400)
}
}
private var unfocusPending = false
private fun dropFocus() {
unfocusPending = false
}
override fun onResume() {
super.onResume()
if (!DualScreenPanel.typingShown) DualScreenPanel.returnFocus(this)
}
override fun onTopResumedActivityChanged(isTopResumedActivity: Boolean) {
super.onTopResumedActivityChanged(isTopResumedActivity)
if (isTopResumedActivity && !DualScreenPanel.typingShown) DualScreenPanel.returnFocus(this)
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
applyImmersiveMode()
if (!DualScreenPanel.typingShown) DualScreenPanel.reclaimFocus(this)
} else if (unfocusPending && !DualScreenPanel.typingShown) dropFocus()
}
@Suppress("OVERRIDE_DEPRECATION")
override fun onBackPressed() {
if (DualScreenPanel.typingShown) DualScreenPanel.finishTyping()
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (DualScreenPanel.typingShown && event.keyCode == KeyEvent.KEYCODE_BUTTON_B) {
if (event.action == KeyEvent.ACTION_UP && !event.isCanceled) DualScreenPanel.finishTyping()
return true
}
return super.dispatchKeyEvent(event)
}
override fun onDestroy() {
DualScreenPanel.detach(this)
super.onDestroy()
}
private fun applyImmersiveMode() {
@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)
}
}
@Composable
internal fun DualPanelContent(model: DualPanelModel) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(Modifier.fillMaxSize().padding(horizontal = 20.dp, vertical = 16.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text(stringResource(R.string.app_name), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = pal.signal)
Spacer(Modifier.size(12.dp))
val (label, _) = railLabelIcon(model.selected)
Text(stringResource(label), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis)
PanelClock()
}
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
val columns = if (model.keys.size > 6) 4 else 3
val rows = (model.keys.size + columns - 1) / columns
val gap = 12.dp
val tileHeight = ((maxHeight - gap * (rows - 1)) / rows).coerceAtLeast(64.dp)
Column(verticalArrangement = Arrangement.spacedBy(gap)) {
for (row in model.keys.chunked(columns)) {
Row(Modifier.fillMaxWidth().height(tileHeight), horizontalArrangement = Arrangement.spacedBy(gap)) {
for (key in row) PanelTile(key, key == model.selected, key in model.badges,
if (key == "stores") model.storeDownloads else 0, Modifier.weight(1f)) { model.onSelect(key) }
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
}
}
}
}
if (model.running != null) {
Row(
Modifier.fillMaxWidth().height(56.dp).clip(RoundedCornerShape(16.dp)).background(pal.good.copy(alpha = 0.18f))
.clickable(role = Role.Button, onClick = model.onResume).testTag("dual-resume").padding(horizontal = 18.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Box(Modifier.size(10.dp).clip(CircleShape).background(pal.good))
Spacer(Modifier.size(12.dp))
Text(stringResource(R.string.rail_resume_named, model.running), fontSize = 16.sp, fontWeight = FontWeight.SemiBold,
color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
}
@Composable
private fun PanelTile(key: String, current: Boolean, badge: Boolean, count: Int, modifier: Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val (label, icon) = railLabelIcon(key)
val shape = RoundedCornerShape(18.dp)
Box(
modifier.fillMaxSize().clip(shape)
.background(if (current) pal.signal.copy(alpha = 0.16f) else colors.surface)
.border(if (current) 2.dp else 1.dp, if (current) pal.signal else Color.White.copy(alpha = 0.06f), shape)
.clickable(role = Role.Tab, onClick = onClick).testTag("dual-rail-$key"),
contentAlignment = Alignment.Center,
) {
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
Icon(icon, contentDescription = null, tint = if (current) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(34.dp))
Text(stringResource(label), fontSize = 15.sp, fontWeight = FontWeight.SemiBold,
color = if (current) pal.signal else colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(horizontal = 6.dp))
}
if (badge) Box(Modifier.align(Alignment.TopEnd).padding(12.dp).size(10.dp).clip(CircleShape).background(AttentionAmber))
if (count > 0) Text(
if (count > 9) "9+" else count.toString(), fontSize = 12.sp, fontWeight = FontWeight.Bold, color = pal.onSignal,
modifier = Modifier.align(Alignment.TopEnd).padding(10.dp).clip(RoundedCornerShape(8.dp)).background(pal.signal)
.padding(horizontal = 6.dp, vertical = 1.dp),
)
}
}
@Composable
private fun PanelClock() {
val context = LocalContext.current
var now by remember { mutableStateOf(System.currentTimeMillis()) }
LaunchedEffect(Unit) {
while (true) {
now = System.currentTimeMillis()
kotlinx.coroutines.delay(60_000L - now % 60_000L)
}
}
Text(android.text.format.DateFormat.getTimeFormat(context).format(java.util.Date(now)), fontSize = 15.sp,
fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
@Composable
internal fun DualPanelPublisher(s: FrontEndState, selected: String, onSelect: (String) -> Unit, a: FrontEndActions) {
val badges = buildSet {
if (setupNeedsAttention(s)) add("setup")
if (s.updates.hasUpdate) add("updates")
}
val model = DualPanelModel(navigationKeys(s), selected, badges, s.storeDownloadsActive, s.running, s.theme, s.appScale, onSelect, a.onResume)
androidx.compose.runtime.SideEffect { DualScreenPanel.model = model }
androidx.compose.runtime.DisposableEffect(Unit) { onDispose { DualScreenPanel.model = null } }
}
internal fun dualPageStep(event: android.view.KeyEvent): Int? = when (event.keyCode) {
android.view.KeyEvent.KEYCODE_BUTTON_L2 -> -1
android.view.KeyEvent.KEYCODE_BUTTON_R2 -> 1
else -> null
}
@@ -94,7 +94,12 @@ internal class FocusGlide(view: View?) {
internal val LocalFocusGlide = staticCompositionLocalOf<FocusGlide?> { null }
internal object RingVeil {
var count by mutableIntStateOf(0)
private var state = mutableIntStateOf(0)
var count: Int
get() = state.intValue
set(value) { state.intValue = value }
internal fun reset() { state = mutableIntStateOf(0) }
}
@Composable
@@ -66,6 +66,8 @@ import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import com.droiddeck.launcher.session.SessionPrefs
import androidx.compose.ui.platform.LocalContext
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -126,6 +128,20 @@ internal fun navigationKeys(s: FrontEndState) = buildList {
add("setup"); add("updates")
}
internal object RailLabels {
var shown by mutableStateOf(true)
private set
fun load(context: android.content.Context) {
shown = SessionPrefs.railLabels(context)
}
fun set(context: android.content.Context, show: Boolean) {
shown = show
SessionPrefs.setRailLabels(context, show)
}
}
@Composable
internal fun SideRail(
s: FrontEndState, selected: String,
@@ -133,7 +149,9 @@ internal fun SideRail(
) {
val colors = MaterialTheme.colorScheme
val compact = LocalConfiguration.current.screenHeightDp < 420
val iconOnly = isNarrowScreen()
val railContext = LocalContext.current
remember { RailLabels.load(railContext) }
val iconOnly = isNarrowScreen() || !RailLabels.shown
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier.width(if (iconOnly) 64.dp else 92.dp).background(colors.surface).padding(vertical = if (compact) 8.dp else 12.dp),
@@ -173,24 +191,28 @@ internal fun SideRail(
}
}
internal fun railLabelIcon(key: String): Pair<Int, ImageVector> = when (key) {
"steam" -> R.string.rail_steam to Icons.Outlined.SportsEsports
"games" -> R.string.rail_games to Icons.Outlined.VideoLibrary
"stores" -> R.string.rail_stores to Icons.Outlined.LocalMall
"desktop" -> R.string.rail_desktop to Icons.Outlined.DesktopWindows
"components" -> R.string.rail_components to Icons.Outlined.Layers
"android-apps" -> R.string.rail_apps to Icons.Outlined.Apps
"setup" -> R.string.rail_setup to Icons.Outlined.Tune
else -> R.string.rail_updates to Icons.Outlined.SystemUpdate
}
internal fun setupNeedsAttention(s: FrontEndState): Boolean = !s.ready || (s.available != null && s.available != s.installed) ||
PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
@Composable
private fun NavigationItems(
s: FrontEndState, shown: String, compact: Boolean, iconOnly: Boolean, height: Dp, width: Dp,
place: (String) -> Modifier, onSelect: (String) -> Unit, onFocusSelect: (String) -> Unit,
) {
val setupNeedsAttention = !s.ready || (s.available != null && s.available != s.installed) ||
PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
val setupNeedsAttention = setupNeedsAttention(s)
for (key in navigationKeys(s)) {
val (label, icon) = when (key) {
"steam" -> R.string.rail_steam to Icons.Outlined.SportsEsports
"games" -> R.string.rail_games to Icons.Outlined.VideoLibrary
"stores" -> R.string.rail_stores to Icons.Outlined.LocalMall
"desktop" -> R.string.rail_desktop to Icons.Outlined.DesktopWindows
"components" -> R.string.rail_components to Icons.Outlined.Layers
"android-apps" -> R.string.rail_apps to Icons.Outlined.Apps
"setup" -> R.string.rail_setup to Icons.Outlined.Tune
else -> R.string.rail_updates to Icons.Outlined.SystemUpdate
}
val (label, icon) = railLabelIcon(key)
key(key) {
RailItem(stringResource(label), icon, key, shown == key, compact, iconOnly, height, width,
badge = (key == "setup" && setupNeedsAttention) || (key == "updates" && s.updates.hasUpdate),
@@ -69,6 +69,9 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalWindowInfo
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.layout.onGloballyPositioned
@@ -127,6 +130,11 @@ class FrontEndState(
val integrationFocus: com.droiddeck.launcher.core.SteamIntegration.Feature? = null,
val androidApps: List<HomeApp.LaunchableApp> = emptyList(),
val secondScreenDisplays: List<SecondScreenDisplay> = emptyList(),
val dualScreen: Boolean = false,
val dualScreenDevice: Boolean = false,
val dualScreenMode: String = com.droiddeck.launcher.input.DualScreen.MODE_AUTO,
val dualScreenLauncher: Boolean = true,
val dualScreenControls: Boolean = true,
val packages: List<PackageRow>? = null,
val packageCatalogLoading: Boolean = false,
val packageBusyId: String? = null,
@@ -229,6 +237,9 @@ class FrontEndActions(
val onLauncherOrientation: (Int) -> Unit = {},
val onLauncherFullscreen: (Boolean) -> Unit = {},
val onAnimationsEnabled: (Boolean) -> Unit = {},
val onDualScreenMode: (String) -> Unit = {},
val onDualScreenLauncher: (Boolean) -> Unit = {},
val onDualScreenControls: (Boolean) -> Unit = {},
val onDownloadSource: (String) -> Unit = {},
val onDownloadMirror: (String) -> Unit = {},
val onDownloadPrefix: (String) -> Unit = {},
@@ -258,7 +269,7 @@ class FrontEndActions(
val onCopyPhantomCommand: (Boolean) -> Unit = {},
val onDismissPhantomGate: () -> Unit = {},
val onStartWirelessAdbPairing: () -> Unit = {},
val onStartPairingGuide: (Int?) -> Boolean = { false },
val onStartPairingGuide: (Int?, Boolean) -> Boolean = { _, _ -> false },
val onShowPhantomGate: () -> Unit = {},
val onOpenNotificationSettings: () -> Unit = {},
val controller: ControllerActions? = null,
@@ -401,10 +412,14 @@ internal suspend fun focusSoon(target: () -> FocusRequester) {
@Composable
fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)? = null) {
val frontFocus = remember { FrontFocus() }
val textInput = androidx.compose.ui.platform.LocalTextInputService.current
val bottomTextInput = remember(textInput) { textInput?.let { androidx.compose.ui.text.input.TextInputService(BottomScreenTextInput(it)) } }
androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxSize()) {
CompositionLocalProvider(
LocalFrontFocus provides frontFocus,
LocalNarrowPane provides (maxWidth < NarrowPaneWidth),
androidx.compose.ui.platform.LocalTextInputService provides (if (s.dualScreen) bottomTextInput else textInput),
LocalBottomTyping provides s.dualScreen,
) { FrontEndScreenBody(s, a, page, frontFocus) }
}
}
@@ -431,6 +446,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) }
var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) }
var developerChoiceGuided by rememberSaveable { mutableStateOf(false) }
var developerChoiceToggle by rememberSaveable { mutableStateOf(false) }
var wirelessAdbDesiredEnabled by rememberSaveable { mutableStateOf(false) }
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
val colors = MaterialTheme.colorScheme
@@ -440,13 +456,26 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
val processSettingsPageVisible = phantomGateVisible || showWirelessAdbFix || showDeveloperDisplayChoice
val requestDeveloperOptions = {
developerChoiceGuided = false
developerChoiceToggle = false
if (s.secondScreenDisplays.isEmpty()) a.onOpenDeveloperOptions(null)
else showDeveloperDisplayChoice = true
}
val openDeveloperOptionsOn: (Int?) -> Unit = { displayId ->
if (developerChoiceGuided) a.onStartWirelessAdbPairing()
if (!developerChoiceGuided || !a.onStartPairingGuide(displayId)) a.onOpenDeveloperOptions(displayId)
val guided = developerChoiceGuided || developerChoiceToggle
if (!guided || !a.onStartPairingGuide(displayId, developerChoiceToggle)) a.onOpenDeveloperOptions(displayId)
developerChoiceGuided = false
developerChoiceToggle = false
}
val requestChildProcessToggle = {
if (!PhantomProcessLimit.hasDeveloperToggle() || com.droiddeck.launcher.core.GlobalSettings.developerOptionsOn(ctx)) {
requestDeveloperOptions()
} else {
developerChoiceGuided = false
developerChoiceToggle = true
if (s.secondScreenDisplays.isEmpty()) openDeveloperOptionsOn(null)
else showDeveloperDisplayChoice = true
}
}
val startGuidedPairing = {
if (!com.droiddeck.launcher.core.WirelessAdbPairingService.notificationsEnabled(ctx)) {
@@ -536,6 +565,18 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
val window = LocalWindowInfo.current
val androidContext = androidx.compose.ui.platform.LocalContext.current
var anyFocused by remember { mutableStateOf(false) }
val paneRequester = remember { FocusRequester() }
val focusManager = androidx.compose.ui.platform.LocalFocusManager.current
suspend fun focusDualPane() {
repeat(30) {
withFrameNanos { }
if (anyFocused) return
runCatching { paneRequester.requestFocus() }
if (anyFocused) return
focusManager.moveFocus(FocusDirection.Down)
if (anyFocused) return
}
}
androidx.compose.foundation.layout.BoxWithConstraints(
modifier = Modifier.fillMaxSize().background(colors.background)
.windowInsetsPadding(if (s.launcherFullscreen) WindowInsets.displayCutout else WindowInsets.systemBars)
@@ -546,7 +587,8 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
if (processSettingsPageVisible) return@LaunchedEffect
snapshotFlow { window.isWindowFocused }.first { it }
if (inputModeManager.inputMode != InputMode.Keyboard) inputModeManager.requestInputMode(InputMode.Keyboard)
focusWithinFrames({ anyFocused }) { if (frontFocus.primaryAttached > 0) frontFocus.primary else frontFocus.railFor(railSelection) }
if (s.dualScreen && frontFocus.primaryAttached == 0) focusDualPane()
else focusWithinFrames({ anyFocused }) { if (frontFocus.primaryAttached > 0) frontFocus.primary else frontFocus.railFor(railSelection) }
}
var openPage by remember { mutableStateOf<String?>(null) }
LaunchedEffect(s.pageKey) {
@@ -568,16 +610,22 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
return@LaunchedEffect
}
if (anyFocused) return@LaunchedEffect
focusWithinFrames({ anyFocused }) { if (frontFocus.primaryAttached > 0) frontFocus.primary else frontFocus.railFor(railSelection) }
if (s.dualScreen && frontFocus.primaryAttached == 0) focusDualPane()
else focusWithinFrames({ anyFocused }) { if (frontFocus.primaryAttached > 0) frontFocus.primary else frontFocus.railFor(railSelection) }
}
LaunchedEffect(railPicks) {
if (railPicks == 0 || processSettingsPageVisible) return@LaunchedEffect
kotlinx.coroutines.delay(Motion.ms(PAGE_EXIT_MS).toLong())
if (inputModeManager.inputMode != InputMode.Keyboard) return@LaunchedEffect
withTimeoutOrNull(1_000) { snapshotFlow { frontFocus.primaryAttached > 0 }.first { it } } ?: return@LaunchedEffect
val entry = withTimeoutOrNull(1_000) { snapshotFlow { frontFocus.primaryAttached > 0 }.first { it } }
if (entry == null) {
if (s.dualScreen) focusDualPane()
return@LaunchedEffect
}
focusWithinFrames({ frontFocus.focusedRail == null && anyFocused }) { frontFocus.paneEntry() }
}
val paneFocus = Modifier
.focusRequester(paneRequester)
.focusProperties {
enter = { frontFocus.paneEntry() }
exit = { direction ->
@@ -603,12 +651,31 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
focusWithinFrames({ frontFocus.last == r.control && anyFocused }) { frontFocus.items[r.control] ?: frontFocus.paneEntry() }
}
var screenAt by remember { mutableStateOf(Offset.Zero) }
if (s.dualScreen) DualPanelPublisher(s, railSelection, { key ->
if (processSettingsPageVisible) return@DualPanelPublisher
if (inputModeManager.inputMode != InputMode.Keyboard) inputModeManager.requestInputMode(InputMode.Keyboard)
focusManager.clearFocus(force = true)
onRailSelect(key)
}, a)
CompositionLocalProvider(LocalShowSection provides { key -> selected = key }) {
LauncherLayout(
bottomNavigation, pal.line,
Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() },
bottomNavigation && !s.dualScreen, pal.line,
Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() }
.then(if (s.dualScreen) Modifier.onKeyEvent { event ->
val step = dualPageStep(event.nativeKeyEvent) ?: return@onKeyEvent false
if (event.type == KeyEventType.KeyDown && !processSettingsPageVisible) {
val keys = navigationKeys(s)
val at = keys.indexOf(railSelectionNow.value)
keys.getOrNull(at + step)?.let { key ->
PageSwipe.direction = step
onRailSelect(key)
}
}
true
} else Modifier),
navigation = {
if (bottomNavigation) BottomBar(s, railSelection, onRailSelect, onRailFocus, a, railFocus)
if (s.dualScreen) Unit
else if (bottomNavigation) BottomBar(s, railSelection, onRailSelect, onRailFocus, a, railFocus)
else SideRail(s, railSelection, onRailSelect, onRailFocus, a, railFocus.fillMaxHeight())
},
) {
@@ -627,7 +694,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null)
else appToChooseDisplay = app
},
onOpenDeveloperOptions = requestDeveloperOptions,
onOpenDeveloperOptions = requestChildProcessToggle,
onRequestWirelessAdb = requestWirelessAdbFix,
onPairWirelessDebugging = startGuidedPairing,
)
@@ -662,7 +729,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
PhantomProcessGatePage(
status = s.phantomProcessStatus,
onDismiss = a.onDismissPhantomGate,
onOpenDeveloperOptions = requestDeveloperOptions,
onOpenDeveloperOptions = requestChildProcessToggle,
applyingSavedPairing = applyingSavedPairing,
onFixWithWirelessDebugging = fixPhantomLimit,
onEnterAddressManually = { requestWirelessAdbFix(false) },
@@ -699,6 +766,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
onDismiss = {
showDeveloperDisplayChoice = false
developerChoiceGuided = false
developerChoiceToggle = false
},
)
}
@@ -389,6 +389,9 @@ internal fun SetupPanel(
)
ToggleRow(host, "launcher-animations", stringResource(R.string.setup_animations), null,
s.animationsEnabled, onChange = a.onAnimationsEnabled)
val railContext = androidx.compose.ui.platform.LocalContext.current
remember { RailLabels.load(railContext) }
ToggleRow(host, "rail-labels", stringResource(R.string.setup_rail_labels), stringResource(R.string.setup_rail_labels_hint), RailLabels.shown) { RailLabels.set(railContext, it) }
LanguageRow(host, s.language, a.onLanguage)
ToggleRow(host, "show-stores", stringResource(R.string.setup_stores), null, s.gameStoresEnabled, onChange = a.onGameStoresEnabled)
}
@@ -418,6 +421,23 @@ internal fun SetupPanel(
if (s.launcherFullscreen) stringResource(R.string.setup_fullscreen_on) else stringResource(R.string.setup_fullscreen_off),
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,
)
}
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) }
}
}
}
val art: @Composable () -> Unit = {
@@ -841,9 +861,8 @@ private fun SettingCard(label: String, value: String, id: String, modifier: Modi
verticalArrangement = Arrangement.spacedBy(3.dp),
modifier = modifier.paneItem(id)
.graphicsLayer { scaleX = scale; scaleY = scale }
.clip(Shape14)
.background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
.glideBorder(hot, Shape14, pal.signal, pal.line2)
.then(if (LocalGlass.current != null) Modifier.glass(Shape14, if (hot) 0.04f else 0f) else Modifier.clip(Shape14).background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface))
.glideBorder(hot, Shape14, pal.signal, if (LocalGlass.current != null) Color.Transparent else pal.line2)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 14.dp, vertical = 12.dp),
Loaded 100 of 630 files, more files were not shown because too many files have changed in this diff. Show more