chore: merge main into feat/bt-controller-trinket

This commit is contained in:
Kurt Himebauch committed 2026-11-16 09:40:35 -05:00
commit dae53c29e0
441 files changed
+37779 -4222

No files matched your search

@@ -20,6 +20,7 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
com.droiddeck.launcher.runtime.NativeGuest.init(this)
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
com.droiddeck.launcher.ui.Themes.loadGradient(this)
com.droiddeck.launcher.ui.BuildWatermark.install(this)
@@ -48,14 +49,15 @@ class App : Application() {
com.droiddeck.launcher.ui.AgentPet.install(this)
if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent"
com.droiddeck.launcher.lab.LabNotice.started(this)
com.droiddeck.launcher.core.SteamIntegration.syncShortcutsListing(this)
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
com.droiddeck.launcher.update.AppUpdates.init(this)
com.droiddeck.launcher.update.UpdateWatch.sync(this, com.droiddeck.launcher.update.AppUpdates.follow(this, null))
com.droiddeck.launcher.core.DownloadSource.init(this)
prefetchAddonPacks()
GpuClockPin.clearLeftover(this)
com.droiddeck.launcher.input.UsbMouse.returnLeftover(this)
com.droiddeck.launcher.glasses.Glasses.init(this)
com.droiddeck.launcher.glasses.GlassesMenuMirror.initialize(this)
BwrapSpawner.start(this)
@@ -81,14 +83,17 @@ class App : Application() {
Thread({
runCatching {
if (com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app).isDirectory) {
com.droiddeck.launcher.core.AddonPack.PROOT.ensure(app)
if (!com.droiddeck.launcher.runtime.LinuxRuntime.patchedProot(app)) com.droiddeck.launcher.core.AddonPack.PROOT.ensure(app)
com.droiddeck.launcher.core.AddonPack.DIRECTAUDIO.ensure(app)
com.droiddeck.launcher.session.SessionFiles.ensureDirtStandIn(app)
}
if (com.droiddeck.launcher.stores.gog.GogComet.enabled(app)) com.droiddeck.launcher.core.AddonPack.COMET.ensure(app)
if (com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, com.droiddeck.launcher.stores.Store.XBOX) != null)
com.droiddeck.launcher.core.AddonPack.XBOX.ensure(app)
if (com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, com.droiddeck.launcher.stores.Store.UBISOFT) != null)
com.droiddeck.launcher.session.SessionFiles.ensureUbisoftService(app)
if (com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, com.droiddeck.launcher.stores.Store.ROCKSTAR) != null)
com.droiddeck.launcher.session.SessionFiles.ensureRockstarService(app)
com.droiddeck.launcher.handtracking.HandTracking.load(app)
}.onFailure { android.util.Log.w("App", "add-on pack prefetch failed", it) }
}, "addon-packs").start()
@@ -286,7 +286,13 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
// Builds before 0.5.0-nad1 turned the bridge on under Auto without recording it, and
// left it on for good (it wins over the pair). Under Auto that switch is taken as Auto's.
if (!SessionPrefs.maliFallbackKnown(activity))
SessionPrefs.setMaliFallbackByAuto(activity, if (SessionPrefs.vkBridge(activity)) "bridge" else "")
SessionPrefs.setMaliFallbackByAuto(
activity,
MaliAutoRoute.initialOwnership(
SessionPrefs.vkBridge(activity), bridgeExplicit(),
SessionPrefs.venus(activity), venusExplicit(),
),
)
// A lone imported PanVK Android driver set by hand stalls the display the same way
// ("black screen with the start-up logo"), so under Auto any imported display goes.
val display = SessionPrefs.androidDriver(activity)
@@ -356,8 +362,14 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val pair = pairs.firstOrNull { it.key == key }
val row = pairRows.firstOrNull { it.key == key }
when {
row?.active == true -> autoStatus = problem?.let { activity.getString(R.string.drivers_up_to_date_check_failed, it) }
?: activity.getString(R.string.upd_current_status)
row?.active == true -> {
if (MaliAutoRoute.shouldEnd(
SessionPrefs.maliFallbackByAuto(activity), gpu.family.mali,
pair?.key?.let { DriverPairs.isNonAdreno(it) } == true,
)) endMaliFallback()
autoStatus = problem?.let { activity.getString(R.string.drivers_up_to_date_check_failed, it) }
?: activity.getString(R.string.upd_current_status)
}
gpu.family == GpuInfo.Family.POWERVR && (pair == null || !pair.complete) -> {
// RADV is not published right now: the Xclipse falls back to the system route.
SessionPrefs.ensurePowerVrAutoDrivers(activity)
@@ -397,6 +409,12 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}, "gpu-driver-auto").start()
}
private fun bridgeExplicit(): Boolean =
MaliAutoRoute.userChoice(SessionPrefs.vkBridgeExplicit(activity), SessionPrefs.maliFallbackByAuto(activity), MaliAutoRoute.BRIDGE)
private fun venusExplicit(): Boolean =
MaliAutoRoute.userChoice(SessionPrefs.venusExplicit(activity), SessionPrefs.maliFallbackByAuto(activity), MaliAutoRoute.VENUS)
/**
* A Mali with no open driver pair to install ([missing] names the unpublished pair, or null when
* no PanVK build covers this GPU) runs through the phone's own driver: Mali (Venus) where this
@@ -410,12 +428,21 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val oldVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(activity)
val venus = oldVulkan == null && com.droiddeck.launcher.session.VenusComponent.available(activity)
if (oldVulkan != null) Log.i(TAG, "auto: Mali driver reports Vulkan $oldVulkan; Venus needs 1.2, the bridge stands in")
val ownership = MaliAutoRoute.fallbackOwnership(
venus,
SessionPrefs.vkBridge(activity), bridgeExplicit(),
SessionPrefs.venus(activity), venusExplicit(),
)
if (venus && !SessionPrefs.venus(activity)) {
SessionPrefs.setVenus(activity, true)
SessionPrefs.setMaliFallbackByAuto(activity, "venus")
if (SessionPrefs.vkBridge(activity) && !bridgeExplicit())
SessionPrefs.setVkBridge(activity, false)
SessionPrefs.setMaliFallbackByAuto(activity, ownership)
} else if (!venus && !SessionPrefs.vkBridge(activity)) {
SessionPrefs.setVkBridge(activity, true)
SessionPrefs.setMaliFallbackByAuto(activity, "bridge")
SessionPrefs.setMaliFallbackByAuto(activity, ownership)
} else if (ownership != MaliAutoRoute.NONE) {
SessionPrefs.setMaliFallbackByAuto(activity, ownership)
}
val route = activity.getString(if (venus) R.string.drivers_route_venus else R.string.drivers_route_bridge)
Log.i(TAG, "auto: Mali stand-in route $route (missing pair: ${missing ?: "none covers ${gpu.name}"})")
@@ -503,7 +530,9 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
// A route Auto switched on in place of a missing pair goes off now that one is
// here. A Mali bridge or Venus switch the user set stays: it wins for the session
// (DeviceSupport.vkBridge, VenusComponent.wanted) and the pair waits.
if (gpu.family.mali && DriverPairs.isNonAdreno(pair.key)) endMaliFallback()
if (MaliAutoRoute.shouldEnd(
SessionPrefs.maliFallbackByAuto(activity), gpu.family.mali, DriverPairs.isNonAdreno(pair.key),
)) endMaliFallback()
val restart = displayChanged && CompositorHost.isStarted
if (auto) {
val trial = AutoDriverTrial.current(activity)
@@ -744,4 +773,3 @@ internal fun Context.displayNameOf(uri: Uri): String? = if (uri.scheme == "file"
} catch (e: Exception) {
null
}
@@ -179,8 +179,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var syncFallback by mutableStateOf(true)
private var fsyncFirst by mutableStateOf(false)
private var gamescopeRealtime by mutableStateOf(false)
private var paceCores by mutableStateOf(true)
private var ramCapMb by mutableStateOf(0)
private var zramClient by mutableStateOf(true)
private var zramIdle by mutableStateOf(true)
private var vramCapMb by mutableStateOf(0)
private var gpuClockPin by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false)
@@ -193,6 +195,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var showPhantomGate by mutableStateOf(false)
private var directAudio by mutableStateOf(false)
private var picturePosition by mutableStateOf("center")
private var integerScaling by mutableStateOf(false)
private var stretch16x9 by mutableStateOf(false)
private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
@@ -365,15 +368,78 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
SteamIntegration.Feature.BRIGHTNESS -> integrationSettings(SteamIntegration.brightnessSettings(this))
SteamIntegration.Feature.HOME -> if (HomeApp.isDefault(this)) HomeApp.openSystemHomeSettings(this) else offerHomeScreen()
SteamIntegration.Feature.SHORTCUTS -> {
if (!integrationState.shortcuts) shortcutsTried = true
SteamIntegration.setShortcutsListed(this, true)
integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
if (integrationState.shortcuts) openShortcutSettings() else installShortcuts()
}
}
}
private fun openAppInfo() =
integrationSettings(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName")))
private fun openShortcutSettings() =
integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
private fun installShortcuts() {
if (ShortcutsInstall.running) return
ShortcutsInstall.running = true
Thread({
val result = runCatching {
val apk = SteamIntegration.bundledShortcuts(this)
when {
SteamIntegration.shortcutsInstalled(this, apk) -> {
ShortcutsInstall.running = false
ui.post { shortcutsReady() }
}
!com.droiddeck.launcher.update.SelfInstaller.canInstall(this) -> {
ShortcutsInstall.running = false
ui.post { integrationSettings(com.droiddeck.launcher.update.SelfInstaller.permissionIntent(this)) }
}
else -> com.droiddeck.launcher.update.SelfInstaller.install(this, apk, com.droiddeck.shortcuts.Relay.PACKAGE,
SteamIntegration.SHORTCUTS_STATUS) { id -> ShortcutsInstall.session = id }
}
}
result.onFailure { e ->
ShortcutsInstall.running = false
ui.post { shortcutsFailed(e.message) }
}
}, "shortcuts-install").start()
}
private fun shortcutsReady() {
shortcutsTried = true
Thread({
val deadline = android.os.SystemClock.uptimeMillis() + 3000
while (!SteamIntegration.shortcutsListed(this) && android.os.SystemClock.uptimeMillis() < deadline) Thread.sleep(100)
ui.post { openShortcutSettings() }
}, "shortcuts-listed").start()
}
private fun shortcutsFailed(message: String?) {
android.widget.Toast.makeText(this, message?.let { getString(R.string.integration_shortcuts_install_failed_with, it) }
?: getString(R.string.integration_shortcuts_install_failed), android.widget.Toast.LENGTH_LONG).show()
}
private val shortcutsInstallStatus = object : android.content.BroadcastReceiver() {
override fun onReceive(context: android.content.Context, intent: Intent) {
val session = intent.getIntExtra(android.content.pm.PackageInstaller.EXTRA_SESSION_ID, -1)
if (session < 0 || session != ShortcutsInstall.session) return
val status = intent.getIntExtra(android.content.pm.PackageInstaller.EXTRA_STATUS,
android.content.pm.PackageInstaller.STATUS_FAILURE)
if (status != android.content.pm.PackageInstaller.STATUS_PENDING_USER_ACTION) {
ShortcutsInstall.session = -1
ShortcutsInstall.running = false
}
when (status) {
android.content.pm.PackageInstaller.STATUS_PENDING_USER_ACTION -> {
val confirm = if (android.os.Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT)
val safe = confirm?.let { com.droiddeck.launcher.update.SelfInstaller.safeConfirmIntent(this@FrontEndActivity, it) }
if (safe == null || runCatching { startActivity(safe) }.isFailure) shortcutsFailed(null)
}
android.content.pm.PackageInstaller.STATUS_SUCCESS -> shortcutsReady()
else -> shortcutsFailed(intent.getStringExtra(android.content.pm.PackageInstaller.EXTRA_STATUS_MESSAGE))
}
}
}
private fun openAppInfo() = integrationSettings(SteamIntegration.shortcutsAppInfo())
private fun openWifiDiscoverySettings() {
if (!WifiDiscovery.permissionGranted(this)) {
@@ -534,6 +600,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var upscaleSharpness by mutableStateOf(75)
private var hdrReason by mutableStateOf<String?>(null)
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
private var pen by mutableStateOf<SessionPrefs.Pen?>(null)
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
private var steamDownloadsInBackground by mutableStateOf(false)
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
@@ -888,13 +955,15 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false): Boolean {
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}): Boolean {
if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this)
if (pkgStage != null) {
onHandled()
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return false
}
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome)
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled)
onHandled()
if (SessionState.running) {
if (SessionState.mode != SessionService.MODE_STEAM || SessionState.stopRequested) {
android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
@@ -938,12 +1007,13 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
.apply { if (returnHome) putExtra(SessionActivity.EXTRA_LINK_TASK, task) }
}
private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean): Boolean {
private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit = {}): Boolean {
val app = applicationContext
Thread({
val added = if (game.library == Library.ADDED) runCatching { com.droiddeck.launcher.session.NoSteamLaunch.addedGame(app, game) }.getOrNull() else null
val added = if (com.droiddeck.launcher.session.NoSteamLaunch.needsAddedGame(game)) runCatching { com.droiddeck.launcher.session.NoSteamLaunch.addedGame(app, game) }.getOrNull() else null
val command = com.droiddeck.launcher.session.NoSteamLaunch.command(game, added)
ui.post {
onHandled()
if (isDestroyed) return@post
if (command == null) {
android.widget.Toast.makeText(this, R.string.game_link_failed, android.widget.Toast.LENGTH_LONG).show()
@@ -1134,6 +1204,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
homeChoiceOpen = savedInstanceState?.getBoolean(STATE_HOME_CHOICE_OPEN) == true
gameSpaceOffered = savedInstanceState?.getBoolean(STATE_GAME_SPACE_OFFERED) == true
if (savedInstanceState == null) readIntegrationIntent(intent)
val shortcutsFilter = android.content.IntentFilter(SteamIntegration.SHORTCUTS_STATUS)
if (android.os.Build.VERSION.SDK_INT >= 33) registerReceiver(shortcutsInstallStatus, shortcutsFilter, RECEIVER_NOT_EXPORTED)
else registerReceiver(shortcutsInstallStatus, shortcutsFilter)
readGameIntent(intent)
// A Lab build is usually the agent's work, so the app comes back where the agent is.
if (savedInstanceState == null && navRequest == null && com.droiddeck.launcher.lab.LabOverlay.promoted && com.droiddeck.launcher.agent.AgentTab.visible) navRequest = "agent"
@@ -1790,15 +1863,24 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled(cold = true) }
else {
val askAllFiles = Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.files.AllFilesAccess.missing() &&
!SessionPrefs.allFilesAsked(this)
if (savedInstanceState == null) {
if (!askAllFiles) ui.post { startSteamAtStartupIfEnabled(cold = true) }
} else {
restoreCompatLaunch(savedInstanceState)
pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH)
savedIntent(savedInstanceState, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, savedInstanceState.getLong(KEY_SWITCH_DEADLINE)) }
}
val wanted = ArrayList<String>()
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= 30) {
// From targetSdk 30, shared storage outside the app's own folders is all-files access or nothing.
if (askAllFiles) {
SessionPrefs.setAllFilesAsked(this)
com.droiddeck.launcher.files.AllFilesAccess.open(this)
}
} else if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
wanted.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
if (SessionPrefs.micEnabled(this) && !SessionPrefs.micAsked(this)
@@ -1970,7 +2052,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
requestedOrientation = launcherOrientation
homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this)
SteamIntegration.syncShortcutsListing(this)
refreshWifiDiscovery()
com.droiddeck.launcher.stores.StoresState.refresh(this)
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
@@ -2069,8 +2150,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g, onBlocked = done) {
if (request != gameLaunchRequest.get() || isFinishing || isDestroyed) { done(); return@beforeLaunch }
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) {
done()
if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g)
if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g, onHandled = done)
else done()
}
}
}
@@ -2079,6 +2160,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
gameLaunchRequest.incrementAndGet()
cancelCompatLaunch()
updates.unregister()
runCatching { unregisterReceiver(shortcutsInstallStatus) }
super.onDestroy()
}
@@ -2467,6 +2549,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
gpuDrivers = drivers.summary(),
touchMode = touchMode,
pen = pen,
suspendPolicy = suspendPolicy,
steamDownloadsInBackground = steamDownloadsInBackground,
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
@@ -2478,6 +2561,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
backActionsInverted = backActionsInverted,
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
picturePosition = if (mode == SessionService.MODE_STEAM) picturePosition else null,
integerScaling = if (mode == SessionService.MODE_STEAM) integerScaling else null,
stretch16x9 = if (mode == SessionService.MODE_STEAM) stretch16x9 else null,
mic = if (mode == SessionService.MODE_STEAM) mic else null,
gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null,
@@ -2519,6 +2603,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m },
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
onPen = { key, value -> SessionPrefs.setPenSetting(this, key, value); pen = SessionPrefs.pen(this) },
onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy },
onSteamDownloadsInBackground = { enabled ->
SessionPrefs.setSteamDownloadsInBackground(this, enabled)
@@ -2538,6 +2623,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
},
onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on },
onPicturePosition = { value -> SessionPrefs.setPicturePosition(this, value); picturePosition = value },
onIntegerScaling = { on -> SessionPrefs.setIntegerScaling(this, on); integerScaling = on },
onStretch16x9 = { on -> SessionPrefs.setStretch16x9(this, on); stretch16x9 = on },
onMic = { on ->
SessionPrefs.setMicEnabled(this, on)
@@ -2621,20 +2707,21 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private fun PerformanceHost() {
PerformancePage(
cores = CpuCores.all.map { c -> CoreRow(c, "cpu$c" + (CpuCores.maxGhz(c)?.let { String.format(java.util.Locale.US, " · %.1f GHz", it) } ?: "")) },
clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores,
clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores, paceCores = paceCores,
tuSysmem = tuSysmem, zinkLazy = zinkLazy, glThread = glThread, noGlError = noGlError, noXalia = noXalia,
fastSync = fastSync,
syncFallback = syncFallback,
fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
ramCapMb = ramCapMb, vramCapMb = vramCapMb, zramClient = zramClient,
ramCapMb = ramCapMb, vramCapMb = vramCapMb, zramClient = zramClient, zramIdle = zramIdle,
deviceRamMb = (android.app.ActivityManager.MemoryInfo()
.also((getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)::getMemoryInfo).totalMem / (1024 * 1024)).toInt(),
ramCapAvailable = com.droiddeck.launcher.core.ZramSupport.supported(),
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, cursorComposite = cursorComposite,
guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
onPaceCores = { on -> SessionPrefs.setPaceCores(this, on); paceCores = on },
onTuSysmem = { on -> SessionPrefs.setTuSysmem(this, on); tuSysmem = on },
onZinkLazy = { on -> SessionPrefs.setZinkLazy(this, on); zinkLazy = on },
onGlThread = { on -> SessionPrefs.setGlThread(this, on); glThread = on },
@@ -2647,6 +2734,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
onRamCapMb = { mb -> SessionPrefs.setRamCapMb(this, mb); ramCapMb = mb },
onZramClient = { on -> SessionPrefs.setZramClient(this, on); zramClient = on },
onZramIdle = { on -> SessionPrefs.setZramIdle(this, on); zramIdle = on },
onVramCapMb = { mb -> SessionPrefs.setVramCapMb(this, mb); vramCapMb = mb },
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
@@ -2864,6 +2952,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
touchMode = SessionPrefs.touchMode(this)
if (!SessionPrefs.penSeen(this) && com.droiddeck.launcher.input.PenStream.penConnected()) SessionPrefs.setPenSeen(this)
pen = SessionPrefs.pen(this).takeIf { SessionPrefs.penSeen(this) }
suspendPolicy = SessionPrefs.suspendPolicy(this, mode)
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
oscMode = SessionPrefs.oscMode(this)
@@ -2871,6 +2961,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
backActionsInverted = SessionPrefs.backActionsInverted(this)
directAudio = SessionPrefs.directAudio(this)
picturePosition = SessionPrefs.picturePosition(this)
integerScaling = SessionPrefs.integerScaling(this)
stretch16x9 = SessionPrefs.stretch16x9(this)
mic = SessionPrefs.micEnabled(this)
refreshWifiDiscovery()
@@ -2941,8 +3032,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
syncFallback = SessionPrefs.syncFallback(this)
fsyncFirst = SessionPrefs.fsyncFirst(this)
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
paceCores = SessionPrefs.paceCores(this)
ramCapMb = SessionPrefs.ramCapMb(this)
zramClient = SessionPrefs.zramClient(this)
zramIdle = SessionPrefs.zramIdle(this)
vramCapMb = SessionPrefs.vramCapMb(this)
gpuClockPin = SessionPrefs.gpuClockPin(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
@@ -3294,3 +3387,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private val WCP_EXT = listOf("wcp")
}
}
// The install session outlives the activity when Android recreates it mid-install.
private object ShortcutsInstall {
@Volatile var session = -1
@Volatile var running = false
}
@@ -18,6 +18,7 @@ import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.core.graphics.drawable.toBitmap
import com.droiddeck.launcher.core.AppUiPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import kotlin.math.roundToInt
@@ -196,7 +197,10 @@ object HomeApp {
}
private fun syncRecents(activity: android.app.Activity) =
keepOutOfRecents(activity, activity is FrontEndActivity && !SessionState.running && isDefault(activity))
keepOutOfRecents(
activity,
activity is FrontEndActivity && !SessionState.running && isDefault(activity) && AppUiPrefs.hideHomeFromRecents(activity),
)
internal enum class RecentsStep { HIDE, SHOW, FORGET, NONE }
@@ -0,0 +1,31 @@
package com.droiddeck.launcher
internal object MaliAutoRoute {
const val NONE = ""
const val BRIDGE = "bridge"
const val VENUS = "venus"
fun initialOwnership(bridgeOn: Boolean, bridgeExplicit: Boolean, venusOn: Boolean, venusExplicit: Boolean): String =
when {
venusOn && !venusExplicit -> VENUS
bridgeOn && !bridgeExplicit -> BRIDGE
else -> NONE
}
fun fallbackOwnership(
venusAvailable: Boolean,
bridgeOn: Boolean,
bridgeExplicit: Boolean,
venusOn: Boolean,
venusExplicit: Boolean,
): String = if (venusAvailable) {
if (!venusOn || !venusExplicit) VENUS else NONE
} else {
if (!bridgeOn || !bridgeExplicit) BRIDGE else NONE
}
fun userChoice(keyStored: Boolean, owner: String, route: String): Boolean = keyStored && owner != route
fun shouldEnd(ownsRoute: String, mali: Boolean, installedPair: Boolean): Boolean =
mali && installedPair && ownsRoute != NONE
}
File diff suppressed because it is too large. Load diff
@@ -17,6 +17,7 @@ import com.droiddeck.launcher.ui.UpdatesActions
import com.droiddeck.launcher.ui.UpdatesState
import com.droiddeck.launcher.update.AppUpdates
import com.droiddeck.launcher.update.SelfInstaller
import com.droiddeck.launcher.update.UpdateWatch
internal class UpdatesMenu(private val activity: Activity, private val ui: Handler) {
var catalog by mutableStateOf<AppUpdates.Catalog?>(null)
@@ -43,6 +44,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
.onFailure { error = activity.getString(R.string.upd_unknown_apps_failed); pending = null }
},
onDismissPermission = { askPermission = false; pending = null },
onSeen = { r -> UpdateWatch.seen(activity, r) },
)
val hasUpdate: Boolean get() = AppUpdates.hasUpdate(catalog, follow)
@@ -77,6 +79,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
private fun choose(f: AppUpdates.Follow) {
AppUpdates.setFollow(activity, f)
UpdateWatch.sync(activity, f, catalog?.let { AppUpdates.release(it, f) })
follow = f
error = null
}
@@ -93,7 +96,17 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
percent = 0
Thread({
val result = runCatching {
val file = SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } }
val file = try {
SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } }
} catch (e: java.io.IOException) {
// Each push replaces a test build's APK, so a list read before the push names a file that is gone.
if (r.pr <= 0) throw e
val fresh = runCatching { AppUpdates.refresh(activity) }.getOrNull() ?: throw e
ui.post { catalog = fresh }
val newer = fresh.tests.firstOrNull { it.tag == r.tag }?.apk?.takeIf { it.url != apk.url } ?: throw e
ui.post { percent = 0 }
SelfInstaller.download(activity, newer) { pct -> ui.post { percent = pct } }
}
ui.post { stage = activity.getString(R.string.upd_stage_installing); percent = -1 }
SelfInstaller.install(activity, file) { id -> session = id }
}
@@ -1,9 +1,13 @@
package com.droiddeck.launcher.agent
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.provider.OpenableColumns
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
@@ -50,6 +54,22 @@ object AgentAttachments {
if (host(context, path).renameTo(moved)) "$GUEST_DIR/$chat/${moved.name}" else path
}
/** Copies the running game's frame; set while a session is open. */
var gameFrame by mutableStateOf<(((Bitmap?) -> Unit) -> Unit)?>(null)
/** Saves [frame] for [chat] (or a new conversation) on the calling thread; returns its guest path. */
fun saveFrame(context: Context, chat: String?, frame: Bitmap): String? = runCatching {
val folder = chat ?: NEW
val dir = File(hostDir(context), folder).apply { mkdirs() }
val target = File(dir, "game-${System.currentTimeMillis()}.jpg")
val written = target.outputStream().use { frame.compress(Bitmap.CompressFormat.JPEG, 88, it) }
if (!written) {
target.delete()
return@runCatching null
}
"$GUEST_DIR/$folder/${target.name}"
}.getOrNull()
/** Deletes copies that will not be sent. */
fun discard(context: Context, files: List<String>) = files.forEach { host(context, it).delete() }
@@ -37,6 +37,21 @@ object AgentChats {
}
.sortedByDescending { it.updated }
/** The chats among [chats] where the user or the agent wrote [query], ignoring case. */
fun search(context: Context, chats: List<Chat>, query: String): List<Chat> {
val q = query.trim()
if (q.isEmpty()) return chats
return chats.filter { chat ->
chat.title.contains(q, ignoreCase = true) || read(file(context, chat.id)).entries.any { matches(it, q) }
}
}
internal fun matches(entry: Entry, query: String) = when (entry) {
is Entry.Asked -> entry.text.contains(query, ignoreCase = true)
is Entry.Said -> entry.text.contains(query, ignoreCase = true)
else -> false
}
fun delete(context: Context, id: String) {
file(context, id).delete()
File(AgentAttachments.hostDir(context), id).deleteRecursively()
@@ -69,9 +84,11 @@ object AgentChats {
internal fun encode(entry: Entry): String = when (entry) {
is Entry.Asked -> JSONObject().put("asked", entry.text).apply { if (entry.files.isNotEmpty()) put("files", JSONArray(entry.files)) }
is Entry.Said -> JSONObject().put("said", entry.text)
is Entry.Notice -> JSONObject().put("notice", entry.text)
is Entry.Thought -> JSONObject().put("thought", entry.text)
is Entry.Result -> JSONObject().put("result", entry.id).put("output", entry.output).put("failed", entry.failed)
is Entry.Used -> JSONObject().put("used", entry.tool).put("detail", entry.detail).put("id", entry.id).put("input", entry.input)
.apply { if (entry.parent.isNotEmpty()) put("parent", entry.parent) }
.apply { entry.output?.let { put("output", it).put("failed", entry.failed) } }
is Entry.Finished -> JSONObject().put("finished", true).put("error", entry.error ?: JSONObject.NULL).put("stopped", entry.stopped).apply {
if (entry.planned) put("planned", true)
@@ -103,9 +120,10 @@ object AgentChats {
private fun decode(o: JSONObject): Entry? = when {
o.has("asked") -> Entry.Asked(o.getString("asked"), o.optJSONArray("files")?.let { a -> (0 until a.length()).map { a.getString(it) } }.orEmpty())
o.has("said") -> Entry.Said(o.getString("said"))
o.has("notice") -> Entry.Notice(o.getString("notice"))
o.has("thought") -> Entry.Thought(o.getString("thought"))
o.has("used") -> Entry.Used(o.optString("id"), o.getString("used"), o.optString("detail"), o.optString("input"),
if (o.has("output")) o.optString("output") else null, o.optBoolean("failed"))
if (o.has("output")) o.optString("output") else null, o.optBoolean("failed"), o.optString("parent"))
o.has("result") -> Entry.Result(o.getString("result"), o.optString("output"), o.optBoolean("failed"))
o.has("finished") -> Entry.Finished(
if (o.isNull("error")) null else o.optString("error"), o.optBoolean("stopped"),
@@ -5,7 +5,7 @@ import org.json.JSONArray
import org.json.JSONObject
import java.io.File
/** One coding agent CLI in the Linux userland, run one process per turn. */
/** One coding agent CLI in the Linux userland, run one process per turn (or kept open, see [input]). */
interface AgentHarness {
val id: String
val name: String
@@ -27,8 +27,18 @@ interface AgentHarness {
fun models(rootfs: File): List<Model>
/** The guest command for one turn; [conversation] is null for the first one. */
fun turn(message: String, conversation: String?, options: Options): List<String>
/**
* The line that hands [message] to a [turn] process over stdin, or null when the message is already in the
* command. A process that takes its messages this way stays open between turns, so work it started in the
* background can wake it, as it does in the CLI's own terminal.
*/
fun input(message: String): String? = null
/** One line of the CLI's output, or null when it carries nothing to show. */
fun parse(line: String): AgentEvent?
/** The folder, under the userland's root, where the CLI loads user skills (`<name>/SKILL.md`). */
val skills: String
/** The CLI's global instructions file under the userland's root, where DroidDeck keeps its rules in a marked block. */
val instructions: String
/** Sets the CLI's own defaults in the userland before it runs; [rootfs] is the userland's root. */
fun prepare(rootfs: File) {}
/** Context and plan limits the CLI keeps on disk rather than printing, read once a turn of [conversation] is done. */
@@ -56,9 +66,13 @@ data class AgentEvent(
val window: Long? = null,
val limits: List<AgentHost.Limit>? = null,
val usage: AgentHost.Usage? = null,
/** This ends a turn the CLI started itself, such as the answer to a finished background task. */
val background: Boolean = false,
/** The error a background turn ended with, if it failed. */
val backgroundError: String? = null,
)
/** Claude Code: `claude -p` with stream-json output, resumed by session id. */
/** Claude Code: `claude -p` with stream-json input and output, resumed by session id. */
object ClaudeCode : AgentHarness {
override val id = "claude"
override val name = "Claude Code"
@@ -73,6 +87,8 @@ object ClaudeCode : AgentHarness {
* Commits and pull requests the agent makes carry no Claude Code credit or co-author line by
* default. Only keys the user has not set are written, so their own choice stays.
*/
override val skills = "root/.claude/skills"
override val instructions = "root/.claude/CLAUDE.md"
override fun prepare(rootfs: File) {
val file = File(rootfs, "root/.claude/settings.json")
val settings = if (file.exists()) runCatching { JSONObject(file.readText()) }.getOrNull() ?: return else JSONObject()
@@ -97,7 +113,7 @@ object ClaudeCode : AgentHarness {
// DroidDeck runs the agent unattended on the user's own device; permission prompts have no one to answer them.
override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = buildList {
addAll(listOf(binary, "-p", message, "--output-format", "stream-json", "--verbose", "--include-partial-messages"))
addAll(listOf(binary, "-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", "--include-partial-messages"))
addAll(listOf("--permission-mode", if (options.plan) "plan" else "bypassPermissions"))
options.model?.let { addAll(listOf("--model", it)) }
options.effort?.let { addAll(listOf("--effort", it)) }
@@ -105,11 +121,19 @@ object ClaudeCode : AgentHarness {
if (conversation != null) addAll(listOf("--resume", conversation))
}
override fun input(message: String): String? = JSONObject()
.put("type", "user")
.put("message", JSONObject().put("role", "user").put("content", JSONArray().put(JSONObject().put("type", "text").put("text", message))))
.toString()
override fun parse(line: String): AgentEvent? {
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
val conversation = o.optString("session_id").takeIf { it.isNotEmpty() }
// A subagent's messages carry the call that started it; only its tool calls are shown, under that call.
val parent = o.optString("parent_tool_use_id").takeIf { it.isNotEmpty() && it != "null" }
return when (o.optString("type")) {
"stream_event" -> {
if (parent != null) return null
val delta = o.optJSONObject("event")?.takeIf { it.optString("type") == "content_block_delta" }?.optJSONObject("delta") ?: return null
when (delta.optString("type")) {
"text_delta" -> AgentEvent(conversation, text = delta.optString("text"))
@@ -123,18 +147,22 @@ object ClaudeCode : AgentHarness {
val entries = (0 until content.length()).mapNotNull { i ->
val block = content.optJSONObject(i) ?: return@mapNotNull null
when (block.optString("type")) {
"text" -> block.optString("text").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Said(it) }
"thinking" -> block.optString("thinking").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Thought(it) }
"text" -> if (parent != null) null else block.optString("text").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Said(it) }
"thinking" -> if (parent != null) null else block.optString("thinking").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Thought(it) }
"tool_use" -> {
val input = block.optJSONObject("input")
AgentHost.Entry.Used(block.optString("id"), block.optString("name"), detail(input), fullInput(block.optString("name"), input))
AgentHost.Entry.Used(
block.optString("id"), block.optString("name"), detail(input), fullInput(block.optString("name"), input),
parent = parent.orEmpty(),
background = input?.optBoolean("run_in_background") == true || block.optString("name") == "Monitor",
)
}
else -> null
}
}
val usage = message?.optJSONObject("usage")
val context = usage?.let { it.optLong("input_tokens") + it.optLong("cache_read_input_tokens") + it.optLong("cache_creation_input_tokens") + it.optLong("output_tokens") }
AgentEvent(conversation, entries, context = context?.takeIf { it > 0 })
AgentEvent(conversation, entries, context = context?.takeIf { it > 0 && parent == null })
}
"user" -> {
val content = o.optJSONObject("message")?.optJSONArray("content") ?: return conversation?.let { AgentEvent(it) }
@@ -145,17 +173,25 @@ object ClaudeCode : AgentHarness {
AgentEvent(conversation, results)
}
"rate_limit_event" -> AgentEvent(conversation, limits = limits(o.optJSONObject("rate_limit_info")))
// A resumed session first answers background tasks the last run left behind; that result is not the turn's.
"result" -> if (o.optJSONObject("origin")?.optString("kind") == "task-notification") conversation?.let { AgentEvent(it) } else AgentEvent(
conversation,
listOf(AgentHost.Entry.Finished(if (o.optBoolean("is_error")) o.optString("result").ifEmpty { o.optString("subtype") } else null)),
window = window(o.optJSONObject("modelUsage")),
usage = AgentHost.Usage(
// The CLI starts turns of its own for background tasks (a resumed session first answers the ones the last
// run left behind). Such a result is not the end of the user's turn; the host decides what it ends.
"result" -> {
val usage = AgentHost.Usage(
o.optLong("duration_ms"), o.optDouble("total_cost_usd", 0.0),
o.optJSONObject("usage")?.let { it.optLong("input_tokens") + it.optLong("cache_read_input_tokens") + it.optLong("cache_creation_input_tokens") } ?: 0,
o.optJSONObject("usage")?.optLong("output_tokens") ?: 0,
),
)
)
if (o.optJSONObject("origin")?.optString("kind") == "task-notification") AgentEvent(
conversation, usage = usage, background = true,
backgroundError = if (o.optBoolean("is_error")) o.optString("result").ifEmpty { o.optString("subtype") } else null,
)
else AgentEvent(
conversation,
listOf(AgentHost.Entry.Finished(if (o.optBoolean("is_error")) o.optString("result").ifEmpty { o.optString("subtype") } else null)),
window = window(o.optJSONObject("modelUsage")),
usage = usage,
)
}
else -> conversation?.let { AgentEvent(it) }
}
}
@@ -224,6 +260,8 @@ object Codex : AgentHarness {
override val id = "codex"
override val name = "Codex"
override val binary = "/root/.local/bin/codex"
override val skills = "root/.codex/skills"
override val instructions = "root/.codex/AGENTS.md"
// Code mode runs in a helper that each release ships as its own download.
private const val HOST = "/root/.local/bin/codex-code-mode-host"
override val files get() = listOf(binary, HOST)
@@ -21,16 +21,24 @@ import java.nio.file.Files
/**
* The launcher's agent: a coding agent CLI ([AgentHarness]) from the Linux userland, run headless
* one process per turn, outside any game or desktop session. Conversations are kept on disk
* outside any game or desktop session: one process per turn, or for a CLI that takes its messages over
* stdin one process kept open between turns, so background work can start a turn of its own. Conversations are kept on disk
* ([AgentChats]), so a restart (a Lab build, a crash) continues the same one.
*/
object AgentHost {
sealed interface Entry {
data class Asked(val text: String, val files: List<String> = emptyList()) : Entry
data class Said(val text: String) : Entry
data class Notice(val text: String) : Entry
data class Thought(val text: String) : Entry
/** A tool call; [output] stays null until its result arrives. */
data class Used(val id: String, val tool: String, val detail: String, val input: String = "", val output: String? = null, val failed: Boolean = false) : Entry
/**
* A tool call; [output] stays null until its result arrives. [parent] is the subagent call it was made under, if any.
* [background]: the call starts work that can wake the CLI after its turn (run_in_background, Monitor).
*/
data class Used(
val id: String, val tool: String, val detail: String, val input: String = "", val output: String? = null, val failed: Boolean = false,
val parent: String = "", val background: Boolean = false,
) : Entry
data class Result(val id: String, val output: String, val failed: Boolean) : Entry
/** [planned]: the turn ran in plan mode, so it ends on a plan that nothing has carried out yet. */
data class Finished(val error: String?, val stopped: Boolean = false, val usage: Usage? = null, val planned: Boolean = false) : Entry
@@ -60,18 +68,12 @@ object AgentHost {
@VisibleForTesting
internal const val BRIEF = "You run inside DroidDeck on the user's handheld, in its Linux userland (Ubuntu under proot, aarch64), " +
"and the user talks to you from DroidDeck's Agent tab, often on a small screen, so keep replies short. " +
"droiddeckctl inspects and drives the app over loopback adb (\$ADB_SERIAL); its guide is ${AgentSetup.CTL}/agent-control.md. " +
"Steam, the desktop and games run in DroidDeck's session, a separate guest from yours: a program you start here is not in it and has no screen. " +
"Reach the session through droiddeckctl: state, start steam, stop, launch, quit, focus, screenshot, logs, and guest to run a command inside it. " +
"Starting, stopping or restarting a session leaves you running. " +
"DroidDeck's rules for working here are in your global instructions file (~/.claude/CLAUDE.md or ~/.codex/AGENTS.md); " +
"if they are not loaded, read ${AgentSetup.CTL}/AGENTS.md before acting on the device. " +
"Never kill by a command-line pattern (pkill -f, pgrep -f piped to kill): your own command line holds the user's message, so the pattern matches you. " +
"End a game with droiddeckctl quit, the session with droiddeckctl stop, anything else by its pid. " +
"dd-lab-build builds the checkout as a Lab build and restarts DroidDeck on it (docs/lab-builds.md). DroidDeck runs the build in a " +
"process of its own and shows the user its progress and time left; dd-lab-build follows that build's log until it is done. " +
"Run it with run_in_background and keep checking its output, so the user can talk to you meanwhile. " +
"The restart ends this process, and this conversation continues on the new build. " +
"Files the user attaches are listed at the end of their message, under /root/.cache/droiddeck/attachments. " +
"Commits and pull requests you make are the user's own: add no co-author line, AI credit or generated-by note."
"To have the user pick between options, end your reply with a fenced code block whose language is choices, one short option per line, " +
"and end your turn: DroidDeck shows them as buttons and sends the one picked as the next message."
val entries = mutableStateListOf<Entry>()
val queue = mutableStateListOf<Queued>()
@@ -121,10 +123,24 @@ object AgentHost {
var lab by mutableStateOf<LabProgress?>(null)
private set
private class Turn(val process: Process, val pid: Int)
private class Turn(val process: Process, val pid: Int, val stdin: java.io.OutputStream? = null) {
var writingGeneration: Int? = null
var exitStatus: Int? = null
var costs: AgentCostTracker? = null
var clearingCosts = false
}
private val main = Handler(Looper.getMainLooper())
private var turn: Turn? = null
/**
* The CLI process when it takes its messages over stdin. It outlives a turn, so work it started in the
* background can wake it: the answer to a finished task then arrives without a message from the user.
*/
private var session: Turn? = null
private var sessionKey: String? = null
/** The running turn is one the CLI started itself, not an answer to the user. */
private var background = false
private val reap = Runnable { if (state != State.WORKING) dropSession() }
/** Counts turns, so a process that starts after its turn was stopped is not adopted by the next one. */
private var generation = 0
private var labProcess: Process? = null
@@ -137,11 +153,14 @@ object AgentHost {
private var turnPlanned = false
private var loaded = false
private var appContext: Context? = null
/** A tool call in this CLI process started work that can wake it after its turn (run_in_background). */
private var launchedBackground = false
val turnPid: Int get() = turn?.pid ?: 0
fun seen() {
unseen = false
appContext?.let { AgentNotice.clear(it) }
}
fun refresh(context: Context) {
@@ -191,6 +210,7 @@ object AgentHost {
AgentSetup.forget()
refresh(app)
}
dropSession()
load(app, id)
prefs(app).edit().putString(CHAT_KEY, id).apply()
}
@@ -279,11 +299,42 @@ object AgentHost {
live = ""
liveThinking = ""
turnStarted = SystemClock.elapsedRealtime()
AgentHostService.start(app)
AgentHostService.start(app)?.let { serviceWarning(app, it) }
val current = harness
val prompt = AgentAttachments.prompt(message, attached)
turnPlanned = plan && current.plans
val command = current.turn(prompt, conversation, AgentHarness.Options(model, turnPlanned, BRIEF, effort))
val options = AgentHarness.Options(model, turnPlanned, BRIEF, effort)
val command = current.turn(prompt, conversation, options)
val line = current.input(prompt)
val key = "${current.id}|$id|$model|$turnPlanned|$effort"
background = false
val kept = session
if (kept != null && line != null && sessionKey == key && kept.process.isAlive) {
main.removeCallbacks(reap)
turn = kept
kept.writingGeneration = gen
kept.clearingCosts = prompt == "/clear"
Thread({
val written = runCatching { synchronized(kept) { kept.stdin?.apply { write((line + "\n").toByteArray()); flush() } != null } }.getOrDefault(false)
// The process died between turns: the same message goes to a new one, which resumes the conversation.
main.post {
if (kept.writingGeneration == gen) kept.writingGeneration = null
if (generation == gen && session === kept) {
if (!written) {
dropSession()
turn = null
spawn(app, gen, current, current.turn(prompt, conversation, options), line, key)
} else kept.exitStatus?.let { processExited(app, kept, current, it) }
}
}
}, "agent-input").start()
return
}
dropSession()
spawn(app, gen, current, command, line, key)
}
private fun spawn(app: Context, gen: Int, current: AgentHarness, command: List<String>, line: String?, key: String) {
val workdir = workspace(app)
var threadConversation = conversation
Thread({
@@ -298,40 +349,100 @@ object AgentHost {
main.post { if (generation == gen) finish(app, e.message ?: "could not start") }
return@Thread
}
val started = Turn(child, AgentProcesses.pidOf(child))
val started = Turn(child, AgentProcesses.pidOf(child), if (line != null) child.outputStream else null).apply {
if (current === ClaudeCode && line != null) costs = AgentCostTracker()
}
OrphanReaper.keep(started.pid)
main.post { if (generation == gen && state == State.WORKING && turn == null) turn = started else AgentProcesses.killTree(started.pid) }
child.outputStream.close()
var ended = false
main.post {
if (generation == gen && state == State.WORKING && turn == null) {
turn = started
if (line != null) { session = started; sessionKey = key }
} else AgentProcesses.killTree(started.pid)
}
if (line != null) runCatching { child.outputStream.apply { write((line + "\n").toByteArray()); flush() } } else child.outputStream.close()
val raw = runCatching {
val log = File(app.filesDir, TURN_LOG).apply { parentFile?.mkdirs() }
log.renameTo(File(app.filesDir, "$TURN_LOG.1"))
log.bufferedWriter()
}.getOrNull()
runCatching {
child.inputStream.bufferedReader().forEachLine { line ->
runCatching { raw?.apply { write(line); newLine(); flush() } }
val parsed = current.parse(line) ?: return@forEachLine
child.inputStream.bufferedReader().forEachLine { output ->
runCatching { raw?.apply { write(output); newLine(); flush() } }
val parsed = current.parse(output) ?: return@forEachLine
parsed.conversation?.let { threadConversation = it }
val done = parsed.entries.any { it is Entry.Finished }
if (done) ended = true
val event = if (!done) parsed else runCatching { current.usage(LinuxRuntime.rootDir(app), threadConversation) }.getOrNull()
?.let { parsed.copy(context = it.context ?: parsed.context, window = it.window ?: parsed.window, limits = it.limits ?: parsed.limits) } ?: parsed
main.post { if (turn === started) apply(app, event) }
main.post { if (turn === started || session === started) handle(app, started, event) }
}
}
runCatching { raw?.close() }
val status = runCatching { child.waitFor() }.getOrDefault(-1)
OrphanReaper.release(started.pid)
main.post {
if (turn === started) {
turn = null
if (state == State.WORKING && !ended) finish(app, app.getString(R.string.agent_exited, current.name, status))
}
if (started.writingGeneration != null) started.exitStatus = status
else processExited(app, started, current, status)
}
}, "agent-output").start()
}
private fun processExited(app: Context, exited: Turn, current: AgentHarness, status: Int) {
if (session === exited) {
session = null
launchedBackground = false
main.removeCallbacks(reap)
AgentHostService.backgroundDone(app)
}
if (turn === exited) {
turn = null
if (state == State.WORKING) finish(app, app.getString(R.string.agent_exited, current.name, status))
}
}
private fun serviceWarning(app: Context, error: Throwable) {
record(app, Entry.Notice("Unable to keep the agent running in the background: ${error.message ?: error.javaClass.simpleName}"))
}
/** One event from the CLI, which may belong to a turn it started on its own once the user's has ended. */
private fun handle(app: Context, from: Turn, event: AgentEvent) {
if (event.background) {
// A leftover task answered before the user's message is not the user's turn; one the CLI started is its own.
if (background && state == State.WORKING) finish(app, event.backgroundError, usage = event.usage?.let { from.costs?.perTurn(it) ?: it })
return
}
val content = event.text != null || event.thinking != null || event.entries.any { it !is Entry.Finished }
if (content && state == State.IDLE && session === from) {
main.removeCallbacks(reap)
background = true
turn = from
turnPlanned = false
state = State.WORKING
live = ""
liveThinking = ""
turnStarted = SystemClock.elapsedRealtime()
AgentHostService.start(app)?.let { serviceWarning(app, it) }
}
val finished = event.entries.filterIsInstance<Entry.Finished>().firstOrNull()
if (finished != null && state == State.WORKING && from.clearingCosts) {
if (finished.error == null) from.costs?.reset()
from.clearingCosts = false
}
val applied = if (finished != null && state == State.WORKING && event.usage != null)
event.copy(usage = from.costs?.perTurn(event.usage) ?: event.usage) else event
apply(app, applied)
}
/** Ends the CLI process kept between turns, and with it whatever it still runs in the background. */
private fun dropSession() {
main.removeCallbacks(reap)
launchedBackground = false
appContext?.let { AgentHostService.backgroundDone(it) }
val kept = session ?: return
session = null
AgentProcesses.killTree(kept.pid)
kept.process.destroy()
}
/** Ends the turn now: its process and everything it started, a build included. */
fun stop(context: Context) {
val app = context.applicationContext
@@ -343,6 +454,7 @@ object AgentHost {
AgentProcesses.killTree(running.pid)
running.process.destroy()
}
dropSession()
if (state == State.WORKING) finish(app, null, stopped = true)
}
@@ -437,19 +549,25 @@ object AgentHost {
private fun finish(app: Context, error: String?, stopped: Boolean = false, usage: Usage? = null) {
if (state != State.WORKING) return
turn = null
val answeredTask = background
background = false
main.removeCallbacks(reap)
if (session != null) main.postDelayed(reap, LINGER_MS)
if (!stopped) labFromTurn = false
live = ""
liveThinking = ""
val held = if (context > 0) (usage ?: Usage(0, 0.0, 0, 0)).copy(context = context, window = window) else usage
record(app, Entry.Finished(error, stopped, held, planned = turnPlanned && !stopped && error == null))
state = State.IDLE
unseen = true
failed = error != null
AgentHostService.stop(app)
if (session != null && launchedBackground) {
AgentHostService.waitForBackground(app)?.let { serviceWarning(app, it) }
} else AgentHostService.stop(app)
record(app, Entry.Finished(error, stopped, held, planned = turnPlanned && !stopped && error == null))
// Claude Code now and then ends a resumed turn at once without reading the message; nothing
// happened, so the message is sent once more.
val asked = entries.lastOrNull { it is Entry.Asked } as? Entry.Asked
if (!stopped && error == null && asked != null && answerless(entries) && !retrying) {
if (!stopped && error == null && !answeredTask && asked != null && answerless(entries) && !retrying) {
retrying = true
val retryChat = chat
resend = Runnable {
@@ -462,7 +580,19 @@ object AgentHost {
if (!stopped && queue.isNotEmpty()) {
val next = queue.removeAt(0)
send(app, next.text, next.files)
} else if (!stopped) notifyEnded(app, error)
}
private fun notifyEnded(app: Context, error: String?) {
val start = entries.indexOfLast { it is Entry.Asked }
val said = entries.subList(start + 1, entries.size).lastOrNull { it is Entry.Said } as? Entry.Said
val reply = said?.let { choices(it.text) }
val kind = when {
error != null -> AgentNotice.Kind.FAILED
!reply?.options.isNullOrEmpty() -> AgentNotice.Kind.QUESTION
else -> AgentNotice.Kind.DONE
}
AgentNotice.post(app, kind, error ?: reply?.text?.takeIf { it.isNotBlank() }?.let { firstLine(it) } ?: "")
}
/** A message typed or retried by the user replaces the automatic resend. */
@@ -475,6 +605,7 @@ object AgentHost {
private fun record(app: Context, entry: Entry) {
if (!AgentChats.merge(entries, entry)) return
if (entry is Entry.Used && entry.background) launchedBackground = true
chat?.let { AgentChats.append(AgentChats.file(app, it), entry) }
}
@@ -501,7 +632,7 @@ object AgentHost {
}
/** The latest todo list the agent wrote in this conversation. */
fun todos(): String? = entries.lastOrNull { it is Entry.Used && it.tool == "TodoWrite" }?.let { (it as Entry.Used).input }
fun todos(): String? = entries.lastOrNull { it is Entry.Used && it.tool == "TodoWrite" && it.parent.isEmpty() }?.let { (it as Entry.Used).input }
private fun tick() {
now = SystemClock.elapsedRealtime()
@@ -627,6 +758,8 @@ object AgentHost {
/** The raw output of the latest turn, for working out what a CLI did when the chat shows nothing. */
private const val TURN_LOG = "agent/turn.log"
private const val RETRY_MS = 3_000L
/** How long the CLI process stays open after a turn, waiting for background work to wake it. */
private const val LINGER_MS = 20 * 60_000L
private fun modelKey(harness: AgentHarness) = "model_${harness.id}"
private fun limitsKey(harness: AgentHarness) = "limits_${harness.id}"
@@ -645,3 +778,48 @@ object AgentHost {
internal fun prefs(context: Context) = context.getSharedPreferences("agent", Context.MODE_PRIVATE)
}
/** A reply split into its text and the options of a trailing choices block. */
internal data class Choices(val text: String, val options: List<String>)
private val FENCE = Regex("""[ \t]{0,3}(`{3,}|~{3,})(.*)""")
/** Walks Markdown fences so a choices block counts only at the top level and only as the last thing in the reply. */
internal fun choices(reply: String): Choices {
val lines = reply.split('\n')
var open = ""
var opener = -1
var openChoices = false
var block: IntRange? = null
lines.forEachIndexed { i, line ->
val fence = FENCE.matchEntire(line)
if (open.isEmpty()) {
if (fence != null) {
open = fence.groupValues[1]
opener = i
openChoices = fence.groupValues[2].trim() == "choices"
block = null
} else if (line.isNotBlank()) block = null
} else if (fence != null && fence.groupValues[1][0] == open[0] && fence.groupValues[1].length >= open.length && fence.groupValues[2].isBlank()) {
block = if (openChoices) opener..i else null
open = ""
}
}
val found = block?.takeIf { open.isEmpty() } ?: return Choices(reply, emptyList())
val options = lines.subList(found.first + 1, found.last).map { it.trim().removePrefix("- ").removePrefix("* ").trim() }.filter { it.isNotEmpty() }
return Choices(lines.subList(0, found.first).joinToString("\n").trimEnd(), options)
}
internal class AgentCostTracker {
private var previous = 0.0
fun reset() { previous = 0.0 }
fun perTurn(usage: AgentHost.Usage): AgentHost.Usage {
val total = usage.costUsd
if (total == 0.0 && previous > 0.0) return usage
val delta = if (total >= previous) total - previous else total
previous = total
return usage.copy(costUsd = delta)
}
}
@@ -42,19 +42,37 @@ class AgentHostService : Service() {
/** Setup steps that keep the app alive while they run, besides the agent's turn. */
private var setupSteps = 0
fun start(context: Context) {
fun start(context: Context): Throwable? {
if (started) { update(context); return null }
lastText = null
started = true
runCatching { context.startForegroundService(Intent(context, AgentHostService::class.java)) }
.onSuccess { awaiting++ }
return runCatching { context.startForegroundService(Intent(context, AgentHostService::class.java)) }
.onSuccess { started = true; awaiting++ }
.exceptionOrNull()
}
fun stop(context: Context) {
if (setupSteps > 0) return
if (setupSteps > 0 || waiting) return
started = false
if (awaiting == 0) context.stopService(Intent(context, AgentHostService::class.java))
}
/**
* The turn has ended but its CLI process stays open with background work that can wake it; the app must stay
* alive to read that answer, so the service keeps running until the process is dropped.
*/
@Volatile private var waiting = false
fun waitForBackground(context: Context): Throwable? {
waiting = true
return if (started) { update(context); null } else start(context)
}
fun backgroundDone(context: Context) {
if (!waiting) return
waiting = false
if (AgentHost.state != AgentHost.State.WORKING) stop(context)
}
fun setupStarted(context: Context) {
setupSteps++
start(context)
@@ -80,7 +98,8 @@ class AgentHostService : Service() {
AgentSetup.detail[AgentSetup.Step.GITHUB]?.takeIf {
AgentSetup.status[AgentSetup.Step.GITHUB] == AgentSetup.Status.WORKING && it.startsWith("GitHub device code:")
}?.let { return it }
if (AgentHost.state != AgentHost.State.WORKING) return context.getString(R.string.agent_setting_up)
if (AgentHost.state != AgentHost.State.WORKING)
return context.getString(if (waiting && setupSteps == 0) R.string.agent_waiting_background else R.string.agent_setting_up)
val tool = AgentHost.running()
val elapsed = minutes((SystemClock.elapsedRealtime() - AgentHost.turnStarted) / 1000)
return if (tool != null) "${tool.tool} · ${tool.detail}".take(120) + " · $elapsed" else context.getString(R.string.agent_thinking_for, elapsed)
@@ -0,0 +1,58 @@
package com.droiddeck.launcher.agent
import android.app.ActivityManager
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import com.droiddeck.launcher.FrontEndActivity
import com.droiddeck.launcher.R
import com.droiddeck.launcher.ui.AgentPet
/** Tells the user a turn has ended when nothing on screen already does. */
internal object AgentNotice {
private const val CHANNEL_ID = "agent_done"
private const val NOTIFICATION_ID = 4108
enum class Kind { DONE, FAILED, QUESTION }
fun post(context: Context, kind: Kind, text: String) {
if (onScreen(context)) return
val manager = context.getSystemService(NotificationManager::class.java) ?: return
manager.createNotificationChannel(NotificationChannel(CHANNEL_ID, context.getString(R.string.agent_done_channel), NotificationManager.IMPORTANCE_DEFAULT))
val open = PendingIntent.getActivity(context, 2,
Intent(context, FrontEndActivity::class.java)
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
.putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "agent"),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
val title = context.getString(when (kind) {
Kind.DONE -> R.string.agent_done
Kind.FAILED -> R.string.agent_done_failed
Kind.QUESTION -> R.string.agent_done_question
})
runCatching {
manager.notify(NOTIFICATION_ID, Notification.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentTitle(title)
.setContentText(text)
.setStyle(Notification.BigTextStyle().bigText(text))
.setContentIntent(open)
.setAutoCancel(true)
.setCategory(Notification.CATEGORY_STATUS)
.build())
}
}
fun clear(context: Context) {
context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)
}
/** The chat in a DroidDeck window in front, or the pet, which shows the reply in its own bubble. */
private fun onScreen(context: Context): Boolean {
if (AgentPet.floating) return true
val state = ActivityManager.RunningAppProcessInfo().also { ActivityManager.getMyMemoryState(it) }
return AgentPet.agentOnScreen > 0 && state.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
}
}
@@ -40,7 +40,11 @@ object AgentProcesses {
val now = SystemClock.elapsedRealtime()
val uptimeTicks = now * HZ / 1000
val elapsed = (now - lastAt).coerceAtLeast(1)
fun isProot(pid: Int) = args[pid].orEmpty().substringBefore(' ').endsWith("proot.so") || args[pid].orEmpty().substringBefore(' ').endsWith("/proot")
fun isProot(pid: Int): Boolean {
val argv = args[pid].orEmpty().split(' ')
val program = if (argv.first().endsWith("/linker64")) argv.getOrElse(1) { "" } else argv.first()
return program.endsWith("proot.so") || program.endsWith("/proot")
}
fun ancestors(pid: Int) = generateSequence(stats[pid]?.ppid) { stats[it]?.ppid }.takeWhile { it > 1 }.take(64)
val out = stats.values.filter { s ->
!isProot(s.pid) && args[s.pid].orEmpty().isNotEmpty() && ancestors(s.pid).any { isProot(it) }
@@ -4,6 +4,7 @@ import android.content.Context
import android.os.Handler
import android.os.Looper
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
@@ -40,7 +41,9 @@ object AgentSetup {
private val main = Handler(Looper.getMainLooper())
private const val REPO = "https://github.com/Droid-Deck/DroidDeck.git"
private const val CHECKOUT = "/root/DroidDeck"
private val HELPERS = listOf("android-open", "dd-gh-login", "droiddeckctl")
private val HELPERS = listOf("android-open", "dd-gh-login", "droiddeckctl", "droiddeck-scenario")
/** DroidDeck's own skills (tools/agent/skills), given to every harness. */
private const val SKILLS = "agent/skills"
internal const val CTL = "/root/.local/share/droiddeck/ctl"
private const val PROBE_TIMEOUT_S = 60L
@@ -187,11 +190,98 @@ object AgentSetup {
/** Written before every step, so the helpers a step relies on are there and match this DroidDeck version. */
internal fun installHelpers(app: Context) {
val root = LinuxRuntime.rootDir(app)
val failed = mutableListOf<String>()
fun attempt(what: String, block: () -> Unit) = runCatching(block).onFailure {
android.util.Log.w("AgentSetup", "could not install $what", it)
failed += what
}
val bin = File(root, "root/.local/bin").apply { mkdirs() }
for (name in HELPERS) copyAsset(app, "agent/$name", File(bin, name))
for (name in HELPERS) attempt(name) { copyAsset(app, "agent/$name", File(bin, name)) }
val ctl = File(root, CTL.removePrefix("/")).apply { mkdirs() }
for (name in app.assets.list("agent/ctl").orEmpty()) copyAsset(app, "agent/ctl/$name", File(ctl, name))
for (name in app.assets.list("agent/ctl").orEmpty()) attempt("ctl/$name") { copyAsset(app, "agent/ctl/$name", File(ctl, name)) }
val skills = app.assets.list(SKILLS).orEmpty().associateWith { app.assets.list("$SKILLS/$it").orEmpty().toList() }
failed += installSkills(root, skills) { app.assets.open("$SKILLS/$it") }
attempt("AGENTS.md") {
val rules = app.assets.open("agent/ctl/AGENTS.md").use { it.readBytes().decodeToString() }
failed += installInstructions(root, rules)
}
unpinAdbSerial(File(root, "root/.bashrc"))
main.post { problems.clear(); problems.addAll(failed.distinct()) }
}
/** What [installHelpers] could not install last time, shown in the Agent tab; empty when all is in place. */
val problems = mutableStateListOf<String>()
/**
* Writes each of DroidDeck's [skills] (name to its files) into every harness's skills folder, so
* Claude Code, Codex and any later harness load the same ones, as of this DroidDeck version.
* Skills the user added there are left alone. Returns the skills that could not be written.
*/
internal fun installSkills(root: File, skills: Map<String, List<String>>, open: (String) -> java.io.InputStream): List<String> {
val failed = mutableListOf<String>()
for (harness in AgentHarness.all) for ((name, files) in skills) runCatching {
val dir = File(root, "${harness.skills}/$name")
// A folder of that name without DroidDeck's mark is the user's own skill: keep it.
if (dir.exists() && !File(dir, SKILL_MARK).exists()) return@runCatching
dir.mkdirs()
// Marked before copying, so a copy that fails part way is retried next turn, not taken for the user's.
File(dir, SKILL_MARK).writeText("Installed by DroidDeck and replaced on every turn. Delete this file to keep your own edits.\n")
for (file in files) open("$name/$file").use { replaceFile(it, File(dir, file), executable = false) }
}.onFailure {
android.util.Log.w("AgentSetup", "could not install skill $name for ${harness.name}", it)
failed += "skill $name"
}
return failed
}
/** Marks a skill folder as DroidDeck's, so it may be replaced; one without it belongs to the user. */
internal const val SKILL_MARK = ".droiddeck"
/**
* Where [file] really is when it is a symlink, as the guest sees it: an absolute target is a
* userland path, so it is looked up under [root]. A dotfiles link keeps working that way.
*/
internal fun guestTarget(root: File, file: File): File {
var current = file
repeat(8) {
val path = current.toPath()
if (!java.nio.file.Files.isSymbolicLink(path)) return current
val target = java.nio.file.Files.readSymbolicLink(path).toString()
current = if (target.startsWith("/")) File(root, target.removePrefix("/")) else File(current.parentFile, target)
}
return current
}
internal const val BLOCK_BEGIN = "<!-- BEGIN DroidDeck: replaced on every turn. Write your own rules outside this block. -->"
internal const val BLOCK_END = "<!-- END DroidDeck -->"
/**
* Puts DroidDeck's [rules] in a marked block of every harness's global instructions file,
* keeping whatever the user wrote around it. Returns the files that could not be written.
*/
internal fun installInstructions(root: File, rules: String): List<String> {
val failed = mutableListOf<String>()
for (harness in AgentHarness.all) runCatching {
val file = guestTarget(root, File(root, harness.instructions)).apply { parentFile?.mkdirs() }
val existing = if (file.exists()) file.readText() else null
val merged = withBlock(existing, rules)
if (merged != existing) replaceFile(merged.byteInputStream(), file, executable = false)
}.onFailure {
android.util.Log.w("AgentSetup", "could not write ${harness.instructions}", it)
failed += harness.instructions.substringAfterLast("root/")
}
return failed
}
/** [existing] with DroidDeck's block set to [rules]: replaced in place, or put first when there is none yet. */
internal fun withBlock(existing: String?, rules: String): String {
val block = "$BLOCK_BEGIN\n${rules.trim()}\n$BLOCK_END\n"
if (existing.isNullOrBlank()) return block
val start = existing.indexOf(BLOCK_BEGIN)
val end = existing.indexOf(BLOCK_END, start.coerceAtLeast(0))
if (start < 0 || end < 0) return "$block\n$existing"
val after = existing.substring(end + BLOCK_END.length).removePrefix("\n")
return existing.substring(0, start) + block + after
}
/** Older tools/agent/setup pinned the adb port in .bashrc, which overrides the live port DroidDeck passes. */
@@ -201,8 +291,24 @@ object AgentSetup {
if (fixed != text) runCatching { bashrc.writeText(fixed) }
}
/**
* Written beside [target] and renamed over it, so a symlink left there by a hand-made setup is
* replaced rather than followed: its absolute target is a userland path the app cannot reach,
* and the failed write stopped every helper after it, the droiddeckctl guide included.
*/
private fun copyAsset(app: Context, asset: String, target: File) {
app.assets.open(asset).use { input -> target.outputStream().use { input.copyTo(it) } }
target.setExecutable(true, false)
app.assets.open(asset).use { replaceFile(it, target) }
}
/** Replaces [target], or the symlink at it, with [input]. */
internal fun replaceFile(input: java.io.InputStream, target: File, executable: Boolean = true) {
// A unique name, since an agent turn and a setup step can install at the same time.
val staged = File.createTempFile(".${target.name}.", ".part", target.parentFile)
staged.outputStream().use { input.copyTo(it) }
if (executable) staged.setExecutable(true, false)
if (!staged.renameTo(target)) {
staged.delete()
throw java.io.IOException("could not replace $target")
}
}
}
@@ -0,0 +1,143 @@
package com.droiddeck.launcher.agent
import android.content.Context
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
import java.util.concurrent.TimeUnit
/** Claude Code's MCP servers and skills in the userland, through its own CLI and skills folder. */
internal object AgentTools {
data class Server(val name: String, val target: String, val status: String) {
/** Connectors come from the claude.ai account and are managed there, not by the CLI. */
val account get() = name.startsWith("claude.ai ")
}
data class Skill(val name: String, val description: String)
class Result(val ok: Boolean, val output: String)
private const val SKILLS = "root/.claude/skills"
private val SERVER = Regex("""^(.+?): (.+) - (.+)$""")
fun servers(context: Context): List<Server>? {
val result = run(context, listOf(ClaudeCode.binary, "mcp", "list"))
if (!result.ok) return null
return parseServers(result.output)
}
internal fun parseServers(output: String): List<Server> = output.lines().mapNotNull { line ->
SERVER.find(line.trim())?.destructured?.let { (name, target, status) -> Server(name, target, status) }
}
/** A URL is added as an HTTP server; anything else is the command that starts a stdio server. */
internal fun addCommand(name: String, target: String): List<String> {
val t = target.trim()
val base = listOf(ClaudeCode.binary, "mcp", "add", "--scope", "user")
return if (t.startsWith("http://") || t.startsWith("https://")) base + listOf("--transport", "http", name.trim(), t)
else base + listOf(name.trim(), "--") + words(t)
}
/** Splits a command line the way a shell would for quotes and backslashes, without expanding anything. */
internal fun words(line: String): List<String> {
val words = mutableListOf<String>()
val word = StringBuilder()
var inWord = false
var quote: Char? = null
var i = 0
while (i < line.length) {
val c = line[i]
when {
quote == '\'' -> if (c == '\'') quote = null else word.append(c)
c == '\\' && i + 1 < line.length && (quote == null || line[i + 1] == '"' || line[i + 1] == '\\') -> {
word.append(line[++i])
inWord = true
}
quote == '"' -> if (c == '"') quote = null else word.append(c)
c == '\'' || c == '"' -> {
quote = c
inWord = true
}
c.isWhitespace() -> if (inWord) {
words += word.toString()
word.clear()
inWord = false
}
else -> {
word.append(c)
inWord = true
}
}
i++
}
if (inWord) words += word.toString()
return words
}
fun add(context: Context, name: String, target: String) = run(context, addCommand(name, target))
fun remove(context: Context, name: String) = run(context, listOf(ClaudeCode.binary, "mcp", "remove", name))
fun skills(context: Context): List<Skill> =
File(LinuxRuntime.rootDir(context), SKILLS).listFiles { f -> f.isDirectory }.orEmpty().sortedBy { it.name.lowercase() }.map { dir ->
Skill(dir.name, description(File(dir, "SKILL.md")))
}
internal fun description(file: File): String = runCatching {
val lines = file.readLines()
if (lines.firstOrNull()?.trim() != "---") return@runCatching ""
lines.drop(1).takeWhile { it.trim() != "---" }.firstOrNull { it.startsWith("description:") }
?.removePrefix("description:")?.trim()?.trim('"', '\'').orEmpty()
}.getOrDefault("")
fun deleteSkill(context: Context, name: String): Boolean {
if (name.isEmpty() || name.contains('/') || name.startsWith(".")) return false
val root = File(LinuxRuntime.rootDir(context), SKILLS)
val dir = File(root, name)
if (dir.parentFile?.path != root.path) return false
return deleteTree(dir.toPath())
}
/** Deletes [path] and what is under it; a symbolic link is removed itself, never what it points to. */
internal fun deleteTree(path: Path): Boolean = runCatching {
if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) return@runCatching true
Files.walkFileTree(path, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
Files.delete(file)
return FileVisitResult.CONTINUE
}
override fun postVisitDirectory(dir: Path, exc: java.io.IOException?): FileVisitResult {
if (exc != null) throw exc
Files.delete(dir)
return FileVisitResult.CONTINUE
}
})
true
}.getOrDefault(false)
private fun run(context: Context, command: List<String>): Result {
val child = runCatching { AgentHost.guest(context.applicationContext, command, connectAdb = false).start() }
.getOrElse { return Result(false, it.message.orEmpty()) }
val output = StringBuffer()
// The CLI can hold its output open past the deadline, so it is read beside the wait rather than before it.
val reader = Thread({ runCatching { child.inputStream.bufferedReader().forEachLine { output.append(it).append('\n') } } }, "agent-tools").apply { start() }
return try {
val ended = child.waitFor(90, TimeUnit.SECONDS)
if (!ended) child.destroyForcibly()
reader.join(2_000)
Result(ended && child.exitValue() == 0, output.toString().trim())
} catch (e: InterruptedException) {
child.destroyForcibly()
Thread.currentThread().interrupt()
Result(false, output.toString().trim())
} finally {
runCatching { child.inputStream.close() }
}
}
}
@@ -16,6 +16,8 @@ import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.function.IntConsumer;
import java.util.function.IntSupplier;
public class PulseAudioComponent extends SessionPart {
private static final String TAG = "PulseAudio";
@@ -29,7 +31,55 @@ public class PulseAudioComponent extends SessionPart {
private final File deviceControls;
private File logFile;
private final String micFifoPath;
private volatile int pid = -1;
private final HostLifecycle host = new HostLifecycle(Process::killProcess);
static final class HostLifecycle {
volatile int pid = -1;
private long generation;
private long launches;
private final IntConsumer terminate;
HostLifecycle(IntConsumer terminate) {
this.terminate = terminate;
}
synchronized long begin() {
stop();
return generation;
}
synchronized void stop() {
generation++;
if (pid > 1) terminate.accept(pid);
pid = -1;
}
synchronized boolean launch(long expected, IntSupplier launch) {
if (expected != generation) return false;
launches++;
pid = launch.getAsInt();
return true;
}
synchronized boolean current(long expected) {
return expected == generation;
}
/** The latest launch; a sink guard holds it so it never reconfigures a host started after its own. */
synchronized long token() {
return launches;
}
synchronized boolean live(long token) {
return token == launches && pid > 1;
}
synchronized boolean exited(long expected) {
if (expected != generation || pid <= 1) return false;
pid = -1;
return true;
}
}
public PulseAudioComponent(Context context) {
this(context, null);
@@ -64,7 +114,12 @@ public class PulseAudioComponent extends SessionPart {
@Override
public void start() {
stop();
start(host.begin());
}
private synchronized void start(long generation) {
// An exit callback's restart can be overtaken by a newer start; it must not touch the newer host's socket.
if (!host.current(generation)) return;
if (!workingDir.isDirectory()) {
workingDir.mkdirs();
FileUtils.chmod(workingDir, 0771);
@@ -113,22 +168,28 @@ public class PulseAudioComponent extends SessionPart {
env.add("HOME=" + workingDir);
env.add("TMPDIR=" + workingDir);
String command = workingDir.getAbsolutePath() + "/libpulseaudio.so"
String command = String.join(" ", HostProcess.dataExecutable(workingDir.getAbsolutePath() + "/libpulseaudio.so"))
+ " --system=false --disable-shm=true --fail=false"
+ " -n --file=default.pa --daemonize=false --use-pid-file=false --exit-idle-time=-1"
+ " --log-level=info";
final java.io.PrintWriter out = openLog();
pid = HostProcess.start(command, env.toArray(new String[0]), workingDir, null,
if (!host.launch(generation, () -> HostProcess.start(command, env.toArray(new String[0]), workingDir, status -> {
if (host.exited(generation)) {
Log.w(TAG, "audio host exited with status " + status + "; restarting");
start(generation);
}
},
line -> {
Log.i(TAG, line);
if (out != null) synchronized (out) { out.println(line); out.flush(); }
});
Thread guard = new Thread(() -> ensureClientSink(out), "pulse-sink-guard");
}))) return;
long token = host.token();
Thread guard = new Thread(() -> ensureClientSink(out, token), "pulse-sink-guard");
guard.setDaemon(true);
guard.start();
}
private void ensureClientSink(java.io.PrintWriter out) {
private void ensureClientSink(java.io.PrintWriter out, long token) {
try {
// Nothing that may block (a sink whose AAudio open hangs: a Galaxy S24 FE (US) hung the
// daemon's start-up loading one from default.pa) is loaded by the daemon itself; the
@@ -137,14 +198,14 @@ public class PulseAudioComponent extends SessionPart {
long deadline = started + 30000L;
String sinks = null;
boolean socketSeen = false;
while (System.currentTimeMillis() < deadline && pid > 1) {
while (System.currentTimeMillis() < deadline && host.live(token)) {
socketSeen |= socket().exists();
if (socketSeen && (sinks = pactl("list", "short", "sinks")) != null) break;
if (socketSeen && (sinks = pactlFor(token, "list", "short", "sinks")) != null) break;
try { Thread.sleep(250L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
}
note(out, "client sink: daemon " + (sinks != null ? "answered" : "did not answer") + " after "
+ (System.currentTimeMillis() - started) + " ms (socket " + (socketSeen ? "present" : "never appeared") + ", pactl "
+ (new File(workingDir, "pactl").isFile() ? "present" : "MISSING") + ", daemon pid " + pid + ")");
+ (new File(workingDir, "pactl").isFile() ? "present" : "MISSING") + ", daemon pid " + host.pid + ")");
String line;
if (sinks == null) {
line = "== client sink: the daemon did not answer in 30 s; no fallback attempted";
@@ -155,15 +216,15 @@ public class PulseAudioComponent extends SessionPart {
// still switching the output route as the session starts (seen on a Galaxy S24 FE):
// try DirectAudio again, then the plain sink, a few times over ten seconds.
String loadedAs = null;
for (int attempt = 1; attempt <= 5 && loadedAs == null && pid > 1; attempt++) {
for (int attempt = 1; attempt <= 5 && loadedAs == null && host.live(token); attempt++) {
try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
if (pactl("load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1",
if (pactlFor(token, "load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1",
"adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls) != null
&& pactl("set-default-sink", "DirectAudio") != null) {
&& pactlFor(token, "set-default-sink", "DirectAudio") != null) {
loadedAs = "DirectAudio on attempt " + attempt;
} else if (pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink",
} else if (pactlFor(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink",
"performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
&& pactl("set-default-sink", "AAudioSink") != null) {
&& pactlFor(token, "set-default-sink", "AAudioSink") != null) {
loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt;
}
}
@@ -186,15 +247,19 @@ public class PulseAudioComponent extends SessionPart {
if (out != null) synchronized (out) { out.println(line); out.flush(); }
}
private String pactlFor(long token, String... args) {
return host.live(token) ? pactl(args) : null;
}
/** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */
private String pactl(String... args) {
File pactl = new File(workingDir, "pactl");
if (!pactl.isFile() || pid <= 1) return null;
if (!pactl.isFile() || host.pid <= 1) return null;
java.lang.Process process = null;
try {
File modules = new File(workingDir, "modules/arm64");
ArrayList<String> cmd = new ArrayList<>();
cmd.add(pactl.getAbsolutePath());
cmd.addAll(HostProcess.dataExecutable(pactl.getAbsolutePath()));
java.util.Collections.addAll(cmd, args);
ProcessBuilder builder = new ProcessBuilder(cmd);
builder.directory(workingDir);
@@ -231,10 +296,7 @@ public class PulseAudioComponent extends SessionPart {
@Override
public void stop() {
if (pid != -1) {
Process.killProcess(pid);
pid = -1;
}
host.stop();
}
public boolean setSinkSuspended(boolean suspended) {
@@ -247,15 +309,16 @@ public class PulseAudioComponent extends SessionPart {
private boolean suspend(String kind, String name, boolean suspended) {
File pactl = new File(workingDir, "pactl");
if (!pactl.isFile() || pid <= 1) {
if (!pactl.isFile() || host.pid <= 1) {
Log.w(TAG, "cannot change " + kind + " state: PulseAudio control client or server unavailable");
return false;
}
java.lang.Process process = null;
try {
File modules = new File(workingDir, "modules/arm64");
ProcessBuilder builder = new ProcessBuilder(
pactl.getAbsolutePath(), "suspend-" + kind, name, Boolean.toString(suspended));
ArrayList<String> argv = new ArrayList<>(HostProcess.dataExecutable(pactl.getAbsolutePath()));
argv.addAll(java.util.Arrays.asList("suspend-" + kind, name, Boolean.toString(suspended)));
ProcessBuilder builder = new ProcessBuilder(argv);
builder.directory(workingDir);
builder.redirectErrorStream(true);
builder.redirectOutput(new File("/dev/null"));
@@ -31,6 +31,9 @@ internal class AddonPack(
val state: StateFlow<State> = mutableState.asStateFlow()
private val lock = Any()
@Volatile var failure: String? = null
private set
val available: Boolean get() = sha256.isNotEmpty()
private val tag get() = "pack-$name-${sha256.take(16)}"
private val urls get() = listOfNotNull(
@@ -67,9 +70,13 @@ internal class AddonPack(
if (installed(app)) { mutableState.value = State.Ready; return }
if (mutableState.value is State.Downloading) return
mutableState.value = State.Downloading(0f)
failure = null
}
scope.launch {
val ok = runCatching { install(app) }.onFailure { Log.w(TAG, "$name: install failed", it) }.getOrDefault(false)
val ok = runCatching { install(app) }.onFailure {
Log.w(TAG, "$name: install failed", it)
failure = it.toString()
}.getOrDefault(false)
mutableState.value = if (ok) State.Ready else State.Failed
if (ok) onReady(app)
}
@@ -93,20 +100,28 @@ internal class AddonPack(
private fun install(context: Context): Boolean {
if (!available) {
Log.w(TAG, if (reuseDeviceCopy) "$name: this build has no pack and none is installed" else "$name: this build has no pack")
failure = if (reuseDeviceCopy) "this build has no pack and none is installed" else "this build has no pack"
Log.w(TAG, "$name: $failure")
return false
}
val root = root(context).apply { mkdirs() }
val archive = File(root, "$sha256.tar.zst")
val problems = mutableListOf<String>()
val downloaded = bundled(context, archive) || urls.any { url ->
Downloader.downloadFile(url, archive, true, sha256) { p -> mutableState.value = State.Downloading(p.coerceIn(0f, 1f)) }
.also { if (!it) archive.delete() }
.also { if (!it) { archive.delete(); Downloader.lastFailure()?.let(problems::add) } }
}
if (!downloaded) {
failure = problems.joinToString("; ").ifEmpty { "download failed" }
return false
}
if (!downloaded) return false
val staging = File(root, "$sha256.partial")
staging.deleteRecursively()
try {
if (!FileInputStream(archive).use { TarZst.extract(it, staging) }) return false
if (!FileInputStream(archive).use { TarZst.extract(it, staging) }) {
failure = "could not unpack the pack"
return false
}
check(required.all { File(staging, it).isFile }) { "$name pack is incomplete" }
File(staging, COMPLETE).writeText(sha256)
val target = dir(context)
@@ -157,5 +172,8 @@ internal class AddonPack(
listOf("runtime.tzst", "version.txt"))
val UBISOFT = AddonPack("ubisoft", BuildConfig.PACK_UBISOFT_SHA256, BuildConfig.PACK_UBISOFT_SIZE,
listOf("droiddeck-upc.exe"))
val ROCKSTAR = AddonPack("rockstar", BuildConfig.PACK_ROCKSTAR_SHA256, BuildConfig.PACK_ROCKSTAR_SIZE,
listOf("Launcher32.exe", "Launcher64.exe"))
val DIRT = AddonPack("dirt", BuildConfig.PACK_DIRT_SHA256, BuildConfig.PACK_DIRT_SIZE, listOf("ws2_32.dll"))
}
}
@@ -46,6 +46,13 @@ object AppUiPrefs {
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putString("home-page", value).apply()
}
fun hideHomeFromRecents(context: Context): Boolean =
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).getBoolean("hide-home-from-recents", false)
fun setHideHomeFromRecents(context: Context, hidden: Boolean) {
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putBoolean("hide-home-from-recents", hidden).apply()
}
internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE
fun scale(context: Context): Int = normalizeScale(
@@ -233,6 +233,10 @@ object DeviceReport {
else "${turnip.displayName(displayId)} ${turnip.driverVersion(displayId)}".trim()
k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> $displayLabel" else androidChoice)
k(" name / version", displayLabel)
turnip.effectiveId().takeIf { it != displayId }?.let { used ->
k(" in use", if (used == "system") DeviceInfo.builtinDriverLabel(SystemVulkanDriver.isPowerVr(), runtime = false)
else "${turnip.displayName(used)} ${turnip.driverVersion(used)}".trim())
}
k(" imported available", turnip.enumerateImported().ifEmpty { listOf("none") }.joinToString(", "))
val lm = LinuxVulkanDriverManager(context)
run {
@@ -242,7 +246,9 @@ object DeviceReport {
lm.getMinGlibc(id).let { if (it.isEmpty()) "" else " (glibc $it+)" } +
if (lm.isInstalled(id)) "" else if (SystemVulkanDriver.isPowerVr()) " [MISSING - select an installed driver or Auto]"
else " [MISSING - falls back to the runtime's own]"
k("Linux driver", label)
val route = DeviceInfo.hostRoute(context)
k("Linux driver", route ?: label)
if (route != null) k(" chosen, not used", label)
}
k("Runtime's own ICD", LinuxRuntime.vulkanIcd(context)?.path)
k("Mali (Venus)", if (com.droiddeck.launcher.session.VenusComponent.wanted(context)) "in use"
@@ -274,6 +280,7 @@ object DeviceReport {
EsyncPacks.status(LinuxRuntime.rootDir(context)).let { k("droiddeck-esync packs", "${it.installed} installed, ${it.wanted} wanted") }
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
k("pace cores", SessionPrefs.paceCores(context))
k("zRAM: compress Steam during games", SessionPrefs.zramClient(context))
k("RAM cap", SessionPrefs.ramCapMb(context).let { if (it > 0) "$it MB" else "off" })
k("VRAM cap", SessionPrefs.vramCapMb(context).let { if (it > 0) "$it MB" else "driver default" })
@@ -289,6 +296,8 @@ object DeviceReport {
k("Microphone", SessionPrefs.micEnabled(context))
k("On-screen controls", SessionPrefs.oscMode(context))
k("Touch mode", SessionPrefs.touchMode(context))
k("Pen mode", SessionPrefs.penMode(context))
k("Pen side button", SessionPrefs.penButton(context))
k("Performance HUD", SessionPrefs.hudEnabled(context))
k("Game storage", when (val g = SessionPrefs.gameStorage(context)) {
"" -> "automatic (" + (com.droiddeck.launcher.session.GameStorage.effective(context)?.path ?: "no card present") + ")"
@@ -31,8 +31,26 @@ public final class Downloader {
return thread;
});
private static final ThreadLocal<String> LAST_FAILURE = new ThreadLocal<>();
private Downloader() {}
public static String lastFailure() {
return LAST_FAILURE.get();
}
private static void failed(String url, String reason) {
String host;
try { host = new java.net.URI(url).getHost(); } catch (java.net.URISyntaxException e) { host = null; }
String entry = (host == null ? url : host) + ": " + reason;
String earlier = LAST_FAILURE.get();
LAST_FAILURE.set(earlier == null ? entry : earlier + "; " + entry);
}
private static String describe(Exception e) {
return e.getMessage() == null ? e.getClass().getSimpleName() : e.getClass().getSimpleName() + ": " + e.getMessage();
}
public static final class Cancellation implements java.util.function.BooleanSupplier {
private final AtomicBoolean cancelled = new AtomicBoolean();
private final AtomicReference<HttpURLConnection> connection = new AtomicReference<>();
@@ -87,12 +105,14 @@ public final class Downloader {
public static String downloadString(String url, java.util.function.BooleanSupplier cancelled) {
List<String> sources = DownloadSource.INSTANCE.candidates(url);
LAST_FAILURE.remove();
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), cancelled);
if (isCancelled(cancelled)) return null;
if (fetch.body != null) {
LAST_FAILURE.remove();
DownloadSource.INSTANCE.succeeded(sources.get(i));
return fetch.body;
}
@@ -103,6 +123,7 @@ public final class Downloader {
}
public static String downloadDirect(String url) {
LAST_FAILURE.remove();
return fetch(url).body;
}
@@ -138,6 +159,7 @@ public final class Downloader {
String expectedSha256, java.util.function.BooleanSupplier cancelled,
java.util.function.Consumer<Float> progress) {
Identity identity = loadIdentity(destination, resume, expectedSha256);
LAST_FAILURE.remove();
for (int i = 0; i < sources.size(); i++) {
String source = sources.get(i);
if (isCancelled(cancelled)) return false;
@@ -150,12 +172,14 @@ public final class Downloader {
if (isCancelled(cancelled)) return false;
if (!expectedSha256.equalsIgnoreCase(actualSha256)) {
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
failed(source, "checksum mismatch");
if (!discardPartial(destination, identity)) return false;
continue;
}
}
if (isCancelled(cancelled)) return false;
resumeFile(destination).delete();
LAST_FAILURE.remove();
DownloadSource.INSTANCE.succeeded(source);
if (progress != null) progress.accept(1f);
return true;
@@ -260,6 +284,7 @@ public final class Downloader {
}
if (code / 100 != 2) {
Log.w(TAG, url + " -> HTTP " + code);
failed(url, "HTTP " + code);
return code == HttpURLConnection.HTTP_NOT_FOUND || code == HttpURLConnection.HTTP_GONE
? Outcome.FATAL : Outcome.RETRY;
}
@@ -308,11 +333,15 @@ public final class Downloader {
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(input);
}
if (isCancelled(cancelled)) return Outcome.CANCELLED;
if (total > 0 && written < total) return Outcome.RETRY;
if (total > 0 && written < total) {
failed(url, "connection closed after " + written + " of " + total + " bytes");
return Outcome.RETRY;
}
return Outcome.DONE;
} catch (Exception e) {
if (isCancelled(cancelled)) return Outcome.CANCELLED;
Log.w(TAG, "download " + url, e);
failed(url, describe(e));
return Outcome.RETRY;
} finally {
if (connection != null) {
@@ -357,6 +386,7 @@ public final class Downloader {
int code = connection.getResponseCode();
if (code / 100 != 2) {
Log.w(TAG, url + " -> HTTP " + code);
failed(url, "HTTP " + code);
return new Fetch(null, code == HttpURLConnection.HTTP_NOT_FOUND || code == HttpURLConnection.HTTP_GONE);
}
try (InputStream in = connection.getInputStream();
@@ -367,6 +397,7 @@ public final class Downloader {
} catch (Exception e) {
if (isCancelled(cancelled)) return new Fetch(null, false);
Log.w(TAG, "GET " + url, e);
failed(url, describe(e));
return new Fetch(null, false);
} finally {
if (connection != null) {
@@ -6,6 +6,12 @@ import java.util.function.Consumer
object HostProcess {
private const val TAG = "HostProcess"
private const val LINKER = "/system/bin/linker64"
/** Android 10+ refuses to execute app data files for targetSdk 29+; its linker still loads them. */
@JvmStatic
fun dataExecutable(path: String): List<String> =
if (android.os.Build.VERSION.SDK_INT >= 29) listOf(LINKER, path) else listOf(path)
@JvmStatic
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?): Int =
@@ -18,7 +18,7 @@ object SessionLogCapture {
private var syncer: Thread? = null
@Synchronized
fun start(target: File) {
fun start(target: File, sinceMillis: Long) {
stop()
try {
val out = target.bufferedWriter()
@@ -28,7 +28,7 @@ object SessionLogCapture {
writer = out
this.target = target
pid = HostProcess.start(
"/system/bin/logcat -v threadtime -T 1 --pid=" + Process.myPid(),
command(Process.myPid(), sinceMillis),
null, target.parentFile, null,
) { line ->
synchronized(this) {
@@ -49,6 +49,11 @@ object SessionLogCapture {
}
}
internal fun command(pid: Int, sinceMillis: Long): String {
val since = if (sinceMillis > 0) "%d.%03d".format(java.util.Locale.US, sinceMillis / 1000, sinceMillis % 1000) else "1"
return "/system/bin/logcat -v threadtime -T $since --pid=$pid"
}
@Synchronized
fun stopFor(dir: File) {
val t = target ?: return
@@ -1,11 +0,0 @@
package com.droiddeck.launcher.core
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
class ShortcutsListingReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == Intent.ACTION_MY_PACKAGE_REPLACED) SteamIntegration.syncShortcutsListing(context)
}
}
@@ -1,20 +1,21 @@
package com.droiddeck.launcher.core
import android.accessibilityservice.AccessibilityServiceInfo
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import android.view.accessibility.AccessibilityManager
import com.droiddeck.launcher.HomeApp
import com.droiddeck.launcher.input.HomeButtonService
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.shortcuts.Relay
import java.io.File
object SteamIntegration {
const val ACTION_SETUP = "com.droiddeck.launcher.STEAM_INTEGRATION"
const val EXTRA_FEATURE = "integration_feature"
const val SHORTCUTS_STATUS = "com.droiddeck.launcher.SHORTCUTS_INSTALL_STATUS"
private const val SHORTCUTS_ASSET = "shortcuts.apk"
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS }
data class State(
@@ -36,11 +37,7 @@ object SteamIntegration {
locationOn = WifiDiscovery.locationEnabled(context),
brightness = Settings.System.canWrite(context),
home = HomeApp.isDefault(context),
shortcuts = context.getSystemService(AccessibilityManager::class.java)
.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK).any {
val service = it.resolveInfo.serviceInfo
ComponentName(service.packageName, service.name) == ComponentName(context, HomeButtonService::class.java)
},
shortcuts = shortcutsEnabled(context),
shortcutsRestricted = restrictedSettings(context),
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
)
@@ -48,48 +45,53 @@ object SteamIntegration {
private fun restrictedSettings(context: Context): Boolean {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
val mode = runCatching {
val uid = context.packageManager.getApplicationInfo(Relay.PACKAGE, 0).uid
context.getSystemService(android.app.AppOpsManager::class.java)
.unsafeCheckOpNoThrow("android:access_restricted_settings", android.os.Process.myUid(), context.packageName)
.unsafeCheckOpNoThrow("android:access_restricted_settings", uid, Relay.PACKAGE)
}.getOrDefault(android.app.AppOpsManager.MODE_ALLOWED)
return mode == android.app.AppOpsManager.MODE_ERRORED || mode == android.app.AppOpsManager.MODE_IGNORED
}
private fun shortcutsComponent(context: Context) = ComponentName(context, HomeButtonService::class.java)
private val shortcutsComponent = ComponentName(Relay.PACKAGE, Relay.SERVICE)
fun shortcutsChosen(context: Context): Boolean = shortcutsSelection(context) == true
private fun shortcutsSelection(context: Context): Boolean? {
val target = shortcutsComponent(context)
fun shortcutsEnabled(context: Context): Boolean {
val enabled = runCatching {
Settings.Secure.getString(context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)
}.getOrElse { return null }.orEmpty()
return enabled.split(':').any { ComponentName.unflattenFromString(it.trim()) == target }
}.getOrNull().orEmpty()
return enabled.split(':').any { ComponentName.unflattenFromString(it.trim()) == shortcutsComponent }
}
fun setShortcutsListed(context: Context, listed: Boolean) {
fun shortcutsListed(context: Context): Boolean =
context.getSystemService(android.view.accessibility.AccessibilityManager::class.java)
?.installedAccessibilityServiceList.orEmpty()
.any { ComponentName(it.resolveInfo.serviceInfo.packageName, it.resolveInfo.serviceInfo.name) == shortcutsComponent }
fun bundledShortcuts(context: Context): File {
val target = File(context.cacheDir, SHORTCUTS_ASSET)
context.assets.open(SHORTCUTS_ASSET).use { input -> target.outputStream().use { input.copyTo(it) } }
return target
}
fun shortcutsInstalled(context: Context, bundled: File): Boolean {
val packages = context.packageManager
val component = shortcutsComponent(context)
val state = if (listed) PackageManager.COMPONENT_ENABLED_STATE_ENABLED else PackageManager.COMPONENT_ENABLED_STATE_DISABLED
runCatching {
if (packages.getComponentEnabledSetting(component) != state) {
packages.setComponentEnabledSetting(component, state, PackageManager.DONT_KILL_APP)
}
}
}
fun syncShortcutsListing(context: Context) {
shortcutsSelection(context)?.let { setShortcutsListed(context, it) }
@Suppress("DEPRECATION")
val installed = runCatching { packages.getPackageInfo(Relay.PACKAGE, 0).versionCode }.getOrNull() ?: return false
@Suppress("DEPRECATION")
val shipped = packages.getPackageArchiveInfo(bundled.absolutePath, 0)?.versionCode ?: return true
return installed >= shipped
}
fun dismissSuggestion(context: Context) {
SessionPrefs.sessionPrefs(context).edit().putBoolean("steam_integration_seen", true).apply()
}
fun shortcutsAppInfo() = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${Relay.PACKAGE}"))
fun brightnessSettings(context: Context) = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
Uri.parse("package:${context.packageName}"))
fun shortcutSettings(context: Context): Intent {
val service = ComponentName(context, HomeButtonService::class.java).flattenToString()
val service = shortcutsComponent.flattenToString()
return Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
.putExtra(":settings:fragment_args_key", service)
.putExtra(":settings:show_fragment_args", android.os.Bundle().apply { putString(":settings:fragment_args_key", service) })
@@ -112,6 +112,10 @@ private const val HISTORY_LIMIT = 50
internal fun canNavigateUp(currentDir: File, currentRoot: File): Boolean =
currentDir != currentRoot && currentDir.parentFile?.exists() == true
// Back leaves after a drive hop instead of replaying a stack of hops one press at a time.
internal fun backExitsAtRootHop(currentDir: File, currentRoot: File, previous: Pair<File, File>): Boolean =
currentDir == currentRoot && previous.first == previous.second
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FileManagerScreen(
@@ -269,8 +273,10 @@ fun FileManagerScreen(
if (showFavorites) showFavorites = false
else {
while (history.isNotEmpty() && !history.last().first.isDirectory) history.removeAt(history.lastIndex)
val previous = history.removeLastOrNull()
if (previous != null) {
val previous = history.lastOrNull()
if (previous != null && backExitsAtRootHop(currentDir, currentRoot, previous)) onExit?.invoke()
else if (previous != null) {
history.removeLastOrNull()
currentRoot = previous.second
loadDirectory(previous.first, record = false)
} else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it, record = false) }
@@ -100,12 +100,13 @@ object AddedGames {
fun candidates(folder: File, reuse: Boolean = false): List<File> = rank(folder, reuse).exes
fun rank(folder: File, reuse: Boolean = false): GameExePicker.Ranking {
val key = "${folder.path}|${folder.lastModified()}"
val declared = declaredExes(folder)
val stamp = declared.fold(0L) { hash, exe -> hash * 31 + exe.path.hashCode() }
val key = "${folder.path}|${folder.lastModified()}|$stamp"
val now = System.currentTimeMillis()
ranked[key]?.takeIf { now - it.first < RANK_FRESH_MS }?.let { return it.second }
if (reuse) kept?.rank(folder)?.let { return it }
if (reuse) kept?.rank(folder, stamp)?.let { return it }
val guessed = GameExePicker.rank(folder) { !skipExe(it.name) }
val declared = declaredExes(folder)
val preferred = declared.map { it.path }.toSet()
val result = if (declared.isEmpty()) guessed else GameExePicker.Ranking(
declared + guessed.exes.filter { it.path !in preferred },
@@ -115,7 +116,7 @@ object AddedGames {
)
if (ranked.size > 256) ranked.clear()
ranked[key] = now to result
kept?.keepRank(folder, result)
kept?.keepRank(folder, result, stamp)
return result
}
@@ -200,8 +201,7 @@ object AddedGames {
private val scanning = Any()
fun scan(context: Context): List<Game> = synchronized(scanning) {
val file = File(context.filesDir, AddedGamesCache.FILE)
val cache = kept?.takeIf { it.file == file } ?: AddedGamesCache(file).also { kept = it }
val cache = cache(context)
try {
scanAll(context)
} finally {
@@ -209,6 +209,13 @@ object AddedGames {
}
}
private val keeping = Any()
private fun cache(context: Context): AddedGamesCache = synchronized(keeping) {
val file = File(context.filesDir, AddedGamesCache.FILE)
kept?.takeIf { it.file == file } ?: AddedGamesCache(file).also { kept = it }
}
private fun scanAll(context: Context): List<Game> {
val out = ArrayList<Game>()
GamesFolderMigration.run(context)
@@ -241,11 +248,17 @@ object AddedGames {
return out.distinctBy { it.folder.canonicalPath }
}
fun single(context: Context, folderPath: String): Game? {
fun single(context: Context, folderPath: String, reuse: Boolean = false): Game? {
val folder = File(folderPath)
if (!folder.isDirectory || folderPath in SessionPrefs.removedAddedGames(context)) return null
val out = ArrayList<Game>(1)
scanGame(context, folder, out, single = AddedExes.list(context).firstOrNull { it.folder == folderPath })
val entry = AddedExes.list(context).firstOrNull { it.folder == folderPath }
val cache = if (reuse) cache(context) else null
try {
scanGame(context, folder, out, single = entry, reuse = reuse)
} finally {
cache?.save()
}
return out.firstOrNull()
}
@@ -7,7 +7,7 @@ import java.io.File
import java.util.concurrent.ConcurrentHashMap
internal class AddedGamesCache(val file: File) {
private class Rank(val modified: Long, val at: Long, val ranking: GameExePicker.Ranking)
private class Rank(val modified: Long, val declared: Long, val at: Long, val ranking: GameExePicker.Ranking)
private class Name(val name: String, val at: Long)
private val ranks = ConcurrentHashMap<String, Rank>()
@@ -22,7 +22,7 @@ internal class AddedGamesCache(val file: File) {
val exes = o.getJSONArray("exes")
val scores = o.getJSONArray("scores")
require(exes.length() > 0 && exes.length() == scores.length())
ranks[path] = Rank(o.getLong("modified"), o.getLong("at"), GameExePicker.Ranking(
ranks[path] = Rank(o.getLong("modified"), o.optLong("declared"), o.getLong("at"), GameExePicker.Ranking(
List(exes.length()) { File(exes.getString(it)) }, List(scores.length()) { scores.getInt(it) }, o.optBoolean("uncertain"),
))
}
@@ -32,19 +32,19 @@ internal class AddedGamesCache(val file: File) {
}
}
fun rank(folder: File): GameExePicker.Ranking? {
fun rank(folder: File, declared: Long = 0): GameExePicker.Ranking? {
val kept = ranks[folder.path] ?: return null
val age = System.currentTimeMillis() - kept.at
val top = kept.ranking.exes.first()
return kept.ranking.takeIf { kept.modified == folder.lastModified() && age in 0 until KEEP_MS && top.isFile }
return kept.ranking.takeIf { kept.modified == folder.lastModified() && kept.declared == declared && age in 0 until KEEP_MS && top.isFile }
}
fun keepRank(folder: File, ranking: GameExePicker.Ranking) {
fun keepRank(folder: File, ranking: GameExePicker.Ranking, declared: Long = 0) {
if (ranking.exes.isEmpty()) {
if (ranks.remove(folder.path) != null) changed = true
return
}
ranks[folder.path] = Rank(folder.lastModified(), System.currentTimeMillis(), ranking)
ranks[folder.path] = Rank(folder.lastModified(), declared, System.currentTimeMillis(), ranking)
changed = true
}
@@ -62,7 +62,7 @@ internal class AddedGamesCache(val file: File) {
val oldest = System.currentTimeMillis() - KEEP_MS
val keptRanks = JSONObject()
ranks.forEach { (path, r) ->
if (r.at >= oldest) keptRanks.put(path, JSONObject().put("modified", r.modified).put("at", r.at)
if (r.at >= oldest) keptRanks.put(path, JSONObject().put("modified", r.modified).put("declared", r.declared).put("at", r.at)
.put("exes", JSONArray(r.ranking.exes.map { it.path })).put("scores", JSONArray(r.ranking.scores))
.put("uncertain", r.ranking.uncertain))
}
@@ -43,11 +43,14 @@ object GameFileSync {
val storageSetting = SessionPrefs.gameStorage(context)
val previousStorage = prefs(context).getString("storagePath", null)
if (storageSetting.isEmpty() && prefs(context).getString("storageSetting", null) == storageSetting && previousStorage != null) {
check(File(previousStorage).isDirectory) { context.getString(R.string.game_sync_err_previous_sd) }
check(libraryReadable(File(previousStorage))) { context.getString(R.string.game_sync_err_previous_sd) }
}
storage?.let { check(File(it.path).listFiles() != null) { context.getString(R.string.game_sync_err_game_storage) } }
storage?.let { check(libraryReadable(File(it.path))) { context.getString(R.string.game_sync_err_game_storage) } }
AddedGames.roots(context).forEach { check(it.host.listFiles() != null) { context.getString(R.string.game_sync_err_added_games) } }
GameFiles.sync(context, folder, Library.launchableGames(context, strictRead = true))
prefs(context).edit().putString("storageSetting", storageSetting).putString("storagePath", storage?.path).apply()
}
internal fun libraryReadable(dir: File): Boolean =
dir.listFiles() != null || (!dir.exists() && dir.parentFile?.isDirectory == true)
}
@@ -0,0 +1,39 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
object SteamInputOverride {
private const val CONFIG_KEY = "UseSteamControllerConfig"
private const val DEFAULT_VALUE = "1"
enum class Mode(val value: String?) {
DEFAULT(null), ENABLED("2"), DISABLED("0");
companion object {
fun from(value: String): Mode? = when (value) {
DEFAULT_VALUE -> DEFAULT
"2" -> ENABLED
"0" -> DISABLED
else -> null
}
}
}
enum class Saved { YES, NO, RUNNING }
fun current(context: Context, appId: Int): Mode? =
SteamLaunchOptions.steamAppSetting(
SessionPrefs.activeSteamRoot(context), appId, CONFIG_KEY, DEFAULT_VALUE,
)?.let(Mode::from)
fun set(context: Context, appId: Int, mode: Mode, shown: Mode): Saved {
if (SessionState.running) return Saved.RUNNING
val saved = SteamLaunchOptions.writeSteamAppSetting(
SessionPrefs.activeSteamRoot(context), appId, CONFIG_KEY,
shown.value ?: DEFAULT_VALUE, mode.value, DEFAULT_VALUE,
)
return if (saved) Saved.YES else Saved.NO
}
}
@@ -13,6 +13,8 @@ import java.nio.file.StandardCopyOption
object SteamLaunchOptions {
private const val TAG = "SteamLaunchOptions"
private val STEAM = listOf("UserLocalConfigStore", "Software", "Valve", "Steam")
// Steam keeps per-game settings such as UseSteamControllerConfig in the root apps section, and launch options under Software/Valve/Steam.
private val ROOT = listOf("UserLocalConfigStore")
fun current(context: Context, appId: Int): String? =
SteamLiveShortcuts.launchOptions(context, appId.toLong()) ?: steam(SessionPrefs.activeSteamRoot(context), appId)
@@ -36,13 +38,38 @@ object SteamLaunchOptions {
val config = AddedGames.accountConfig(steamHome) ?: return null
val text = runCatching { File(config, "localconfig.vdf").readText() }.getOrNull() ?: return null
if (section(text, STEAM) == null) return null
return launchOptions(text, appId).orEmpty()
return appValue(text, appId, "LaunchOptions").orEmpty()
}
internal fun write(steamHome: File, appId: Int, options: String): Boolean {
val config = AddedGames.accountConfig(steamHome)?.let { File(it, "localconfig.vdf") } ?: return false
val text = runCatching { config.readText() }.getOrNull() ?: return false
val updated = withLaunchOptions(text, appId, options) ?: return false
return writeConfig(config, text, updated)
}
internal fun steamAppSetting(steamHome: File, appId: Int, key: String, default: String): String? {
val config = AddedGames.accountConfig(steamHome) ?: return null
val text = runCatching { File(config, "localconfig.vdf").readText() }.getOrNull() ?: return null
if (section(text, ROOT) == null) return null
return settingValue(text, appId, key) ?: default
}
private fun settingValue(text: String, appId: Int, key: String): String? =
appValue(text, appId, key, ROOT) ?: appValue(text, appId, key, STEAM)
internal fun writeSteamAppSetting(
steamHome: File, appId: Int, key: String, expected: String, value: String?, default: String,
): Boolean {
val config = AddedGames.accountConfig(steamHome)?.let { File(it, "localconfig.vdf") } ?: return false
val text = runCatching { config.readText() }.getOrNull() ?: return false
if (section(text, ROOT) == null || (settingValue(text, appId, key) ?: default) != expected) return false
val updated = (if (value == null) withoutAppValue(text, appId, key, ROOT) else withAppValue(text, appId, key, value, ROOT))
?.let { withoutAppValue(it, appId, key, STEAM) } ?: return false
return writeConfig(config, text, updated)
}
private fun writeConfig(config: File, text: String, updated: String): Boolean {
if (updated == text) return true
val staged = File(config.parentFile, config.name + ".staged")
return try {
@@ -55,36 +82,57 @@ object SteamLaunchOptions {
true
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not write launch options to ${config.path}", e)
Log.w(TAG, "could not write Steam app settings to ${config.path}", e)
false
}
}
internal fun launchOptions(text: String, appId: Int): String? {
val app = section(text, STEAM + "apps" + appId.toString()) ?: return null
return entries(text, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals("LaunchOptions", true) }
return appValue(text, appId, "LaunchOptions")
}
private fun appValue(text: String, appId: Int, key: String, base: List<String> = STEAM): String? {
val app = section(text, base + "apps" + appId.toString()) ?: return null
return entries(text, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals(key, true) }
?.let { unescape(text.substring(it.valueStart + 1, it.end)) }
}
internal fun withLaunchOptions(text: String, appId: Int, options: String): String? {
internal fun withLaunchOptions(text: String, appId: Int, options: String): String? =
withAppValue(text, appId, "LaunchOptions", options)
private fun withAppValue(text: String, appId: Int, key: String, rawValue: String, base: List<String> = STEAM): String? {
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
var updated = text
var path = STEAM
for (key in listOf("apps", appId.toString())) {
updated = withSection(updated, section(updated, path) ?: return null, key, newline) ?: return null
path = path + key
var path = base
for (pathPart in listOf("apps", appId.toString())) {
updated = withSection(updated, section(updated, path) ?: return null, pathPart, newline) ?: return null
path = path + pathPart
}
val app = section(updated, path) ?: return null
val value = "\"" + escape(options) + "\""
entries(updated, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals("LaunchOptions", true) }?.let {
val value = "\"" + escape(rawValue) + "\""
entries(updated, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals(key, true) }?.let {
return updated.replaceRange(it.valueStart, it.end + 1, value)
}
val lineStart = closingLine(updated, app) ?: return null
val indent = updated.substring(lineStart, app.end) + "\t"
return updated.substring(0, lineStart) + indent + "\"LaunchOptions\"\t\t" + value + newline + updated.substring(lineStart)
return updated.substring(0, lineStart) + indent + "\"${escape(key)}\"\t\t" + value + newline + updated.substring(lineStart)
}
private class Entry(val key: String, val valueStart: Int, val end: Int, val section: Boolean)
private fun withoutAppValue(text: String, appId: Int, key: String, base: List<String> = STEAM): String {
val app = section(text, base + "apps" + appId.toString()) ?: return text
val entry = entries(text, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals(key, true) } ?: return text
val lineStart = text.lastIndexOf('\n', entry.start - 1) + 1
val lineEnd = text.indexOf('\n', entry.end + 1).let { if (it < 0) text.length else it }
val onlyEntryOnLine = text.substring(lineStart, entry.start).all(Char::isWhitespace) &&
text.substring(entry.end + 1, lineEnd).all(Char::isWhitespace)
return if (onlyEntryOnLine) {
text.removeRange(lineStart, if (lineEnd < text.length) lineEnd + 1 else lineEnd)
} else {
text.removeRange(entry.start, entry.end + 1)
}
}
private class Entry(val key: String, val start: Int, val valueStart: Int, val end: Int, val section: Boolean)
private fun section(text: String, path: List<String>): Entry? {
var found: Entry? = null
@@ -98,18 +146,27 @@ object SteamLaunchOptions {
private fun entries(text: String, open: Int, close: Int): List<Entry> {
val found = ArrayList<Entry>()
var key: String? = null
var keyStart = -1
var i = open + 1
while (i < close) {
when {
text[i] == '"' -> {
val end = stringEnd(text, i) ?: return found
if (key == null) key = unescape(text.substring(i + 1, end)) else { found += Entry(key, i, end, false); key = null }
if (key == null) {
key = unescape(text.substring(i + 1, end))
keyStart = i
} else {
found += Entry(key, keyStart, i, end, false)
key = null
keyStart = -1
}
i = end + 1
}
text[i] == '{' -> {
val end = sectionEnd(text, i) ?: return found
key?.let { found += Entry(it, i, end, true) }
key?.let { found += Entry(it, keyStart, i, end, true) }
key = null
keyStart = -1
i = end + 1
}
text.startsWith("//", i) -> i = text.indexOf('\n', i).let { if (it < 0) close else it }
@@ -563,7 +563,7 @@ object Glasses {
val device = selected?.first
val m = selected?.second
val controllable = m?.let(::canOpenModel) == true
val permitted = controllable && device != null && (m === XrealModel || usb.hasPermission(device))
val permitted = controllable && device != null && (m is XrealModel || usb.hasPermission(device))
val identity = device?.let {
GlassesModeState.Device(it.productId, if (permitted) runCatching { it.serialNumber }.getOrNull() else null)
}
@@ -614,9 +614,9 @@ object Glasses {
sbs = sbsByDisplay,
switching3d = modeState.pendingStereo,
brightnessMax = m?.brightnessMax ?: 8, volumeMax = m?.volumeMax ?: 8,
sunblock = if (m === XrealModel) it.sunblock else _settings.value.sunblock ?: it.sunblock,
sunblock = if (m is XrealModel) it.sunblock else _settings.value.sunblock ?: it.sunblock,
hardwareControls = m?.hardwareControls == true &&
(device?.vendorId == VitureProtocol.VENDOR_ID || m === XrealModel || m is RokidModel),
(device?.vendorId == VitureProtocol.VENDOR_ID || m is XrealModel || m is RokidModel),
supportsDisplayModeControl = m?.supportsDisplayModeControl == true,
hasSunblock = m?.hasSunblock == true,
diagonalFovDeg = m?.diagonalFovDeg ?: 46f,
@@ -624,7 +624,7 @@ object Glasses {
noSignal = noSignal,
sbs90 = m?.sbs90 == true,
rates2d = m?.rates2d ?: listOf(60, 90, 120),
experimental = m === XrealModel || (m is VitureProtocol.Model && m.family == VitureProtocol.Family.PRO2 && !m.needsSdk),
experimental = m is XrealModel || (m is VitureProtocol.Model && m.family == VitureProtocol.Family.PRO2 && !m.needsSdk),
supportsScreen3dof = link?.hasImu == true,
supports30Hz = display?.let(::supports30Hz) == true,
supportsSpatial = (link as? VitureSdkLink)?.isCarina == true,
@@ -660,8 +660,8 @@ object Glasses {
else VitureSdk.marketName(device.productId)?.let(VitureProtocol::sdkModel)
?: VitureProtocol.model(device.productId, name)
}
else if (XrealModel.matches(device.vendorId, device.productId)) XrealModel
else RokidModel.model(device.vendorId, device.productId, name)
else XrealModel.model(device.vendorId, device.productId)
?: RokidModel.model(device.vendorId, device.productId, name)
?: RayNeoModel.model(device.vendorId, device.productId, name)
}
@@ -729,8 +729,8 @@ object Glasses {
VitureSdkLink.open(usb, device, File(app.noBackupFilesDir, "viture"), sdkListener(generation),
(model as? VitureProtocol.Model)?.family, spatial)
} else VitureLink.open(usb, device, linkListener(generation))
} else if (model === XrealModel) {
XrealLink.open(app, xrealListener(generation))
} else if (model is XrealModel) {
XrealLink.open(app, model as XrealModel, xrealListener(generation))
} else if (model is RokidModel) {
RokidLink.open(usb, device, rokidListener(generation))
} else {
@@ -10,6 +10,7 @@ import java.util.concurrent.atomic.AtomicReference
internal class XrealLink internal constructor(
private val connector: XrealConnector,
private val listener: Listener,
private val model: XrealModel = XrealModel.ONE_S,
) : GlassesLink {
interface Listener {
fun onReady()
@@ -29,7 +30,8 @@ internal class XrealLink internal constructor(
private val worker = Thread(::run, "xreal-control").apply { isDaemon = true; start() }
companion object {
fun open(context: Context, listener: Listener) = XrealLink(AndroidXrealConnector(context), listener)
fun open(context: Context, model: XrealModel, listener: Listener) =
XrealLink(AndroidXrealConnector(context), listener, model)
}
override fun send(msgId: Int, payload: ByteArray): Boolean {
@@ -43,9 +45,10 @@ internal class XrealLink internal constructor(
if (msgId == VitureProtocol.MSG_GET_IMU) return true
val valid = when (msgId) {
VitureProtocol.MSG_GET_DISPLAY -> true
VitureProtocol.MSG_DISPLAY -> value in 2..5 || value == XrealModel.NATIVE_60HZ
VitureProtocol.MSG_BRIGHTNESS -> value in 0..9
VitureProtocol.MSG_FILM -> value in 0..1
VitureProtocol.MSG_DISPLAY -> if (model.stereoOnlyControl) value == 5 || value == XrealModel.NATIVE_60HZ
else value in 2..5 || value == XrealModel.NATIVE_60HZ
VitureProtocol.MSG_BRIGHTNESS -> !model.stereoOnlyControl && value in 0..9
VitureProtocol.MSG_FILM -> !model.stereoOnlyControl && value in 0..1
else -> false
}
return valid && commands.offer(Command(msgId, value))
@@ -61,12 +64,12 @@ internal class XrealLink internal constructor(
channels = connector.connect()
connection.set(channels)
if (!running) break
val control = XrealControl(channels)
val control = XrealControl(channels, stereoOnly = model.stereoOnlyControl)
listener.onValue(VitureProtocol.MSG_GET_DISPLAY, control.display())
val current = channels
reports = Thread({
try {
var filter = XrealOrientationFilter()
var filter = XrealOrientationFilter(model.flipsYz)
var wasTracking = false
var lastSensor = System.nanoTime()
while (running && connection.get() === current) {
@@ -75,7 +78,7 @@ internal class XrealLink internal constructor(
if (sample != null) {
lastSensor = System.nanoTime()
val enabled = tracking
if (enabled && !wasTracking) filter = XrealOrientationFilter()
if (enabled && !wasTracking) filter = XrealOrientationFilter(model.flipsYz)
wasTracking = enabled
if (enabled) filter.update(sample)?.let {
if (running && ready && tracking && connection.get() === current)
@@ -149,7 +152,11 @@ internal class XrealLink internal constructor(
}
}
internal class XrealControl(private val channels: XrealChannels, private val settleDelayMs: Long = 150) {
internal class XrealControl(
private val channels: XrealChannels,
private val settleDelayMs: Long = 150,
private val stereoOnly: Boolean = false,
) {
private var transaction = 0
private fun exchange(command: Int, value: Int? = null): ByteArray {
transaction = if (transaction == Int.MAX_VALUE) 1 else transaction + 1
@@ -163,26 +170,42 @@ internal class XrealControl(private val channels: XrealChannels, private val set
throw IOException("XREAL control response was not received")
}
fun display(): Int {
if (stereoOnly) return stereoDisplay()
val reply = exchange(XrealProtocol.GET_DISPLAY)
return XrealProtocol.numeric(reply)?.takeIf { it in 2..5 || it == XrealModel.NATIVE_60HZ }
?: throw IOException("Unsupported XREAL display response: ${reply.take(32).joinToString("") { "%02x".format(it) }}")
}
private fun stereoDisplay(): Int {
val reply = exchange(XrealProtocol.GET_INPUT)
return when {
XrealProtocol.acknowledged(reply) -> XrealModel.NATIVE_60HZ
else -> when (XrealProtocol.numeric(reply)) {
0 -> XrealModel.NATIVE_60HZ
1 -> 5
else -> throw IOException("Unsupported XREAL stereo response: ${reply.take(32).joinToString("") { "%02x".format(it) }}")
}
}
}
fun changeDisplay(mode: Int): Int {
val stereo = mode == 5
set(XrealProtocol.SET_INPUT, if (stereo) 1 else 0)
val current = awaitDisplay { (it == 5) == stereo }
if (current == mode) return current
if (current == mode || stereoOnly) return current
set(XrealProtocol.SET_DISPLAY, mode)
return awaitDisplay { it == mode }
}
private fun awaitDisplay(matches: (Int) -> Boolean): Int {
val deadline = System.nanoTime() + 8_000_000_000L
repeat(40) {
val reply = exchange(XrealProtocol.GET_DISPLAY)
val value = XrealProtocol.numeric(reply)
if (value != null && matches(value)) return value
if (value == null && !XrealProtocol.acknowledged(reply))
throw IOException("Invalid XREAL display transition response")
if (stereoOnly) {
stereoDisplay().let { if (matches(it)) return it }
} else {
val reply = exchange(XrealProtocol.GET_DISPLAY)
val value = XrealProtocol.numeric(reply)
if (value != null && matches(value)) return value
if (value == null && !XrealProtocol.acknowledged(reply))
throw IOException("Invalid XREAL display transition response")
}
if (System.nanoTime() > deadline) throw IOException("XREAL display transition timed out")
Thread.sleep(settleDelayMs)
}
@@ -1,25 +1,63 @@
package com.droiddeck.launcher.glasses
object XrealModel : GlassesModel {
const val VENDOR_ID = 0x3318
const val PRODUCT_1S = 0x043e
const val NATIVE_60HZ = 29
override val name = "XREAL 1S"
internal class XrealModel private constructor(
override val name: String,
val family: Family,
override val diagonalFovDeg: Float,
) : GlassesModel {
enum class Family {
ONE_S,
ONE,
AURA,
}
override val controllable = true
override val brightnessMax = 9
override val volumeMax = 0
override val hasSunblock = true
override val diagonalFovDeg = 52f
override val hasSunblock get() = family == Family.ONE_S
override val hardwareControls get() = family == Family.ONE_S
override val sbs90 = false
override val rates2d get() = if (family == Family.ONE_S) super.rates2d else listOf(60)
fun matches(vid: Int, pid: Int) = vid == VENDOR_ID && pid == PRODUCT_1S
fun isDisplay(name: String) = name.contains("XREAL", ignoreCase = true)
// Only the 1S has been exercised with SET_DISPLAY; the Aura is known to reboot on an unexpected index.
val stereoOnlyControl get() = family != Family.ONE_S
// The Aura reports x right, y up, z back; the rest of the One family is a half turn about x from it.
val flipsYz get() = family != Family.AURA
override fun mode(hz: Int, sbs: Boolean) = when {
sbs -> 5
stereoOnlyControl -> NATIVE_60HZ
hz >= 120 -> 4
hz >= 90 -> 3
else -> NATIVE_60HZ
}
override fun modeForStep(step: Int): Int? = null
override fun toString() = name
companion object {
const val VENDOR_ID = 0x3318
const val PRODUCT_1S = 0x043e
const val NATIVE_60HZ = 29
val ONE_S = XrealModel("XREAL 1S", Family.ONE_S, 52f)
val ONE = XrealModel("XREAL One", Family.ONE, 50f)
val ONE_PRO = XrealModel("XREAL One Pro", Family.ONE, 57f)
val ONE_PRO_PLUS = XrealModel("XREAL One Pro+", Family.ONE, 57f)
val AURA = XrealModel("XREAL Aura", Family.AURA, 70f)
// The odd product ids one below these are the glasses' recovery mode.
private val products = mapOf(
PRODUCT_1S to ONE_S,
0x0438 to ONE,
0x0436 to ONE_PRO,
0x0444 to ONE_PRO_PLUS,
0x043a to AURA,
)
fun model(vid: Int, pid: Int): XrealModel? = if (vid == VENDOR_ID) products[pid] else null
fun matches(vid: Int, pid: Int) = model(vid, pid) != null
fun isDisplay(name: String) = name.contains("XREAL", ignoreCase = true)
}
}
@@ -2,12 +2,13 @@ package com.droiddeck.launcher.glasses
import kotlin.math.abs
internal class XrealOrientationFilter {
internal class XrealOrientationFilter(private val flipYz: Boolean = true) {
private val fusion = ImuFusion()
fun update(sample: XrealProtocol.Sample): FloatArray? = fusion.update(sample.timeNs,
Vec3(sample.accel.x, -sample.accel.y, -sample.accel.z),
Vec3(sample.gyro.x, -sample.gyro.y, -sample.gyro.z))
sample.accel.headAxes(), sample.gyro.headAxes())
private fun Vec3.headAxes() = if (flipYz) Vec3(x, -y, -z) else this
}
internal class ImuFusion {
@@ -13,6 +13,7 @@ internal object XrealProtocol {
const val REPORT = 0x2836
const val GET_DISPLAY = 0x275e
const val SET_DISPLAY = 0x275f
const val GET_INPUT = 0x2821
const val SET_INPUT = 0x2822
const val SET_BRIGHTNESS = 0x271c
const val SET_DIMMER = 0x2727
@@ -145,16 +145,22 @@ object DeviceInfo {
private fun drivers(context: Context, gpu: GpuInfo) = Section("Drivers DroidDeck uses", buildList<Pair<String, String>> {
add("Driver mode", SessionPrefs.gpuDriverMode(context))
val turnip = TurnipDriver(context)
val choice = SessionPrefs.androidDriver(context).ifEmpty { turnip.autoId() }
val choice = turnip.effectiveId()
val powerVr = gpu.family == GpuInfo.Family.POWERVR
add("Display driver", if (choice == "system") builtinDriverLabel(powerVr, runtime = false)
else "${turnip.displayName(choice)} ${turnip.driverVersion(choice)}".trim())
val linux = LinuxVulkanDriverManager(context)
val id = SessionPrefs.linuxDriver(context)
add("Game driver", if (id.isEmpty()) builtinDriverLabel(powerVr, runtime = true) else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
add("Game driver", hostRoute(context) ?: if (id.isEmpty()) builtinDriverLabel(powerVr, runtime = true) else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
if (gpu.oneUi8Gen2) add("Note", "One UI on an 8 Gen 2: needs the OneUI Turnip build")
})
internal fun hostRoute(context: Context): String? = when {
com.droiddeck.launcher.session.VenusComponent.wanted(context) -> "Mali (Venus)"
com.droiddeck.launcher.core.DeviceSupport.vkBridge(context) -> "the Mali bridge"
else -> null
}
/** Shared by the device card and the session report, which are written in English. */
internal fun builtinDriverLabel(powerVr: Boolean, runtime: Boolean): String = when {
powerVr -> "System PowerVR"
@@ -34,6 +34,8 @@ public final class TurnipDriver {
public static final List<String> BUNDLED = Collections.unmodifiableList(Arrays.asList(
DRIVER_A7XX, DRIVER_A8XX, com.droiddeck.launcher.session.QuestExperimental.DRIVER,
DRIVER_A6XX, com.droiddeck.launcher.session.QuestExperimental.DRIVER_A6XX));
private static final String KGSL_NODE = "/dev/kgsl-3d0";
private static final String KGSL_SYSFS = "/sys/class/kgsl/kgsl-3d0";
private static final String OVERRIDE_FILE = "Download/droiddeck-driver";
private static final String PREFS = "graphics_driver";
private static final String KEY_HIDDEN = "hiddenBundled";
@@ -140,6 +142,25 @@ public final class TurnipDriver {
return id == null ? "system" : id;
}
public String effectiveId() {
String id = choose();
return id == null || !reachesGpu(id) ? "system" : id;
}
public boolean reachesGpu(String driverId) {
String library = libraryName(driverId);
return library == null || !needsMissingKgsl(new File(new File(contentDir, driverId), library),
kgslPresent(new File(KGSL_NODE), new File(KGSL_SYSFS)));
}
static boolean kgslPresent(File node, File sysfs) {
return node.exists() || sysfs.exists();
}
static boolean needsMissingKgsl(File library, boolean kgsl) {
return !kgsl && library.isFile() && LinuxVulkanDriverManager.containsAscii(library, KGSL_NODE);
}
public void remove(String driverId) {
if (driverId == null || driverId.isEmpty() || BUNDLED.contains(driverId)
|| driverId.contains("/") || driverId.contains("..")) return;
@@ -257,6 +278,11 @@ public final class TurnipDriver {
Log.e(TAG, id + " unpacked without " + library);
return null;
}
if (!reachesGpu(id)) {
Log.w(TAG, id + " needs " + KGSL_NODE + ", which this GPU does not have; display on the system Vulkan loader");
DriverSetupLog.write(context, "install.no-kgsl driver=" + id);
return null;
}
Log.i(TAG, "graphics driver " + id + " (" + library + ")");
DriverSetupLog.write(context, "install.ready driver=" + id + " library=" + library);
return id;
@@ -282,6 +308,12 @@ public final class TurnipDriver {
}
}
if (chosen != null && !chosen.isEmpty()) {
if (SessionPrefs.GPU_DRIVERS_AUTO.equals(SessionPrefs.INSTANCE.gpuDriverMode(context))
&& SessionPrefs.INSTANCE.gpuAutoInstalled(context).contains(chosen)
&& gpuDetector.get().getFamily() == GpuInfo.Family.A7XX_LOW) {
Log.i(TAG, "Auto-selected display driver does not cover Adreno 710/720/722; leaving the display driver to the system");
return null;
}
if (BUNDLED.contains(chosen)) {
Log.i(TAG, "driver pinned by the user: " + chosen);
return chosen;
@@ -318,6 +350,10 @@ public final class TurnipDriver {
Log.i(TAG, "not an Adreno GPU; leaving the display driver to the system");
return null;
}
if (gpu.getFamily() == GpuInfo.Family.A7XX_LOW) {
Log.i(TAG, "no bundled display driver covers Adreno 710/720/722; leaving the display driver to the system");
return null;
}
int model = gpu.getModel();
Log.i(TAG, "gpu model: " + (model == 0 ? "unknown" : model));
return chooseByModel(model, android.os.Build.VERSION.SDK_INT);
@@ -7,15 +7,21 @@ internal object DroidDeckHudConfig {
val DEFAULTS: Map<String, String> = linkedMapOf(
"hudSize" to "minimal", "hudLocked" to "1", "hudSnap" to "1", "hudScale" to "100", "hudDock" to "none", "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", "showLow1" to "1", "showLow01" to "1", "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",
"showGpuModel" to "1", "showGPULoad" to "1", "showCPUUsage" to "1", "showCPULoad" to "1",
"showPerCore" to "1", "showTemp" to "1", "showBatteryTemp" to "1", "showGpuTemp" to "0",
"showVram" to "1", "showRAM" to "1", "showSwap" to "1", "showBattery" to "0", "showBatteryTime" to "0", "showPower" to "1",
"showFPS" to "1", "showFPSGraph" to "1", "fpsDecimal" to "1",
"showLatency" to "1", "showAvg" to "1", "showLow1" to "1", "showLow01" to "1", "showLow001" to "1",
"showEngine" to "1", "showRenderer" to "1",
"showDisplay" to "1", "showHdr" to "1", "showNet" to "1", "showResolution" to "1",
"showProton" to "1", "showSession" to "1", "showClock" to "1", "hudOrder" to "",
"tempUnit" to "c", "tempBands" to "1", "tempAuto" to "1", "tempRedCpu" to "90", "tempRedGpu" to "90", "tempRedBat" to "48",
)
private val TWINS = mapOf("showCPUUsage" to "showCPULoad", "showTemp" to "showBatteryTemp", "showEngine" to "showRenderer")
private val NOT_READINGS = setOf("showCPULoad", "showRenderer", "fpsDecimal")
/** Orders saved before the GPU switch was named after the alias the HUD actually reads. */
private val RENAMED = mapOf("showGPU" to "showGPULoad")
fun load(context: Context): MutableMap<String, String> {
val values = LinkedHashMap(DEFAULTS)
@@ -36,7 +42,31 @@ internal object DroidDeckHudConfig {
val values = load(context)
if (key !in DEFAULTS) return values
values[key] = value
TWINS[key]?.let { values[it] = value }
SessionPrefs.setDroidDeckHudConfig(context, encode(values))
return values
}
/** Writes several switches and the row order in one go, so the HUD is rebuilt once. */
fun choose(context: Context, switches: Map<String, Boolean>, order: List<String>): Map<String, String> {
val values = load(context)
for ((key, on) in switches) if (key in DEFAULTS) {
values[key] = flag(on)
}
val size = DroidDeckHudSize.from(values["hudSize"])
val groups = sizeOrders(values).toMutableMap()
if (groups.isEmpty()) {
val legacy = legacyOrder(values)
if (legacy.isNotEmpty()) for (each in DroidDeckHudSize.values()) groups[each] = legacy.filter { it in each.rows }
}
groups[size] = order.filter { it in ORDER }
values["hudOrder"] = encodeOrders(groups)
SessionPrefs.setDroidDeckHudConfig(context, encode(values))
return values
}
fun clearOrder(context: Context): Map<String, String> {
val values = load(context)
values["hudOrder"] = ""
SessionPrefs.setDroidDeckHudConfig(context, encode(values))
return values
}
@@ -46,5 +76,37 @@ internal object DroidDeckHudConfig {
return DEFAULTS
}
/** Every metric switch, in the order the HUD lists them before the user moves any. Derived from
* [DEFAULTS], so a switch added there shows up here without a second list to keep in step. */
val ORDER: List<String> = DEFAULTS.keys.filter { it.startsWith("show") && it !in NOT_READINGS }
/** Only the rows the user moved for [size], in the order they left them. */
fun storedOrder(values: Map<String, String>, size: DroidDeckHudSize): List<String> =
sizeOrders(values)[size] ?: legacyOrder(values)
/** Orders saved before each size kept its own: one list, applied to every size. */
private fun legacyOrder(values: Map<String, String>): List<String> {
val raw = values["hudOrder"].orEmpty()
if (raw.isBlank() || raw.contains(':')) return emptyList()
return raw.split('|').map { RENAMED[it] ?: it }.filter { it in ORDER }
}
private fun sizeOrders(values: Map<String, String>): Map<DroidDeckHudSize, List<String>> {
val raw = values["hudOrder"].orEmpty()
if (raw.isBlank()) return emptyMap()
val groups = LinkedHashMap<DroidDeckHudSize, List<String>>()
for (group in raw.split(';')) {
val colon = group.indexOf(':')
if (colon <= 0) continue
val size = DroidDeckHudSize.values().firstOrNull { it.token == group.substring(0, colon) } ?: continue
groups[size] = group.substring(colon + 1).split('|').map { RENAMED[it] ?: it }.filter { it in ORDER }
}
return groups
}
private fun encodeOrders(groups: Map<DroidDeckHudSize, List<String>>): String =
groups.entries.filter { it.value.isNotEmpty() }
.joinToString(";") { "${it.key.token}:${it.value.joinToString("|")}" }
private fun flag(on: Boolean) = if (on) "1" else "0"
}
@@ -13,6 +13,27 @@
package com.droiddeck.launcher.hud
/**
* Size modes for the DroidDeck 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.
*/
/** The text sizes and spacing a [DroidDeckHudSize] lays its rows out with, in sp. */
data class DroidDeckHudStyle(
val row: Float,
val unit: Float,
val pad: Float,
val lineGap: Float,
val labelGap: Float,
val key: Float = 0f,
val sub: Float = 0f,
val foot: Float = 0f,
val band: Float = 0f,
val gutter: Float = 0f,
val tileGap: Float = 0f,
val innerPad: Float = 0f,
)
enum class DroidDeckHudSize(val token: String, val label: String) {
FULL("full", "Full"),
TILES("tiles", "Tiles"),
@@ -26,27 +47,73 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
return all[(ordinal + 1) % all.size]
}
fun supportedChips(): Set<String> = when (this) {
MINIMAL -> MINIMAL_CHIPS
PILL -> PILL_CHIPS
FULL, TILES, STRIP -> STANDARD_CHIPS
MEGA -> MEGA_CHIPS
}
/**
* The rows this size draws, in the order it draws them before the user moves any. This is the single
* source of truth for both surfaces: [DroidDeckHudView] draws exactly these and the settings screen
* offers exactly these. A switch outside the set is ignored by the size, so the two cannot drift.
*/
val rows: List<String> get() = ROWS.getValue(this)
/** This size's rows: the ones the user moved first, then the rest in the order [rows] lists them. */
fun rowsIn(stored: List<String>): List<String> =
stored.filter { it in rows } + rows.filter { it !in stored }
/**
* The numbers each size sets its text in, in sp. One table so a size's scale can be read (and changed)
* in one place instead of hunting the `sp(...)` literals scattered through its builder.
*/
val style: DroidDeckHudStyle get() = STYLE.getValue(this)
companion object {
fun from(token: String?): DroidDeckHudSize =
values().firstOrNull { it.token.equals(token, ignoreCase = true) } ?: FULL
val MINIMAL_CHIPS = setOf("FPS", "FPS graph", "1% low", "0.1% low", "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", "1% low", "0.1% low", "0.01% low", "FPS .1", "Clock",
private val EXTRAS = setOf("showClock")
val ROWS: Map<DroidDeckHudSize, List<String>> = mapOf(
FULL to listOf(
"showFPS", "showFPSGraph", "showGpuModel", "showDisplay", "showHdr", "showGPULoad", "showGpuTemp",
"showCPUUsage", "showTemp", "showVram", "showRAM", "showBattery", "showBatteryTemp", "showBatteryTime",
"showPower", "showLatency", "showAvg", "showLow1", "showLow01", "showLow001",
),
TILES to listOf(
"showFPS", "showFPSGraph", "showLatency", "showGPULoad", "showGpuTemp", "showCPUUsage", "showTemp",
"showVram", "showRAM", "showEngine", "showDisplay", "showHdr", "showAvg", "showLow1",
"showLow01", "showLow001", "showGpuModel", "showBattery", "showBatteryTemp", "showBatteryTime", "showPower",
),
PILL to listOf(
"showFPS", "showFPSGraph", "showGpuModel", "showGPULoad", "showGpuTemp", "showCPUUsage", "showTemp",
"showRAM", "showBattery", "showBatteryTemp", "showBatteryTime", "showPower", "showLatency", "showDisplay",
"showVram", "showHdr",
),
MINIMAL to listOf(
"showFPS", "showBatteryTime", "showFPSGraph", "showLow1", "showLow01", "showLow001", "showAvg", "showLatency",
"showEngine", "showDisplay", "showHdr",
),
MEGA to DroidDeckHudConfig.ORDER.filter { it !in EXTRAS },
STRIP to listOf(
"showFPS", "showFPSGraph", "showLow1", "showLow01", "showLow001", "showGPULoad", "showGpuTemp",
"showCPUUsage", "showTemp", "showVram", "showRAM", "showBattery", "showBatteryTemp", "showBatteryTime",
"showPower", "showDisplay", "showHdr", "showGpuModel",
),
)
val MEGA_ONLY = setOf(
"Per-core", "Swap", "Network", "Resolution", "Proton", "Wrapper", "DX ver", "Session",
val STYLE: Map<DroidDeckHudSize, DroidDeckHudStyle> = mapOf(
FULL to DroidDeckHudStyle(row = 12f, unit = 12f * 0.62f, pad = 10f, lineGap = 4f, labelGap = 8f),
TILES to DroidDeckHudStyle(row = 18f, unit = 11f, pad = 9f, lineGap = 4f, labelGap = 8f,
key = 10f, sub = 10f, tileGap = 6f, innerPad = 8f),
PILL to DroidDeckHudStyle(row = 30f, unit = 30f * 0.36f, pad = 10f, lineGap = 3f, labelGap = 12f,
sub = 11.5f),
MINIMAL to DroidDeckHudStyle(row = 34f, unit = 34f * 0.32f, pad = 10f, lineGap = 4f, labelGap = 8f,
sub = 11.5f, foot = 9.5f),
MEGA to DroidDeckHudStyle(row = 11.5f, unit = 11.5f * 0.62f, pad = 10f, lineGap = 3.5f, labelGap = 7f,
band = 9.5f, gutter = 16f),
STRIP to DroidDeckHudStyle(row = 11.5f, unit = 11.5f * 0.8f, pad = 10f, lineGap = 0f, labelGap = 13f),
)
val MEGA_CHIPS = STANDARD_CHIPS + MEGA_ONLY
fun rowsFor(size: DroidDeckHudSize, values: Map<String, String>): List<String> =
size.rowsIn(DroidDeckHudConfig.storedOrder(values, size))
}
}
@@ -69,6 +69,7 @@ class DroidDeckHudView(context: Context) : View(context) {
private val density = resources.displayMetrics.density
private var cfg: KeyValueSet = KeyValueSet()
private var size = DroidDeckHudSize.FULL
private var scale = 1f
private var bgOpacity = 0.8f
@@ -95,13 +96,16 @@ class DroidDeckHudView(context: Context) : View(context) {
private var showLow001 = true
private var fpsDecimal = true
private var showClockTime = true
private var showLatency = true
private var showAvg = true
private var showDisplay = true
private var showHdr = true
private var storedOrder: List<String> = emptyList()
private var showPerCore = true
private var showSwap = true
private var showNet = true
private var showResolution = true
private var showProton = true
private var showWrapper = true
private var showDxVer = true
private var showSession = true
private var engineLabel = ""
@@ -177,7 +181,7 @@ class DroidDeckHudView(context: Context) : View(context) {
fun moved(dx: Float, dy: Float) = Glyph(x + dx, baseline + dy, text, color, sizePx, glow)
}
private class Span(val text: String, val color: Int, val sizePx: Float, val glow: Boolean = false)
private class HudRow(val label: Span, val vals: List<Span>, val inline: Boolean = false)
private class HudRow(val key: String, val label: Span, val vals: List<Span>, val inline: Boolean = false)
private val glyphs = ArrayList<Glyph>()
private val tileRects = ArrayList<RectF>()
private var graphRect: RectF? = null
@@ -289,41 +293,52 @@ class DroidDeckHudView(context: Context) : View(context) {
private fun cycleSize() {
size = size.next()
refreshOrder()
onSizeCycledListener?.accept(size.token)
rebuildAndInvalidate()
}
private fun refreshOrder() {
storedOrder = DroidDeckHudConfig.storedOrder(mapOf("hudOrder" to cfg.get("hudOrder", "")), size)
}
private fun switchOn(key: String): Boolean =
cfg.get(key, DroidDeckHudConfig.DEFAULTS[key] ?: "1") == "1"
fun applyConfig(configString: String?) {
if (configString.isNullOrEmpty()) return
val cfg = KeyValueSet(configString)
cfg = KeyValueSet(configString)
size = DroidDeckHudSize.from(cfg.get("hudSize", "minimal"))
showFPS = cfg.get("showFPS", "1") == "1"
showEngine = cfg.get("showEngine", "1") == "1"
showGpuModel = cfg.get("showGpuModel", "1") == "1"
showCPU = cfg.get("showCPUUsage", cfg.get("showCPULoad", "1")) == "1"
showGPU = cfg.get("showGPULoad", "1") == "1"
showCpuTemp = cfg.get("showTemp", "1") == "1"
showGpuTemp = cfg.get("showGpuTemp", "0") == "1"
showVram = cfg.get("showVram", "1") == "1"
showRAM = cfg.get("showRAM", "1") == "1"
showBattery = cfg.get("showBattery", "1") == "1"
showPower = cfg.get("showPower", "1") == "1"
showBatteryTemp = cfg.get("showBatteryTemp", "0") == "1"
showGraph = cfg.get("showFPSGraph", "0") == "1"
showLow1 = cfg.get("showLow1", "1") == "1"
showLow01 = cfg.get("showLow01", "1") == "1"
showLow001 = cfg.get("showLow001", "1") == "1"
showFPS = switchOn("showFPS")
showEngine = switchOn("showEngine")
showGpuModel = switchOn("showGpuModel")
showCPU = switchOn("showCPUUsage")
showGPU = switchOn("showGPULoad")
showCpuTemp = switchOn("showTemp")
showGpuTemp = switchOn("showGpuTemp")
showVram = switchOn("showVram")
showRAM = switchOn("showRAM")
showBattery = switchOn("showBattery")
showPower = switchOn("showPower")
showBatteryTemp = switchOn("showBatteryTemp")
showGraph = switchOn("showFPSGraph")
showLow001 = switchOn("showLow001")
fpsDecimal = cfg.get("fpsDecimal", "1") == "1"
showClockTime = cfg.get("showClock", "1") == "1"
showPerCore = cfg.get("showPerCore", "1") == "1"
showSwap = cfg.get("showSwap", "1") == "1"
showNet = cfg.get("showNet", "1") == "1"
showResolution = cfg.get("showResolution", "1") == "1"
showProton = cfg.get("showProton", "1") == "1"
showWrapper = cfg.get("showWrapper", "1") == "1"
showDxVer = cfg.get("showDxVer", "1") == "1"
showSession = cfg.get("showSession", "1") == "1"
showClockTime = switchOn("showClock")
showLatency = switchOn("showLatency")
showAvg = switchOn("showAvg")
showLow1 = switchOn("showLow1")
showLow01 = switchOn("showLow01")
showDisplay = switchOn("showDisplay")
showHdr = switchOn("showHdr")
refreshOrder()
showPerCore = switchOn("showPerCore")
showSwap = switchOn("showSwap")
showNet = switchOn("showNet")
showResolution = switchOn("showResolution")
showProton = switchOn("showProton")
showSession = switchOn("showSession")
tempDisplay = HudMetrics.TempDisplay.from(cfg)
lockController.setLocked(cfg.get("hudLocked", "1") == "1")
dock = DroidDeckHudDock.from(cfg.get("hudDock", "none"))
@@ -458,6 +473,8 @@ class DroidDeckHudView(context: Context) : View(context) {
return w
}
private fun showHdrLine(): Boolean = showHdr && hdrState != DroidDeckHudHdr.NONE
private fun placeRun(startX: Float, baseline: Float, spans: List<Span>, glow: Boolean = false): Float {
var x = startX
for (s in spans) {
@@ -539,13 +556,15 @@ class DroidDeckHudView(context: Context) : View(context) {
val s = snap
if (s == null) { contentW = 0f; contentH = 0f; return }
if (dock != DroidDeckHudDock.NONE) { buildDockTab(); return }
if (size == DroidDeckHudSize.STRIP) { buildStrip(s); return }
buildRows(s)
if (contentW <= 0f || contentH <= 0f) return
if (size == DroidDeckHudSize.PILL) addSubtleClock(sp(10f), leftAligned = true)
val pad = sp(size.style.pad)
when (size) {
DroidDeckHudSize.FULL -> { buildFull(s); intoPanel(sp(10f), header = true) }
DroidDeckHudSize.TILES -> { buildTiles(s); intoPanel(sp(9f), header = true) }
DroidDeckHudSize.PILL -> { buildPill(s); intoPanel(sp(10f), header = false) }
DroidDeckHudSize.MINIMAL -> buildMinimal(s)
DroidDeckHudSize.MEGA -> { buildMega(s); intoPanel(sp(10f), header = true) }
DroidDeckHudSize.STRIP -> buildStrip(s)
DroidDeckHudSize.MINIMAL -> intoPanel(pad, header = true, halfRound = true)
DroidDeckHudSize.PILL -> intoPanel(pad, header = false)
else -> intoPanel(pad, header = true)
}
}
@@ -615,7 +634,12 @@ class DroidDeckHudView(context: Context) : View(context) {
return Pair(dDividerTop + max(1f, density), x)
}
private fun intoPanel(pad: Float, header: Boolean) {
/**
* Moves a size's content, laid out from [pad] at the origin, into the panel: under the header, or after
* the logo chip on the Pill. Lines that start on the content's left edge are lined up by their ink, so
* the logo, labels and numbers share one edge.
*/
private fun intoPanel(pad: Float, header: Boolean, halfRound: Boolean = !header) {
if (contentW <= 0f || contentH <= 0f) return
for (i in glyphs.indices) {
val g = glyphs[i]
@@ -641,7 +665,7 @@ class DroidDeckHudView(context: Context) : View(context) {
val panel = RectF(panelLeft(), panelInset(), max(contentW - pad + dx, headerRight) + sp(18f),
contentH - pad + dy + sp(10f) + stroke)
chipRect?.let { it.offsetTo(it.left, panel.centerY() - it.height() / 2f) }
finishPanel(panel, halfRound = !header)
finishPanel(panel, halfRound = halfRound)
}
private fun finishPanel(panel: RectF, halfRound: Boolean) {
@@ -712,316 +736,188 @@ class DroidDeckHudView(context: Context) : View(context) {
contentW = max(contentW, pad + w + pad)
}
private fun hasGpuStats(s: HudMetrics.Snapshot): Boolean =
s.gpuPercent != null || s.gpuTempC != null || s.gpuClockMhz != null
private fun buildFull(s: HudMetrics.Snapshot) {
val rowPx = sp(12f); val unitPx = rowPx * 0.62f
val pad = sp(10f); val lineGap = sp(4f); val lvGap = sp(8f)
val rows = ArrayList<HudRow>()
if (showGpuModel && gpuNameText().isNotBlank())
rows.add(HudRow(Span("GPU", colGpu, rowPx), gpuModelSpans(rowPx, colValue)))
if (displayServer.isNotBlank())
rows.add(HudRow(Span("DISP", colDisp, rowPx), listOf(Span(displayServer, colValue, rowPx))))
if (hdrState != DroidDeckHudHdr.NONE)
rows.add(HudRow(Span("HDR", colHdr, rowPx), hdrValue(rowPx)))
if (showGPU && hasGpuStats(s)) {
val v = ArrayList<Span>()
v += numUnit(s.gpuPercent?.toString(), "%", rowPx, unitPx)
if (showGpuTemp) tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx)
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
v += gap(unitPx); v += numUnit(s.gpuClockMhz?.toString(), "MHz", rowPx, unitPx)
rows.add(HudRow(Span("GPU", colGpu, rowPx), v))
}
if (showCPU) {
val v = ArrayList<Span>()
v += numUnit(s.cpuPercent?.toString(), "%", rowPx, unitPx)
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
if (showCpuTemp) tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx)
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
rows.add(HudRow(Span("CPU", colCpu, rowPx), v))
}
if (showVram && s.vramText() != null)
rows.add(HudRow(Span("VRAM", colVram, rowPx), valueUnit(s.vramText()!!, rowPx, unitPx)))
if (showRAM) {
val v = ArrayList<Span>()
v += valueUnit(s.ramUsedText(), rowPx, unitPx)
v += gap(unitPx); v += numUnit(s.ramPercent.roundToInt().toString(), "%", rowPx, unitPx)
rows.add(HudRow(Span("RAM", colRam, rowPx), v))
}
if (showBattery || showPower || showBatteryTemp) {
val v = ArrayList<Span>(); var any = false
if (showBattery && s.battery.percent != null) { v += numUnit(s.battery.percent.toString(), "%", rowPx, unitPx); any = true }
if (showBatteryTemp) tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, rowPx, unitPx)
.let { if (it.isNotEmpty()) { if (any) v += gap(unitPx); v += it; any = true } }
if (showPower && s.battery.watts > 0f) { if (any) v += gap(unitPx); v += numUnit(fmt1(s.battery.watts), "W", rowPx, unitPx); any = true }
if (any) rows.add(HudRow(Span("BAT", colBat, rowPx), v))
}
if (showFPS) {
val v = ArrayList<Span>()
v += glowing(numUnit(fpsText(fpsNow), "FPS", rowPx, unitPx))
v += gap(unitPx); v += numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", rowPx, unitPx)
rows.add(HudRow(Span(apiLabel(), colFps, rowPx), v))
rows.add(HudRow(Span("AVG", colLo, rowPx), numUnit(fmt1(fpsAvg), "FPS", rowPx, unitPx)))
if (showLow1)
rows.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
if (showLow01)
rows.add(HudRow(Span("0.1%", colLo, rowPx), numUnit(lowText(lows.low01Fps), "FPS", rowPx, unitPx)))
if (showLow001)
rows.add(HudRow(Span("0.01%", colLo, rowPx), numUnit(lowText(lows.low001Fps), "FPS", rowPx, unitPx)))
}
var labelCol = 0f
for (r in rows) if (!r.inline) labelCol = max(labelCol, measure(r.label.text, rowPx))
val h = lineH(rowPx); val asc = ascent(rowPx)
var y = pad; var maxRight = pad
for (r in rows) {
val baseline = y - asc
placeRun(pad, baseline, listOf(r.label))
val valX = if (r.inline) pad + measure(r.label.text, rowPx) + lvGap
else pad + labelCol + lvGap
val end = placeRun(valX, baseline, r.vals)
maxRight = max(maxRight, end)
y += h + lineGap
}
if (showFPS && showGraph) {
val ftPx = unitPx * 1.15f
val baseline = y - asc
placeRun(pad, baseline, listOf(Span("Frametime", colFps, ftPx)))
val stat = "min:${fmt1(graphMinMs)} max:${fmt1(graphMaxMs)}"
val statX = pad + max(labelCol, measure("Frametime", ftPx)) + lvGap
val end = placeRun(statX, baseline, listOf(Span(stat, colDim, unitPx)))
maxRight = max(maxRight, end)
y += h + lineGap
val gh = sp(22f)
val right = max(maxRight, pad + sp(160f))
graphRect = RectF(pad, y, right, y + gh)
maxRight = max(maxRight, right)
y += gh
}
contentW = maxRight + pad
contentH = y + pad
addSubtleClock(pad)
private fun switchLabel(key: String): Pair<String, Int> = when (key) {
"showGpuModel" -> "MODEL" to colGpu
"showGPULoad" -> "GPU" to colGpu
"showGpuTemp" -> "GPU.T" to colGpu
"showCPUUsage" -> "CPU" to colCpu
"showTemp" -> "CPU.T" to colCpu
"showBatteryTemp" -> "BAT.T" to colBat
"showPower" -> "PWR" to colBat
"showBattery" -> "BAT" to colBat
"showBatteryTime" -> "BAT TIME" to colBat
"showVram" -> "VRAM" to colVram
"showRAM" -> "RAM" to colRam
"showSwap" -> "SWP" to colRam
"showNet" -> "NET" to colFps
"showPerCore" -> "CORE" to colCpu
"showFPS" -> "FPS" to colFps
"showLatency" -> "MS" to colDim
"showAvg" -> "AVG" to colLo
"showLow1" -> "1%" to colLo
"showLow01" -> "0.1%" to colLo
"showLow001" -> "0.01%" to colLo
"showEngine" -> "API" to colFps
"showDisplay" -> "DISP" to colDisp
"showHdr" -> "HDR" to colHdr
"showResolution" -> "RES" to colDim
"showProton" -> "PROTON" to colVram
"showSession" -> "TIME" to colDim
else -> key.removePrefix("show") to colDim
}
private fun buildTiles(s: HudMetrics.Snapshot) {
val keyPx = sp(10f); val valPx = sp(18f); val subPx = sp(10f); val unitPx = sp(11f)
val pad = sp(9f); val innerPad = sp(8f); val tileGap = sp(6f); val lineGap = sp(4f)
class Tile(val key: String, val keyColor: Int, val value: List<Span>, val sub: String?, val wide: Boolean)
val tiles = ArrayList<Tile>()
if (showFPS) tiles.add(Tile("FPS", colFps, listOf(Span(fpsText(fpsNow), colValue, valPx, glow = true)),
"${fmt1(fpsAvg)} avg" + (if (showLow1) " · ${lowText(lows.low1Fps) ?: "—"} 1%" else ""), false))
if (showFPS) tiles.add(Tile("FRAME", colDim, numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", valPx, unitPx),
"${fmt1(graphMinMs)} – ${fmt1(graphMaxMs)}", false))
if (showGPU && hasGpuStats(s)) tiles.add(Tile("GPU", colGpu, numUnit(s.gpuPercent?.toString(), "%", valPx, unitPx),
if (showGpuTemp && s.gpuTempC != null) HudMetrics.formatTemp(s.gpuTempC.toFloat(), tempDisplay, false)
else s.gpuClockMhz?.let { "${it}MHz" }, false))
if (showCPU) tiles.add(Tile("CPU", colCpu, numUnit(s.cpuPercent?.toString(), "%", valPx, unitPx),
listOfNotNull(s.cpuClockMhz?.let { "${it}MHz" },
if (showCpuTemp) s.cpuTempC?.let { HudMetrics.formatTemp(it.toFloat(), tempDisplay, false) } else null)
.joinToString(" · ").ifBlank { null }, false))
if (showVram && s.vramText() != null) tiles.add(Tile("VRAM", colVram, valueUnit(s.vramText()!!, valPx, unitPx), null, false))
if (showRAM) tiles.add(Tile("RAM", colRam, numUnit(s.ramPercent.roundToInt().toString(), "%", valPx, unitPx),
"${s.ramUsedText()} / ${s.ramTotalText()}", false))
if (showEngine && engineLabel.isNotBlank())
tiles.add(Tile("API", colFps, listOf(Span(engineLabel, colValue, valPx)),
dxVersion().ifBlank { null }, false))
if (displayServer.isNotBlank())
tiles.add(Tile("DISPLAY", colDisp, listOf(Span(displayServer, colValue, valPx)),
if (hdrState != DroidDeckHudHdr.NONE) hdrText() else null, false))
if (showGpuModel && gpuNameText().isNotBlank())
tiles.add(Tile("GPU", colGpu, gpuModelSpans(valPx, colValue), null, true))
if (showBattery || showPower || showBatteryTemp) {
val parts = ArrayList<Span>(); var any = false
if (showBattery && s.battery.percent != null) { parts += numUnit(s.battery.percent.toString(), "%", valPx, unitPx); any = true }
if (showBatteryTemp && s.battery.tempC != null) { if (any) parts += Span(" · ", colDim, subPx); parts += tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, valPx, unitPx); any = true }
if (showPower && s.battery.watts > 0f) { if (any) parts += Span(" · ", colDim, subPx); parts += numUnit(fmt1(s.battery.watts), "W", valPx, unitPx); any = true }
if (any) tiles.add(Tile("BAT", colBat, parts, null, true))
private fun reading(key: String, s: HudMetrics.Snapshot, labelPx: Float, valuePx: Float, unitPx: Float): HudRow {
if (key == "showFPSGraph") return HudRow(key, Span("", colDim, 0f), emptyList())
val (label, color) = switchLabel(key)
val values: List<Span> = when (key) {
"showGpuModel" -> if (gpuNameText().isBlank()) numUnit(null, "", valuePx, unitPx)
else gpuModelSpans(valuePx, colValue)
"showGPULoad" -> numUnit(s.gpuPercent?.toString(), "%", valuePx, unitPx)
"showGpuTemp" -> tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, valuePx, unitPx)
"showCPUUsage" -> numUnit(s.cpuPercent?.toString(), "%", valuePx, unitPx)
"showTemp" -> tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, valuePx, unitPx)
"showBatteryTemp" -> tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, valuePx, unitPx)
"showPower" -> numUnit(if (s.battery.watts > 0f) fmt1(s.battery.watts) else null, "W", valuePx, unitPx)
"showBattery" -> numUnit(s.battery.percent?.toString(), "%", valuePx, unitPx)
"showBatteryTime" -> valueUnit(s.battery.runtimeText ?: "—", valuePx, unitPx)
"showVram" -> valueUnit(s.vramText() ?: "—", valuePx, unitPx)
"showRAM" -> numUnit(s.ramPercent.roundToInt().toString(), "%", valuePx, unitPx)
"showSwap" -> valueUnit(s.swapUsedText() ?: "—", valuePx, unitPx)
"showNet" -> listOf(
Span("↓", colDim, unitPx), Span(((s.netDownBps ?: 0L) / 1024L).toString(), colValue, valuePx),
Span(" ↑", colDim, unitPx), Span(((s.netUpBps ?: 0L) / 1024L).toString(), colValue, valuePx),
)
"showPerCore" -> listOf(Span(s.perCorePercent.size.toString(), colValue, valuePx))
"showFPS" -> glowing(numUnit(fpsText(fpsNow), "", valuePx, unitPx))
"showLatency" -> numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", valuePx, unitPx)
"showAvg" -> numUnit(fmt1(fpsAvg), "", valuePx, unitPx)
"showLow1" -> numUnit(lowText(lows.low1Fps), "", valuePx, unitPx)
"showLow01" -> numUnit(lowText(lows.low01Fps), "", valuePx, unitPx)
"showLow001" -> numUnit(lowText(lows.low001Fps), "", valuePx, unitPx)
"showEngine" -> listOf(Span(engineLabel.ifBlank { "—" }, colValue, valuePx))
"showDisplay" -> listOf(Span(displayServer.ifBlank { "—" }, colDisp, valuePx))
"showHdr" -> if (showHdrLine()) hdrValue(valuePx) else listOf(Span("off", colDim, valuePx))
"showResolution" -> listOf(Span(resolutionString(), colValue, valuePx))
"showProton" -> listOf(Span(wineVersion.ifBlank { "—" }, colVram, valuePx))
"showSession" -> listOf(Span(elapsedString(), colValue, valuePx))
else -> listOf(Span("—", colDim, valuePx))
}
if (tiles.isEmpty()) { contentW = 0f; contentH = 0f; return }
val keyH = lineH(keyPx); val valH = lineH(valPx); val subH = lineH(subPx)
fun tileW(t: Tile) = max(max(measure(t.key, keyPx), runWidth(t.value)),
t.sub?.let { measure(it, subPx) } ?: 0f) + innerPad * 2
var normalW = 0f
for (t in tiles) if (!t.wide) normalW = max(normalW, tileW(t))
if (normalW == 0f) for (t in tiles) normalW = max(normalW, tileW(t) / 2f)
val tileH = innerPad * 2 + keyH + lineGap + valH + lineGap + subH
val fullW = normalW * 2 + tileGap
var x = pad; var y = pad; var col = 0
fun place(t: Tile, tx: Float, ty: Float, tw: Float) {
tileRects.add(RectF(tx, ty, tx + tw, ty + tileH))
var by = ty + innerPad - ascent(keyPx)
placeRun(tx + innerPad, by, listOf(Span(t.key, t.keyColor, keyPx)))
by = ty + innerPad + keyH + lineGap - ascent(valPx)
placeRun(tx + innerPad, by, t.value)
if (t.sub != null) {
by = ty + innerPad + keyH + lineGap + valH + lineGap - ascent(subPx)
placeRun(tx + innerPad, by, listOf(Span(t.sub, colDim, subPx)))
}
}
for (t in tiles) {
if (t.wide) {
if (col != 0) { y += tileH + tileGap; col = 0; x = pad }
place(t, pad, y, fullW)
y += tileH + tileGap; col = 0; x = pad
} else {
place(t, x, y, normalW)
col++; x += normalW + tileGap
if (col == 2) { col = 0; x = pad; y += tileH + tileGap }
}
}
if (col != 0) y += tileH + tileGap
if (showFPS && showGraph) {
graphRect = RectF(pad, y, pad + fullW, y + sp(22f))
y += sp(22f) + tileGap
}
contentW = pad + fullW + pad
contentH = y + (pad - tileGap)
addSubtleClock(pad)
return HudRow(key, Span(label, color, labelPx), values.ifEmpty { listOf(Span("—", colDim, valuePx)) })
}
private fun buildPill(s: HudMetrics.Snapshot) {
val bigPx = sp(30f); val bigUnitPx = bigPx * 0.36f; val stkPx = sp(11.5f)
val pad = sp(10f); val midGap = sp(12f); val stkLineGap = sp(3f)
private fun buildRows(s: HudMetrics.Snapshot) {
val st = size.style
val pad = sp(st.pad); val lineGap = sp(st.lineGap); val lvGap = sp(st.labelGap)
val gutter = sp(if (st.gutter > 0f) st.gutter else 14f)
val unitPx = sp(if (st.unit > 0f) st.unit else st.row * 0.62f)
val basePx = sp(if (st.sub > 0f) st.sub else st.row)
val left = ArrayList<Span>()
val generating = differs(fpsNow)
val fpsPx = if (generating) bigPx * 0.55f else bigPx
left += Span(fpsText(fpsNow), colValue, fpsPx, glow = true)
left += Span("fps", colDim, if (generating) bigUnitPx * 0.8f else bigUnitPx)
val stack = ArrayList<List<Span>>()
val gpuName = if (showGpuModel && gpuNameText().isNotBlank()) gpuModelSpans(stkPx, colDim, compact = true) else null
run {
val l = ArrayList<Span>()
if (showGPU && s.gpuPercent != null) { l += Span("GPU ${s.gpuPercent}%", colGpu, stkPx) }
if (showCPU) { if (l.isNotEmpty()) l += Span(" · ", colDim, stkPx); l += Span("CPU ${s.cpuPercent ?: "—"}%", colCpu, stkPx) }
if (l.isNotEmpty()) stack.add(l)
val keys = size.rowsIn(storedOrder).filter { switchOn(it) }
if (keys.isEmpty()) { contentW = 0f; contentH = 0f; return }
val hero = (size == DroidDeckHudSize.PILL || size == DroidDeckHudSize.MINIMAL) && keys.firstOrNull() == "showFPS"
val tiles = size == DroidDeckHudSize.TILES
val bigPx = sp(st.row); val bigUnitPx = sp(st.unit)
val heroSpans = listOf(
Span(fpsText(fpsNow), colValue, bigPx, glow = true),
Span("fps", colDim, bigUnitPx),
)
val listed = keys.filter { !hero || it != "showFPS" }.flatMap { key ->
val labelPx = if (tiles) sp(st.key) else basePx
val valuePx = if (tiles) sp(st.row) else basePx
if (key == "showPerCore" && size == DroidDeckHudSize.MEGA)
perCoreRows(s, labelPx, valuePx, unitPx)
else listOf(reading(key, s, labelPx, valuePx, unitPx))
}
if (showRAM) stack.add(listOf(Span("RAM ${s.ramPercent.roundToInt()}%", colRam, stkPx)))
if (showBattery || showPower || showBatteryTemp) {
val l = ArrayList<Span>()
fun part(spans: List<Span>) {
l += if (l.isEmpty()) Span("BAT ", colBat, stkPx) else Span(" · ", colDim, stkPx)
l += spans
val maxCols = if (size == DroidDeckHudSize.MEGA) 3 else 2
val cols = when {
listed.size >= 9 -> maxCols
listed.size >= 4 -> minOf(2, maxCols)
else -> 1
}
if (tiles) {
val innerPad = sp(st.innerPad); val tileGap = sp(st.tileGap)
val keyH = lineH(sp(st.key)); val valH = lineH(sp(st.row))
val cellW = listed.maxOf { max(measure(it.label.text, it.label.sizePx), runWidth(it.vals)) } + innerPad * 2f
val graphMin = if (listed.any { it.key == "showFPSGraph" }) sp(GRAPH_MIN_WIDTH_SP) else 0f
val cellMin = graphMin + innerPad * 2f
val cellH = innerPad * 2f + keyH + lineGap + valH
for ((i, r) in listed.withIndex()) {
val x = pad + (i % cols) * (cellW + tileGap)
val y = pad + (i / cols) * (cellH + tileGap)
tileRects.add(RectF(x, y, x + cellW, y + cellH))
if (r.key == "showFPSGraph") {
graphRect = RectF(x + innerPad, y + innerPad, x + max(cellW, cellMin) - innerPad, y + cellH - innerPad)
continue
}
placeRun(x + innerPad, y + innerPad - ascent(r.label.sizePx), listOf(r.label))
placeRun(x + innerPad, y + innerPad + keyH + lineGap - ascent(sp(st.row)), r.vals)
}
if (showBattery && s.battery.percent != null) part(listOf(Span("${s.battery.percent}%", colBat, stkPx)))
if (showBatteryTemp && s.battery.tempC != null)
part(tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, stkPx, stkPx * 0.62f))
if (showPower && s.battery.watts > 0f) part(listOf(Span("${fmt1(s.battery.watts)}W", colDim, stkPx)))
if (l.isNotEmpty()) stack.add(l)
}
run {
val l = ArrayList<Span>()
l += Span("${fmt1(1000f / max(fpsNow, 1f))}ms", colDim, stkPx)
if (displayServer.isNotBlank()) { l += Span(" · ", colDim, stkPx); l += Span(displayServer, colDisp, stkPx) }
if (showVram && s.vramText() != null) { l += Span(" · ", colDim, stkPx); l += Span("${s.vramText()} vram", colDim, stkPx) }
stack.add(l)
}
if (hdrState != DroidDeckHudHdr.NONE) stack.add(hdrLine(stkPx))
var statsW = 0f
for (l in stack) statsW = max(statsW, runWidth(l))
val nameOnTop = gpuName != null && runWidth(gpuName) > statsW
if (gpuName != null && !nameOnTop) stack.add(0, gpuName)
val apiStr = apiLabel()
val hasApi = apiStr != "FPS"
val apiH = if (hasApi) lineH(stkPx) else 0f
val apiGap = if (hasApi) stkLineGap else 0f
val leftW = runWidth(left); val leftH = lineH(bigPx)
val apiW = if (hasApi) measure(apiStr, stkPx) else 0f
val leftBlockW = max(leftW, apiW)
val leftColH = apiH + apiGap + leftH
val stkH = lineH(stkPx)
var stackW = 0f
for (l in stack) stackW = max(stackW, runWidth(l))
val stackTotalH = stack.size * stkH + (stack.size - 1).coerceAtLeast(0) * stkLineGap
val innerH = max(leftColH, stackTotalH)
val topLineH = if (nameOnTop) stkH + stkLineGap else 0f
contentW = pad + leftBlockW + midGap + stackW + pad
contentH = pad + topLineH + innerH + pad
var ly = pad + topLineH + (innerH - leftColH) / 2f
if (hasApi) {
placeRun(pad, ly - ascent(stkPx), listOf(Span(apiStr, colFps, stkPx)))
ly += apiH + apiGap
}
placeRun(pad, ly - ascent(bigPx), left)
var sy = pad + topLineH + (innerH - stackTotalH) / 2f
for (l in stack) {
placeRun(pad + leftBlockW + midGap, sy - ascent(stkPx), l)
sy += stkH + stkLineGap
}
addSubtleClock(pad, leftAligned = true)
if (nameOnTop && gpuName != null) {
val end = placeRun(pad, pad - ascent(stkPx), gpuName)
contentW = max(contentW, end + pad)
val lines = (listed.size + cols - 1) / cols
contentW = pad + cols * (cellW + tileGap) - tileGap + pad
contentH = pad + lines * (cellH + tileGap) - tileGap + pad
} else {
val columns = (0 until cols).map { c -> listed.filterIndexed { i, _ -> i % cols == c } }
val labelW = columns.map { col -> col.maxOfOrNull { measure(it.label.text, it.label.sizePx) } ?: 0f }
val colW = columns.mapIndexed { c, col ->
val body = if (col.isEmpty()) 0f else labelW[c] + lvGap + (col.maxOfOrNull { runWidth(it.vals) } ?: 0f)
val graph = if (col.any { it.key == "showFPSGraph" }) sp(GRAPH_MIN_WIDTH_SP) + labelW[c] + lvGap else 0f
max(body, graph)
}
val gaps = (0 until cols).count { columns[it].isNotEmpty() }.coerceAtLeast(1) - 1
val bodyW = colW.sum() + gutter * gaps
var bodyH = 0f
for (col in columns) {
var y = 0f
for (r in col) y += rowHeight(r) + lineGap
if (col.isNotEmpty()) bodyH = max(bodyH, y - lineGap)
}
val heroW = if (hero) runWidth(heroSpans) else 0f
val heroH = if (hero) lineH(bigPx) else 0f
val x0 = pad + if (hero && listed.isNotEmpty()) heroW + gutter else 0f
val top = pad + (max(bodyH, heroH) - bodyH) / 2f
var x = x0
for (c in 0 until cols) {
if (columns[c].isEmpty()) continue
var y = top
for (r in columns[c]) {
if (r.key == "showFPSGraph") {
val left = x + labelW[c] + lvGap
graphRect = RectF(left, y, max(x + colW[c], left + sp(GRAPH_MIN_WIDTH_SP)), y + sp(GRAPH_HEIGHT_SP))
y += sp(GRAPH_HEIGHT_SP) + lineGap
continue
}
val px = maxOf(r.label.sizePx, r.vals.maxOfOrNull { it.sizePx } ?: 0f)
val baseline = y - ascent(px)
placeRun(x, baseline, listOf(r.label))
placeRun(x + labelW[c] + lvGap, baseline, r.vals)
y += lineH(px) + lineGap
}
x += colW[c] + gutter
}
if (hero) {
val baseline = pad + (max(bodyH, heroH) - heroH) / 2f - ascent(bigPx)
placeRun(pad, baseline, heroSpans, glow = true)
}
contentW = max(x0 + bodyW, pad + heroW) + pad
contentH = pad + max(bodyH, heroH) + pad
}
}
private fun buildMinimal(s: HudMetrics.Snapshot) {
val bigPx = sp(34f); val bigUnitPx = bigPx * 0.32f; val subPx = sp(11.5f); val footPx = sp(9.5f)
val stroke = outlineWidth()
val left = contentLeft()
val inner = panelInset() + stroke
private fun rowHeight(r: HudRow): Float =
if (r.key == "showFPSGraph") sp(GRAPH_HEIGHT_SP)
else lineH(maxOf(r.label.sizePx, r.vals.maxOfOrNull { it.sizePx } ?: 0f))
val minGenerating = differs(fpsNow)
val big = listOf(
Span(fpsText(fpsNow), colValue, if (minGenerating) bigPx * 0.55f else bigPx),
Span("fps", colDim, if (minGenerating) bigUnitPx * 0.8f else bigUnitPx))
val sub = ArrayList<Span>()
fun low(label: String, value: Float) {
if (sub.isNotEmpty()) sub += Span(" · ", colDim, subPx)
sub += Span("$label ", colDim, subPx)
sub += Span(lowText(value) ?: "—", colFps, subPx)
private fun perCoreRows(s: HudMetrics.Snapshot, labelPx: Float, valuePx: Float, unitPx: Float): List<HudRow> {
val pct = s.perCorePercent
val clk = s.perCoreClockMhz
return (0 until max(pct.size, clk.size)).map { i ->
val vals = ArrayList<Span>()
vals += numUnit(if (i < pct.size && pct[i] >= 0) pct[i].toString() else null, "%", valuePx, unitPx)
vals += Span(" ", colDim, unitPx)
vals += numUnit(if (i < clk.size && clk[i] > 0) clk[i].toString() else null, "MHz", valuePx, unitPx)
HudRow("showPerCore", Span("C$i", colCpu, labelPx), vals)
}
if (showLow1) low("1%", lows.low1Fps)
if (showLow01) low("0.1%", lows.low01Fps)
if (showLow001) low("0.01%", lows.low001Fps)
val footerLabel = listOf(if (showEngine) engineLabel else "", displayServer)
.filter { it.isNotBlank() }.joinToString(" · ")
val hdr = if (hdrState != DroidDeckHudHdr.NONE) hdrLine(footPx) else emptyList()
val (headerBottom, headerRight) = addPanelHeader(left, inner)
val x = headerRight
val colW = maxOf(runWidth(big), runWidth(sub), x - left,
max(measure(footerLabel, footPx), runWidth(hdr)), if (showGraph) sp(120f) else 0f)
val bigBase = headerBottom + sp(8f) + capHeight(big[0].sizePx)
placeRun(left - inkLeft(big[0].text, big[0].sizePx), bigBase, big, glow = true)
var last = bigBase
if (sub.isNotEmpty()) {
last += sp(10f) + capHeight(subPx)
placeRun(left - inkLeft(sub[0].text, subPx), last, sub)
}
if (showGraph) {
val top = last + sp(9f)
graphRect = RectF(left, top, left + colW, top + sp(24f))
last = top + sp(24f)
}
if (footerLabel.isNotBlank()) {
val base = last + sp(8f) + capHeight(footPx)
glyphs.add(Glyph(left - inkLeft(footerLabel, footPx), base, footerLabel, blend(colDim), footPx))
last = base
}
if (hdr.isNotEmpty()) {
val base = last + sp(6f) + capHeight(footPx)
placeRun(left - inkLeft(hdr[0].text, footPx), base, hdr)
last = base
}
measurePaint.textSize = footPx
val panel = RectF(panelLeft(), panelInset(), left + colW + sp(34f), last + measurePaint.fontMetrics.descent + sp(9f) + stroke)
finishPanel(panel, halfRound = true)
}
private fun buildStrip(s: HudMetrics.Snapshot) {
@@ -1046,66 +942,27 @@ class DroidDeckHudView(context: Context) : View(context) {
}
val generating = differs(fpsNow)
val fps = ArrayList<Span>()
if (apiLabel() != "FPS") fps += Span("${apiLabel()} ", colDim, rowPx)
fps += Span(fpsText(fpsNow), colValue, if (generating) fpsPx * 0.8f else fpsPx, glow = true)
fps += Span("fps", colDim, unitPx)
x = placeRun(x, baseline, fps) + groupGap
if (showGraph) {
val gw = sp(72f); val gh = h * 0.55f
if (x + gw <= right) {
for (key in size.rowsIn(storedOrder)) {
if (!switchOn(key)) continue
if (key == "showFPSGraph") {
val gw = sp(72f); val gh = h * 0.55f
if (x + gw > right) break
graphRect = RectF(x, mid - gh / 2f, x + gw, mid + gh / 2f)
x += gw + groupGap
continue
}
}
val groups = ArrayList<List<Span>>()
run {
val l = ArrayList<Span>()
fun low(label: String, value: Float) {
if (l.isNotEmpty()) l += Span(" ", colDim, rowPx)
l += Span("$label ", colDim, rowPx)
l += Span(lowText(value) ?: "—", colFps, rowPx)
val spans = if (key == "showFPS") {
val fps = ArrayList<Span>()
if (apiLabel() != "FPS") fps += Span("${apiLabel()} ", colDim, rowPx)
fps += Span(fpsText(fpsNow), colValue, if (generating) fpsPx * 0.8f else fpsPx, glow = true)
fps += Span("fps", colDim, unitPx)
fps
} else {
val row = reading(key, s, rowPx, rowPx, unitPx)
listOf(row.label, Span(" ", colDim, rowPx)) + row.vals
}
if (showLow1) low("1%", lows.low1Fps)
if (showLow01) low("0.1%", lows.low01Fps)
if (showLow001) low("0.01%", lows.low001Fps)
if (l.isNotEmpty()) groups += l
}
if (showGPU || showGpuTemp) {
val l = arrayListOf(Span("GPU", colGpu, rowPx))
if (showGPU) l += Span(" ${s.gpuPercent ?: "—"}%", colGpu, rowPx)
if (showGpuTemp && s.gpuTempC != null) { l += Span(" ", colDim, rowPx); l += tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx) }
groups += l
}
if (showCPU || showCpuTemp) {
val l = arrayListOf(Span("CPU", colCpu, rowPx))
if (showCPU) l += Span(" ${s.cpuPercent ?: "—"}%", colCpu, rowPx)
if (showCpuTemp && s.cpuTempC != null) { l += Span(" ", colDim, rowPx); l += tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx) }
groups += l
}
if (showVram) s.vramText()?.let { groups += listOf(Span("VRAM $it", colVram, rowPx)) }
if (showRAM) groups += listOf(Span("RAM ${s.ramPercent.roundToInt()}%", colRam, rowPx))
if (showBattery || showPower || showBatteryTemp) {
val l = ArrayList<Span>()
fun part(spans: List<Span>) {
l += if (l.isEmpty()) Span("BAT ", colBat, rowPx) else Span(" ", colDim, rowPx)
l += spans
}
if (showBattery && s.battery.percent != null) part(listOf(Span("${s.battery.percent}%", colBat, rowPx)))
if (showBatteryTemp && s.battery.tempC != null)
part(tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, rowPx, unitPx))
if (showPower && s.battery.watts > 0f) part(listOf(Span("${fmt1(s.battery.watts)}W", colDim, rowPx)))
if (l.isNotEmpty()) groups += l
}
if (displayServer.isNotBlank()) groups += listOf(Span(displayServer, colDisp, rowPx))
if (hdrState != DroidDeckHudHdr.NONE) groups += hdrLine(rowPx)
if (showGpuModel && gpuNameText().isNotBlank()) groups += gpuModelSpans(rowPx, colDim, compact = true)
for (g in groups) {
if (x + runWidth(g) > right) break
x = placeRun(x, baseline, g) + groupGap
if (x + runWidth(spans) > right) break
x = placeRun(x, baseline, spans) + groupGap
}
stripRect = RectF(0f, 0f, w, h)
@@ -1125,168 +982,6 @@ class DroidDeckHudView(context: Context) : View(context) {
return inkRect.left.toFloat()
}
private fun layoutColumn(rows: List<HudRow>, x: Float, y0: Float,
rowPx: Float, lineGap: Float, lvGap: Float): Pair<Float, Float> {
if (rows.isEmpty()) return Pair(y0, x)
var labelCol = 0f
for (r in rows) if (!r.inline) labelCol = max(labelCol, measure(r.label.text, rowPx))
val h = lineH(rowPx); val asc = ascent(rowPx)
var y = y0; var right = x
for (r in rows) {
val baseline = y - asc
placeRun(x, baseline, listOf(r.label))
val valX = if (r.inline) x + measure(r.label.text, rowPx) + lvGap
else x + labelCol + lvGap
val end = placeRun(valX, baseline, r.vals)
right = max(right, end)
y += h + lineGap
}
return Pair(y - lineGap, right)
}
private fun layoutWrap(fragments: List<List<Span>>, x: Float, y0: Float, maxWidth: Float,
px: Float, lineGap: Float): Pair<Float, Float> {
if (fragments.isEmpty()) return Pair(y0, x)
val h = lineH(px); val asc = ascent(px)
val sepW = measure(" · ", px)
var cx = x; var y = y0; var right = x; var firstOnLine = true
for (frag in fragments) {
val w = runWidth(frag)
if (!firstOnLine && (cx + sepW + w - x) > maxWidth) { y += h + lineGap; cx = x; firstOnLine = true }
if (!firstOnLine) { placeRun(cx, y - asc, listOf(Span(" · ", colDim, px))); cx += sepW }
val end = placeRun(cx, y - asc, frag)
cx = end; right = max(right, end); firstOnLine = false
}
return Pair(y + h, right)
}
private fun buildMega(s: HudMetrics.Snapshot) {
val rowPx = sp(11.5f); val unitPx = rowPx * 0.62f; val bandPx = sp(9.5f)
val pad = sp(10f); val lineGap = sp(3.5f); val lvGap = sp(7f); val gutter = sp(16f)
val left = ArrayList<HudRow>()
if (showGpuModel && gpuNameText().isNotBlank())
left.add(HudRow(Span("GPU", colGpu, rowPx), gpuModelSpans(rowPx, colValue)))
if (showGPU && hasGpuStats(s)) {
val v = ArrayList<Span>()
v += numUnit(s.gpuPercent?.toString(), "%", rowPx, unitPx)
if (showGpuTemp) tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx)
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
v += gap(unitPx); v += numUnit(s.gpuClockMhz?.toString(), "MHz", rowPx, unitPx)
left.add(HudRow(Span("GPU", colGpu, rowPx), v))
}
if (showCPU) {
val v = ArrayList<Span>()
v += numUnit(s.cpuPercent?.toString(), "%", rowPx, unitPx)
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
if (showCpuTemp) tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx)
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
left.add(HudRow(Span("CPU", colCpu, rowPx), v))
}
if (showPerCore) {
val pct = s.perCorePercent; val clk = s.perCoreClockMhz
val n = max(pct.size, clk.size)
for (i in 0 until n) {
val v = ArrayList<Span>()
v += numUnit(if (i < pct.size && pct[i] >= 0) pct[i].toString() else null, "%", rowPx, unitPx)
v += gap(unitPx)
v += numUnit(if (i < clk.size && clk[i] > 0) clk[i].toString() else null, "MHz", rowPx, unitPx)
left.add(HudRow(Span("C$i", colCpu, rowPx), v))
}
}
val right = ArrayList<HudRow>()
if (showVram && s.vramText() != null)
right.add(HudRow(Span("VRAM", colVram, rowPx), valueUnit(s.vramText()!!, rowPx, unitPx)))
if (showRAM) {
val v = ArrayList<Span>()
v += valueUnit(s.ramUsedText(), rowPx, unitPx)
v += Span("/", colDim, unitPx); v += valueUnit(s.ramTotalText(), rowPx, unitPx)
v += gap(unitPx); v += numUnit(s.ramPercent.roundToInt().toString(), "%", rowPx, unitPx)
right.add(HudRow(Span("RAM", colRam, rowPx), v))
}
if (showSwap && s.swapUsedText() != null) {
val v = ArrayList<Span>()
v += valueUnit(s.swapUsedText()!!, rowPx, unitPx)
s.swapTotalText()?.let { v += Span("/", colDim, unitPx); v += valueUnit(it, rowPx, unitPx) }
right.add(HudRow(Span("SWP", colRam, rowPx), v))
}
if (showNet && s.netDownBps != null) {
val d = (s.netDownBps ?: 0L) / 1024L
val u = (s.netUpBps ?: 0L) / 1024L
val v = ArrayList<Span>()
v += Span("↓", colDim, unitPx); v += Span(d.toString(), colValue, rowPx)
v += Span(" ↑", colDim, unitPx); v += Span(u.toString(), colValue, rowPx)
v += Span("KB/s", colDim, unitPx)
right.add(HudRow(Span("NET", colFps, rowPx), v))
}
if (showBattery || showPower || showBatteryTemp) {
val v = ArrayList<Span>(); var any = false
if (showBattery && s.battery.percent != null) { v += numUnit(s.battery.percent.toString(), "%", rowPx, unitPx); any = true }
if (showBatteryTemp) tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, rowPx, unitPx)
.let { if (it.isNotEmpty()) { if (any) v += gap(unitPx); v += it; any = true } }
if (showPower && s.battery.watts > 0f) { if (any) v += gap(unitPx); v += numUnit(fmt1(s.battery.watts), "W", rowPx, unitPx); any = true }
if (any) right.add(HudRow(Span("BAT", colBat, rowPx), v))
}
if (showFPS) {
val v = ArrayList<Span>()
v += glowing(numUnit(fpsText(fpsNow), "FPS", rowPx, unitPx))
v += gap(unitPx); v += numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", rowPx, unitPx)
right.add(HudRow(Span(apiLabel(), colFps, rowPx), v))
right.add(HudRow(Span("AVG", colLo, rowPx), numUnit(fmt1(fpsAvg), "FPS", rowPx, unitPx)))
if (showLow1)
right.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
if (showLow01)
right.add(HudRow(Span("0.1%", colLo, rowPx), numUnit(lowText(lows.low01Fps), "FPS", rowPx, unitPx)))
if (showLow001)
right.add(HudRow(Span("0.01%", colLo, rowPx), numUnit(lowText(lows.low001Fps), "FPS", rowPx, unitPx)))
}
val (leftBottom, leftRight) = layoutColumn(left, pad, pad, rowPx, lineGap, lvGap)
val rightX = (if (left.isEmpty()) pad else leftRight + gutter)
val (rightBottom, rightRight) = layoutColumn(right, rightX, pad, rowPx, lineGap, lvGap)
var y = max(leftBottom, rightBottom)
var maxRight = max(leftRight, rightRight)
val band = ArrayList<List<Span>>()
if (showResolution) band.add(listOf(Span("RES ", colDim, bandPx), Span(resolutionString(), colValue, bandPx)))
if (displayServer.isNotBlank()) band.add(listOf(Span("DISP ", colDim, bandPx), Span(displayServer, colDisp, bandPx)))
if (hdrState != DroidDeckHudHdr.NONE) band.add(listOf(Span("HDR ", colDim, bandPx)) + hdrValue(bandPx))
if (showProton && wineVersion.isNotBlank()) band.add(listOf(Span(wineVersion, colVram, bandPx)))
if (showSession) band.add(listOf(Span("elapsed ", colDim, bandPx), Span(elapsedString(), colValue, bandPx)))
if (band.isNotEmpty()) {
y += sp(4f)
val (bBottom, bRight) = layoutWrap(band, pad, y, max(maxRight - pad, sp(180f)), bandPx, lineGap)
y = bBottom; maxRight = max(maxRight, bRight)
}
if (showGraph) {
y += sp(3f)
val gh = sp(22f)
val gr = max(maxRight, pad + sp(220f))
graphRect = RectF(pad, y, gr, y + gh)
maxRight = max(maxRight, gr)
y += gh
}
val dxLine = dxVersionLabeled()
val hasDx = showDxVer && dxLine.isNotBlank()
if (hasDx) {
y += sp(4f)
maxRight = max(maxRight, placeRun(pad, y - ascent(bandPx), listOf(Span(dxLine, colDim, bandPx))))
y += lineH(bandPx)
}
if (showWrapper && graphicsWrapper.isNotBlank()) {
y += if (hasDx) sp(1f) else sp(4f)
maxRight = max(maxRight, placeRun(pad, y - ascent(bandPx), listOf(Span(graphicsWrapper, colDim, bandPx))))
y += lineH(bandPx)
}
contentW = maxRight + pad
contentH = y + pad
addSubtleClock(pad)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
if (stripRect != null) { setMeasuredDimension(contentW.roundToInt(), resolveSize(contentH.roundToInt(), heightMeasureSpec)); return }
setMeasuredDimension(
@@ -1567,6 +1262,8 @@ class DroidDeckHudView(context: Context) : View(context) {
const val MIN_SCALE = 0.5f
const val MAX_SCALE = 2f
const val GRAPH_CLIP_MS = 49.9f
const val GRAPH_HEIGHT_SP = 22f
const val GRAPH_MIN_WIDTH_SP = 160f
fun parseIntOr(s: String?, d: Int): Int = try { s?.trim()?.toInt() ?: d } catch (e: Exception) { d }
@@ -14,6 +14,8 @@
package com.droiddeck.launcher.hud;
import com.droiddeck.launcher.session.BatteryRuntimeEstimator;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
@@ -560,10 +562,9 @@ public class HudMetrics {
return sawSignal;
}
private Double smoothedBatteryRuntimeHours = null;
private static final double MAX_RUNTIME_HOURS = 72.0;
private static final double RUNTIME_SMOOTHING_OLD_WEIGHT = 0.65;
private static final double RUNTIME_SMOOTHING_NEW_WEIGHT = 0.35;
private final BatteryRuntimeEstimator batteryRuntimeEstimator = new BatteryRuntimeEstimator();
private Boolean lastBatteryDischarging = null;
private Boolean lastBatteryCharging = null;
public Battery collectBattery() {
BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
@@ -581,11 +582,22 @@ public class HudMetrics {
int st = status.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN);
boolean charging = st == BatteryManager.BATTERY_STATUS_CHARGING || st == BatteryManager.BATTERY_STATUS_FULL;
boolean discharging = st == BatteryManager.BATTERY_STATUS_DISCHARGING
|| st == BatteryManager.BATTERY_STATUS_NOT_CHARGING;
if (lastBatteryDischarging != null && lastBatteryDischarging.booleanValue() != discharging) {
batteryRuntimeEstimator.reset();
}
lastBatteryDischarging = discharging;
if (st == BatteryManager.BATTERY_STATUS_UNKNOWN) {
Boolean sysCharging = readChargingFromPowerSupply();
if (sysCharging != null) charging = sysCharging;
}
long currentMicroAmps = Math.abs(bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW));
if (lastBatteryCharging != null
&& lastBatteryCharging.booleanValue() != charging) {
batteryRuntimeEstimator.reset();
}
lastBatteryCharging = charging;
long currentMicroAmps = BatteryRuntimeEstimator.toMicroamps(bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW));
long chargeCounter = bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER);
int voltageMv = status.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
@@ -606,36 +618,16 @@ public class HudMetrics {
if (uw != null && uw != 0L) watts = (float) (Math.abs(uw) / 1_000_000.0);
}
Double runtimeHours = !charging
? batteryRuntimeEstimator.estimateHours(chargeCounter, Math.abs((double) currentMicroAmps))
: null;
String runtimeText;
if (charging) {
smoothedBatteryRuntimeHours = null;
runtimeText = "LEFT CHG";
} else if (currentMicroAmps <= 0L || chargeCounter <= 0L) {
runtimeText = null;
} else {
double rawHours = (double) chargeCounter / (double) currentMicroAmps;
if (!Double.isFinite(rawHours) || rawHours <= 0.0 || rawHours > MAX_RUNTIME_HOURS) {
runtimeText = null;
} else {
double smoothed = smoothedBatteryRuntimeHours == null ? rawHours
: (smoothedBatteryRuntimeHours * RUNTIME_SMOOTHING_OLD_WEIGHT)
+ (rawHours * RUNTIME_SMOOTHING_NEW_WEIGHT);
smoothedBatteryRuntimeHours = smoothed;
runtimeText = "LEFT " + formatRuntimeHours(smoothed);
}
}
if (st == BatteryManager.BATTERY_STATUS_FULL || (percent != null && percent >= 100)) runtimeText = "Full";
else if (charging) runtimeText = "Charging";
else runtimeText = BatteryRuntimeEstimator.formatDuration(runtimeHours);
return new Battery(watts, charging, percent, tempC, runtimeText);
}
private static String formatRuntimeHours(double hours) {
int totalMinutes = Math.max(1, (int) Math.round(hours * 60.0));
int wholeHours = totalMinutes / 60;
int minutes = totalMinutes % 60;
if (wholeHours > 0 && minutes > 0) return wholeHours + "h " + minutes + "m";
if (wholeHours > 0) return wholeHours + "h";
return minutes + "m";
}
private static float currentRawToAmps(long raw) {
if (raw == 0L || raw == Long.MIN_VALUE) return 0f;
long a = Math.abs(raw);
@@ -843,7 +835,7 @@ public class HudMetrics {
Battery android = collectBattery();
MangoReadings.Battery bat = m.battery();
Battery battery = bat == null ? android : new Battery(bat.getWatts(), bat.getCharging(),
bat.getPercent() != null ? bat.getPercent() : android.percent, android.tempC, android.runtimeText);
bat.getPercent() != null ? bat.getPercent() : android.percent, android.tempC, bat.getRuntimeText());
long[] net = readNetRateBps();
int[] perCoreClk = getPerCoreClockMhz();
return new Snapshot(cpu != null ? cpu.getPercent() : null, m.gpuPercent(), fastestCoreMhz(perCoreClk), m.gpuClockMhz(),
@@ -2,13 +2,18 @@ package com.droiddeck.launcher.hud
import android.os.Environment
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.BatteryRuntimeEstimator
import java.io.File
import kotlin.math.abs
import kotlin.math.roundToInt
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)
class Battery(val percent: Int?, val watts: Float, val charging: Boolean, val runtimeText: String?)
private val batteryRuntimeEstimator = BatteryRuntimeEstimator()
private var lastBatteryDischarging: Boolean? = null
private val cpuTimes = HashMap<String, LongArray>()
private val cpuPercents = HashMap<String, Int>()
@@ -106,32 +111,113 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)?.takeIf { it > 0 }
fun battery(): Battery? {
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }?.take(2)
if (dirs.isNullOrEmpty()) return null
var chargeNow = 0f
var chargeFull = 0f
var watts = 0f
var charging = false
var weightedChargeNow = 0.0
var weightedChargeFull = 0.0
var allHaveWeightedCharge = true
val perBatteryPercents = ArrayList<Int>()
var runtimeChargeUah = 0.0
var runtimeChargeComplete = true
var aggregateCurrentUa = 0.0
var currentComplete = true
var watts = 0.0
var anyDischarging = false
var anyChargingStatus = false
var allFull = true
var suppliedRuntimeSeconds: Long? = null
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()
val isDischarging = status == "Discharging" || status == "Not charging"
if (isDischarging) anyDischarging = true
if (status == "Charging" || status == "Unknown") anyChargingStatus = true
if (status != "Full") allFull = false
val chargeNowFile = File(dir, "charge_now")
val chargeFullFile = File(dir, "charge_full")
val energyNowFile = File(dir, "energy_now")
val energyFullFile = File(dir, "energy_full")
val voltageFile = File(dir, "voltage_now")
val chargeNow = if (chargeNowFile.isFile) readFloat(chargeNowFile)?.toDouble() else null
val chargeFull = if (chargeFullFile.isFile) readFloat(chargeFullFile)?.toDouble() else null
val energyNow = if (energyNowFile.isFile) readFloat(energyNowFile)?.toDouble() else null
val energyFull = if (energyFullFile.isFile) readFloat(energyFullFile)?.toDouble() else null
val voltageUv = if (voltageFile.isFile) readFloat(voltageFile)?.toDouble() else null
val nowForPercent: Double? = when {
chargeNow != null && chargeNow >= 0.0 -> chargeNow
energyNow != null && voltageUv != null -> BatteryRuntimeEstimator.chargeMicroampHoursFromEnergy(energyNow, voltageUv)
else -> null
}
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 fullForPercent: Double? = when {
chargeFull != null && chargeFull > 0.0 -> chargeFull
energyFull != null && voltageUv != null -> BatteryRuntimeEstimator.chargeMicroampHoursFromEnergy(energyFull, voltageUv)
else -> null
}
if (nowForPercent != null && fullForPercent != null && fullForPercent > 0.0) {
weightedChargeNow += nowForPercent
weightedChargeFull += fullForPercent
perBatteryPercents += (nowForPercent * 100.0 / fullForPercent).roundToInt().coerceIn(0, 100)
} else {
allHaveWeightedCharge = false
readFloat(File(dir, "capacity"))?.roundToInt()?.coerceIn(0, 100)?.let { perBatteryPercents += it }
}
when {
chargeNow != null && chargeNow >= 0.0 -> runtimeChargeUah += chargeNow
energyNow != null && voltageUv != null ->
BatteryRuntimeEstimator.chargeMicroampHoursFromEnergy(energyNow, voltageUv)?.let { runtimeChargeUah += it }
?: run { runtimeChargeComplete = false }
else -> runtimeChargeComplete = false
}
if (dirs.size == 1) {
suppliedRuntimeSeconds = readLong(File(dir, "time_to_empty_avg"))?.takeIf { it > 0L }
?: readLong(File(dir, "time_to_empty_now"))?.takeIf { it > 0L }
?: suppliedRuntimeSeconds
}
val currentFile = File(dir, "current_now")
val powerFile = File(dir, "power_now")
val currentNow = if (currentFile.isFile) readFloat(currentFile)?.toDouble() else null
val currentForEta = when {
currentNow != null -> abs(currentNow)
powerFile.isFile && voltageUv != null -> readFloat(powerFile)?.toDouble()?.let {
BatteryRuntimeEstimator.currentMicroampsFromPower(it, voltageUv)
}
else -> null
}
if (currentForEta == null) currentComplete = false else aggregateCurrentUa += currentForEta
if (isDischarging) {
val power = if (powerFile.isFile) readFloat(powerFile)?.toDouble() else null
if (power != null) watts += abs(power) / 1_000_000.0
else if (currentNow != null && voltageUv != null) watts += abs(currentNow * voltageUv) / 1_000_000_000_000.0
}
}
val percent = if (chargeFull > 0f) Math.round(chargeNow / chargeFull * 100f) else null
return Battery(percent, if (charging) 0f else watts, charging)
val percent = when {
allHaveWeightedCharge && weightedChargeFull > 0.0 -> (weightedChargeNow * 100.0 / weightedChargeFull).roundToInt().coerceIn(0, 100)
perBatteryPercents.isNotEmpty() -> perBatteryPercents.average().roundToInt().coerceIn(0, 100)
else -> null
}
if (lastBatteryDischarging != null && lastBatteryDischarging != anyDischarging) {
batteryRuntimeEstimator.reset()
}
lastBatteryDischarging = anyDischarging
val estimatedHours = if (anyDischarging && runtimeChargeComplete && currentComplete)
batteryRuntimeEstimator.estimateHours(runtimeChargeUah, aggregateCurrentUa) else null
val runtimeHours = suppliedRuntimeSeconds?.let { it / 3600.0 } ?: estimatedHours
val charging = !anyDischarging && anyChargingStatus
val runtimeText = when {
anyDischarging -> BatteryRuntimeEstimator.formatDuration(runtimeHours)
charging -> "Charging"
allFull -> "Full"
else -> null
}
return Battery(percent, if (anyDischarging) watts.toFloat() else 0f, charging, runtimeText)
}
private fun fresh(file: File, maxAgeMs: Long = FEED_FRESH_MS): File? =
@@ -1,10 +1,8 @@
package com.droiddeck.launcher.input
import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.AccessibilityServiceInfo
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Rect
import android.hardware.display.DisplayManager
import android.os.Build
import android.os.Handler
@@ -12,9 +10,9 @@ import android.os.HandlerThread
import android.os.SystemClock
import android.util.Log
import android.view.Display
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityWindowInfo
import android.view.inputmethod.InputMethodManager
import com.droiddeck.shortcuts.Relay
import java.util.concurrent.ConcurrentHashMap
object BottomScreenGuests {
@@ -45,7 +43,7 @@ object BottomScreenGuests {
sdk >= 33 && DualScreen.yieldsBottom(model)
}
class BottomScreenWatch(private val service: AccessibilityService) {
class BottomScreenWatch(private val service: Context) {
private class Arrival(val pkg: String, val at: Long)
private val thread = HandlerThread("bottom-screen").apply { start() }
@@ -57,33 +55,22 @@ class BottomScreenWatch(private val service: AccessibilityService) {
private var holders: Map<Int, String?> = emptyMap()
private var ownWindows: Map<Int, Set<Int>> = emptyMap()
private val ownShownAt = mutableMapOf<Int, Long>()
private val check = Runnable { evaluate() }
fun start() {
current = this
service.serviceInfo = service.serviceInfo?.apply {
eventTypes = eventTypes or AccessibilityEvent.TYPE_WINDOWS_CHANGED or AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
flags = flags or AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS
}
handler.post {
homes = homePackages()
keyboards = keyboardPackages()
evaluate()
}
}
fun onEvent(event: AccessibilityEvent) {
when (event.eventType) {
AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> {
val pkg = event.packageName?.toString() ?: return
if (event.displayId == Display.DEFAULT_DISPLAY || pkg == own || pkg == SYSTEM_UI) return
arrivals[event.displayId] = Arrival(pkg, event.eventTime)
}
AccessibilityEvent.TYPE_WINDOWS_CHANGED -> Unit
else -> return
}
handler.removeCallbacks(check)
handler.postDelayed(check, 150)
fun onArrival(displayId: Int, pkg: String, at: Long) {
if (displayId == Display.DEFAULT_DISPLAY || pkg == own || pkg == SYSTEM_UI) return
arrivals[displayId] = Arrival(pkg, at)
}
fun onWindows(all: Map<Int, List<Relay.Window>>) {
handler.post { evaluate(all) }
}
fun stop() {
@@ -97,25 +84,22 @@ class BottomScreenWatch(private val service: AccessibilityService) {
thread.quitSafely()
}
private fun evaluate() {
private fun evaluate(all: Map<Int, List<Relay.Window>>) {
val seen = HashMap(arrivals)
val all = runCatching { service.windowsOnAllDisplays }.getOrNull() ?: return
val displays = service.getSystemService(DisplayManager::class.java) ?: return
val taken = mutableMapOf<Int, String?>()
val shown = mutableMapOf<Int, Set<Int>>()
val now = SystemClock.uptimeMillis()
for (i in 0 until all.size()) {
val id = all.keyAt(i)
for ((id, list) in all) {
if (id == Display.DEFAULT_DISPLAY) continue
val display = displays.getDisplay(id)?.takeIf(DualScreen::builtIn) ?: continue
val windows = all.valueAt(i)
val windows = list
.filter { !BottomScreenGuests.ignorable(it.type) && cover(it, display) >= BottomScreenGuests.MIN_COVER }
.sortedByDescending { it.layer }
.map { it to packageOf(it) }
val ours = windows.filter { it.second == own }.map { it.first.id }.toSet()
val ours = windows.filter { it.pkg == own }.map { it.id }.toSet()
if (!ownWindows[id].orEmpty().containsAll(ours)) ownShownAt[id] = now
shown[id] = ours
val topPkg = windows.firstNotNullOfOrNull { it.second?.takeUnless { pkg -> pkg == own } }
val topPkg = windows.firstNotNullOfOrNull { it.pkg?.takeUnless { pkg -> pkg == own } }
val arrival = seen[id]?.takeIf { BottomScreenGuests.current(it.at, ownShownAt[id]) }
seen[id]?.takeIf { topPkg != null || arrival == null }?.let { arrivals.remove(id, it) }
BottomScreenGuests.holder(topPkg, arrival?.pkg?.takeUnless { it in keyboards }, homes)?.let { taken[id] = it }
@@ -127,15 +111,11 @@ class BottomScreenWatch(private val service: AccessibilityService) {
DualScreen.setTaken(taken.keys)
}
private fun cover(window: AccessibilityWindowInfo, display: Display): Float {
val bounds = Rect().also(window::getBoundsInScreen)
private fun cover(window: Relay.Window, display: Display): Float {
val area = display.mode.physicalWidth.toFloat() * display.mode.physicalHeight
return if (area <= 0f) 0f else bounds.width().toFloat() * bounds.height() / area
return if (area <= 0f) 0f else window.bounds.width().toFloat() * window.bounds.height() / area
}
private fun packageOf(window: AccessibilityWindowInfo): String? =
runCatching { window.getRoot(0)?.packageName?.toString() }.getOrNull()
private fun homePackages(): Set<String> {
val pm = service.packageManager
return listOf(Intent.CATEGORY_HOME, Intent.CATEGORY_SECONDARY_HOME).flatMap { category ->
@@ -154,6 +134,7 @@ class BottomScreenWatch(private val service: AccessibilityService) {
private companion object {
@Volatile var current: BottomScreenWatch? = null
const val TAG = "BottomScreen"
const val SYSTEM_UI = "com.android.systemui"
}
@@ -82,6 +82,8 @@ public class FakeInputWriter {
private static final int PAD_TYPE_OFFSET = IMU_OFFSET + 44;
private static final int PAD_TYPE_SET = 0x80000000;
private static final int LATENCY_OFFSET = IMU_OFFSET + 48;
private static final int REMOTE_IMU_MODE_OFFSET = IMU_OFFSET + 52;
private static final int REMOTE_IMU_PID_OFFSET = IMU_OFFSET + 56;
public static final int LATENCY_CONTROLLER = 1;
public static final int LATENCY_TOUCH = 2;
private static volatile int latency = 0;
@@ -231,6 +233,8 @@ public class FakeInputWriter {
}
data.putInt(IMU_OFFSET, 0);
data.putInt(IMU_MODE_OFFSET, 0);
data.putInt(REMOTE_IMU_MODE_OFFSET, 0);
data.putInt(REMOTE_IMU_PID_OFFSET, 0);
data.putLong(IMU_SEQ_OFFSET, 0L);
for (int i = 0; i < 12; i++) {
data.putShort(IMU_ACCEL_OFFSET + (i * 2), (short) 0);
@@ -494,8 +498,11 @@ public class FakeInputWriter {
if (ringSlot == null) return -1;
synchronized (ringSlot) {
ByteBuffer ring = ringSlot.data;
int value = ring == null ? 0 : ring.getInt(IMU_MODE_OFFSET);
return value < 0 ? value & 0xffff : -1;
if (ring == null) return 0;
int remote = ring.getInt(REMOTE_IMU_MODE_OFFSET);
int pid = ring.getInt(REMOTE_IMU_PID_OFFSET);
return ImuModes.combine(ring.getInt(IMU_MODE_OFFSET), remote,
remote < 0 && pid > 0 && new File("/proc/" + pid).exists());
}
}
@@ -0,0 +1,158 @@
package com.droiddeck.launcher.input
/** Where a USB mouse's input report keeps its buttons, motion and wheel, as its HID report descriptor lays them out. */
class HidMouseReport(
val reportId: Int,
private val buttons: List<Field?>,
private val x: Field,
private val y: Field,
private val wheel: Field?,
) {
class Field(private val bit: Int, private val size: Int, private val signed: Boolean) {
fun read(report: ByteArray, length: Int, base: Int): Int {
var value = 0
for (i in 0 until minOf(size, 32)) {
val at = base + bit + i
if (at / 8 >= length) break
if ((report[at / 8].toInt() shr (at % 8)) and 1 != 0) value = value or (1 shl i)
}
return if (signed && size in 1..31 && value and (1 shl (size - 1)) != 0) value - (1 shl size) else value
}
}
/** [buttons] has bit 0 set for the first button. */
data class State(val buttons: Int, val dx: Int, val dy: Int, val wheel: Int)
/** Returns null for reports with another ID, such as a receiver's media keys. */
fun decode(report: ByteArray, length: Int): State? {
val base = if (reportId == 0) 0 else {
if (length < 1 || (report[0].toInt() and 0xff) != reportId) return null
8
}
var pressed = 0
buttons.forEachIndexed { i, field -> if (field != null && field.read(report, length, base) != 0) pressed = pressed or (1 shl i) }
return State(pressed, x.read(report, length, base), y.read(report, length, base), wheel?.read(report, length, base) ?: 0)
}
companion object {
/** The report every boot mouse sends after SET_PROTOCOL(boot): three buttons, then X and Y as signed bytes. */
val BOOT = HidMouseReport(0, List(3) { Field(it, 1, false) }, Field(8, 8, true), Field(16, 8, true), null)
private const val BUTTON_PAGE = 0x09
private const val MOUSE = 0x00010002
private const val X = 0x00010030
private const val Y = 0x00010031
private const val WHEEL = 0x00010038
private const val MAX_BUTTONS = 8
private const val MAX_FIELD_BITS = 32
private const val MAX_REPORT_COUNT = 4096
private class Global(var usagePage: Int = 0, var logicalMin: Int = 0, var reportSize: Int = 0,
var reportCount: Int = 0, var reportId: Int = 0) {
fun copy() = Global(usagePage, logicalMin, reportSize, reportCount, reportId)
}
private class Placed(val reportId: Int, val field: Field)
/** Returns null if [descriptor] has no mouse collection with X and Y in one report. */
fun parse(descriptor: ByteArray): HidMouseReport? {
var global = Global()
val pushed = ArrayDeque<Global>()
val usages = mutableListOf<Int>()
var usageMin = -1
var usageMax = -1
val offsets = HashMap<Int, Int>()
var depth = 0
var mouseDepth = -1
var mouseDone = false
val placed = HashMap<Int, Placed>()
fun usage(index: Int): Int = when {
usages.isNotEmpty() -> usages.getOrElse(index) { usages.last() }
usageMin >= 0 && usageMax >= usageMin -> minOf(usageMin + index, usageMax)
else -> -1
}
var i = 0
while (i < descriptor.size) {
val prefix = descriptor[i].toInt() and 0xff
if (prefix == 0xfe) {
if (i + 1 >= descriptor.size) break
i += 3 + (descriptor[i + 1].toInt() and 0xff)
continue
}
val size = intArrayOf(0, 1, 2, 4)[prefix and 3]
if (i + 1 + size > descriptor.size) break
var data = 0
for (b in 0 until size) data = data or ((descriptor[i + 1 + b].toInt() and 0xff) shl (8 * b))
val signedData = when (size) {
1 -> data.toByte().toInt()
2 -> data.toShort().toInt()
else -> data
}
val tag = prefix shr 4
when ((prefix shr 2) and 3) {
0 -> {
when (tag) {
0x8 -> {
if (global.reportSize !in 0..MAX_FIELD_BITS || global.reportCount !in 0..MAX_REPORT_COUNT) return null
val start = offsets[global.reportId] ?: 0
val isData = data and 1 == 0
val isVariable = data and 2 != 0
if (mouseDepth >= 0 && !mouseDone && isData && isVariable) {
for (n in 0 until global.reportCount) {
val u = usage(n)
if (u < 0) break
val field = Placed(global.reportId, Field(start + n * global.reportSize, global.reportSize, global.logicalMin < 0))
val button = if (u ushr 16 == BUTTON_PAGE) u and 0xffff else 0
when {
u == X || u == Y || u == WHEEL -> placed.putIfAbsent(u, field)
button in 1..MAX_BUTTONS -> placed.putIfAbsent(u, field)
}
}
}
offsets[global.reportId] = start + global.reportSize * global.reportCount
}
0xa -> {
depth++
if (mouseDepth < 0 && data == 1 && usage(0) == MOUSE) mouseDepth = depth
}
0xc -> {
if (depth == mouseDepth) mouseDone = true
depth--
}
}
usages.clear()
usageMin = -1
usageMax = -1
}
1 -> when (tag) {
0x0 -> global.usagePage = data
0x1 -> global.logicalMin = signedData
0x7 -> global.reportSize = data
0x8 -> global.reportId = data
0x9 -> global.reportCount = data
0xa -> pushed.addLast(global.copy())
0xb -> global = pushed.removeLastOrNull() ?: global
}
2 -> {
val full = if (size == 4) data else (global.usagePage shl 16) or data
when (tag) {
0x0 -> usages += full
0x1 -> usageMin = full
0x2 -> usageMax = full
}
}
}
i += 1 + size
}
val x = placed[X] ?: return null
val y = placed[Y]?.takeIf { it.reportId == x.reportId } ?: return null
val id = x.reportId
val buttons = (1..MAX_BUTTONS).map { n -> placed[(BUTTON_PAGE shl 16) or n]?.takeIf { it.reportId == id }?.field }
return HidMouseReport(id, buttons.dropLastWhile { it == null }, x.field, y.field,
placed[WHEEL]?.takeIf { it.reportId == id }?.field)
}
}
}
@@ -0,0 +1,14 @@
package com.droiddeck.launcher.input;
final class ImuModes {
private ImuModes() {}
// Steam and its Remote Play client each keep their own mode word, with the top bit set once written. Motion is
// read while either process wants it, and a word that has not been set leaves the choice to the other one.
// -1 means neither has set a mode yet.
static int combine(int steam, int remote, boolean remoteRunning) {
boolean remoteSet = remote < 0 && remoteRunning;
if (steam >= 0 && !remoteSet) return -1;
return ((steam < 0 ? steam : 0) | (remoteSet ? remote : 0)) & 0xffff;
}
}
@@ -3,11 +3,16 @@ package com.droiddeck.launcher.input
object InputSpace {
const val WIDTH = 1920
const val HEIGHT = 1080
const val FIXED_ONE = 256
fun x(position: Float, viewWidth: Int): Int = scale(position, viewWidth, WIDTH)
fun y(position: Float, viewHeight: Int): Int = scale(position, viewHeight, HEIGHT)
fun fixedX(position: Float, viewWidth: Int): Int = scale(position, viewWidth, WIDTH * FIXED_ONE)
fun fixedY(position: Float, viewHeight: Int): Int = scale(position, viewHeight, HEIGHT * FIXED_ONE)
private fun scale(position: Float, extent: Int, size: Int): Int =
if (extent <= 0) 0 else (position / extent * size).toInt().coerceIn(0, size - 1)
}
@@ -57,6 +57,16 @@ class MouseBackInput(private val sendRight: (Boolean) -> Unit, private val mouse
!device.supportsSource(InputDevice.SOURCE_TOUCHSCREEN)
}
/** A controller's own mouse interface (8BitDo Ultimate Mobile) is not a mouse the user right-clicks with. */
fun externalMouse(devices: List<InputDevice?>): InputDevice? {
val controllers = devices.filterNotNull().filter { PadBridge.isFromController(it) }
return devices.filterNotNull().firstOrNull { mouse ->
isExternalMouse(mouse) && controllers.none {
it.vendorId != 0 && it.vendorId == mouse.vendorId && it.productId == mouse.productId
}
}
}
private val VIRTUAL_NAME = Regex("\\bvirtual\\b", RegexOption.IGNORE_CASE)
fun declaresVirtual(name: String?): Boolean = name != null && VIRTUAL_NAME.containsMatchIn(name)
@@ -0,0 +1,46 @@
package com.droiddeck.launcher.input
import kotlin.math.abs
/**
* Holding the middle button still opens the session menu. While the session reads the mouse over USB, Android has
* no cursor, so this is how a mouse reaches the menu and, through it, the system again.
*/
class MouseMenuHold(
private val schedule: (Runnable, Long) -> Unit,
private val cancel: (Runnable) -> Unit,
private val onMenu: () -> Unit,
) {
private var holding = false
private var travel = 0
private val fire = Runnable {
if (!holding) return@Runnable
holding = false
onMenu()
}
fun onButton(index: Int, down: Boolean) {
if (index != MIDDLE) return
cancel(fire)
holding = down
travel = 0
if (down) schedule(fire, HOLD_MS)
}
fun onMove(dx: Int, dy: Int) {
if (!holding) return
travel += abs(dx) + abs(dy)
if (travel > SLOP) reset()
}
fun reset() {
holding = false
cancel(fire)
}
companion object {
const val MIDDLE = 2
const val HOLD_MS = 2000L
const val SLOP = 48
}
}
@@ -0,0 +1,14 @@
package com.droiddeck.launcher.input
import com.droiddeck.launcher.session.SessionPrefs
object PenRouter {
enum class Route { BLOCKED, PEN, RELATIVE, TOUCH }
fun decide(uiBlocking: Boolean, mode: String, glasses: Boolean, programLock: Boolean): Route = when {
uiBlocking -> Route.BLOCKED
mode == SessionPrefs.PEN_TOUCH -> Route.TOUCH
glasses || programLock -> Route.RELATIVE
else -> Route.PEN
}
}
@@ -0,0 +1,247 @@
package com.droiddeck.launcher.input
import android.graphics.RectF
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.InputDevice
import android.view.KeyEvent
import android.view.MotionEvent
import com.droiddeck.launcher.session.SessionPrefs
class PenStream(private val sink: Sink) {
fun interface Sink {
fun sample(flags: Int, x: Int, y: Int)
}
private val handler = Handler(Looper.getMainLooper())
private val exitLater = Runnable { if (exitPending) leave() }
private val hoverWatchdog = Runnable { checkHover() }
private var watching = false
private var contact = false
private var barrel = 0
private var keyDown = false
private var keyDevice = Int.MIN_VALUE
private var keyCode = 0
private var exitPending = false
private var exitTime = 0L
private var deviceId = Int.MIN_VALUE
private var x = 0
private var y = 0
private var sampleTime = 0L
var sideButton = SessionPrefs.PEN_BUTTON_RIGHT
var inProximity = false
private set
fun onMotion(event: MotionEvent, pointer: Int, area: RectF, width: Int, height: Int): Boolean {
val action = event.actionMasked
val time = event.eventTime
val own = isPenAction(event, pointer)
expire(time)
when (action) {
MotionEvent.ACTION_HOVER_ENTER, MotionEvent.ACTION_HOVER_MOVE -> {
continueAt(time)
contact = false
enter(event)
samples(event, pointer, area, width, height)
}
MotionEvent.ACTION_HOVER_EXIT -> if (inProximity && !exitPending && !contact) pendExit(time)
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE -> {
continueAt(time)
if (!inProximity) return true
barrel = event.buttonState
samples(event, pointer, area, width, height)
}
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> if (own) {
continueAt(time)
enter(event)
contact = true
samples(event, pointer, area, width, height)
} else if (contact) samples(event, pointer, area, width, height)
MotionEvent.ACTION_MOVE -> if (contact) {
barrel = event.buttonState
samples(event, pointer, area, width, height)
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> if (!own) {
if (contact) samples(event, pointer, area, width, height)
} else if (contact) {
if (event.flags and MotionEvent.FLAG_CANCELED != 0) cancel()
else {
barrel = event.buttonState
samples(event, pointer, area, width, height, lift = true)
pendExit(time)
}
}
MotionEvent.ACTION_CANCEL -> cancel()
else -> return false
}
return true
}
fun onKey(event: KeyEvent): Boolean {
expire(event.eventTime)
val down = event.action == KeyEvent.ACTION_DOWN
val repeat = event.repeatCount > 0
if (exitPending && !repeat) leave()
if (!inProximity || exitPending) {
if (!repeat && event.deviceId == keyDevice && event.keyCode == keyCode) keyDown = down
return true
}
if (down == keyDown) return true
val before = state()
keyDown = down
if (down) {
keyDevice = event.deviceId
keyCode = event.keyCode
}
if (state() == before) return true
emit(state())
return true
}
fun cancel(releaseKey: Boolean = false) {
if (releaseKey) keyDown = false
leave()
}
fun holdsKey(event: KeyEvent): Boolean = keyDown && event.deviceId == keyDevice && event.keyCode == keyCode
fun deviceRemoved(deviceId: Int) {
if (deviceId == this.deviceId) cancel()
if (!keyDown || deviceId != keyDevice) return
val before = state()
keyDown = false
if (inProximity && state() != before) emit(state())
}
private fun enter(event: MotionEvent) {
barrel = event.buttonState
if (inProximity) return
inProximity = true
deviceId = event.deviceId
}
private fun continueAt(time: Long) {
if (!exitPending) return
if (time - exitTime > EXIT_GRACE_MS) { leave(); return }
exitPending = false
handler.removeCallbacks(exitLater)
}
private fun pendExit(time: Long) {
exitPending = true
exitTime = time
handler.removeCallbacks(exitLater)
handler.postDelayed(exitLater, EXIT_GRACE_MS)
}
private fun expire(time: Long) {
if (inProximity && !contact && time - sampleTime >= HOVER_TIMEOUT_MS) leave()
}
private fun watchHover(delay: Long = HOVER_TIMEOUT_MS) {
if (watching || contact) return
watching = true
handler.postDelayed(hoverWatchdog, delay)
}
private fun checkHover() {
watching = false
if (!inProximity || contact || exitPending) return
val silent = SystemClock.uptimeMillis() - sampleTime
if (silent >= HOVER_TIMEOUT_MS) leave() else watchHover(HOVER_TIMEOUT_MS - silent)
}
private fun leave() {
if (!inProximity) return
emit(0)
handler.removeCallbacks(exitLater)
handler.removeCallbacks(hoverWatchdog)
watching = false
inProximity = false
contact = false
exitPending = false
barrel = 0
}
private fun samples(event: MotionEvent, pointer: Int, area: RectF, width: Int, height: Int, lift: Boolean = false) {
for (h in 0 until event.historySize) sample(event, pointer, h, area, width, height)
if (lift) contact = false
sample(event, pointer, -1, area, width, height)
}
private fun sample(event: MotionEvent, pointer: Int, h: Int, area: RectF, width: Int, height: Int) {
x = InputSpace.fixedX(event.axis(MotionEvent.AXIS_X, pointer, h).coerceIn(area.left, area.right), width)
y = InputSpace.fixedY(event.axis(MotionEvent.AXIS_Y, pointer, h).coerceIn(area.top, area.bottom), height)
sampleTime = if (h < 0) event.eventTime else event.getHistoricalEventTime(h)
emit(state())
watchHover()
}
private fun emit(flags: Int) = sink.sample(flags, x, y)
private fun state(): Int =
PEN_IN or (if (contact) PEN_TIP else 0) or buttonFlags(keyDown || barrel and MotionEvent.BUTTON_STYLUS_PRIMARY != 0,
barrel and MotionEvent.BUTTON_STYLUS_SECONDARY != 0, sideButton)
private fun MotionEvent.axis(axis: Int, pointer: Int, h: Int): Float =
if (h < 0) getAxisValue(axis, pointer) else getHistoricalAxisValue(axis, pointer, h)
companion object {
const val PEN_IN = 1 shl 0
const val PEN_TIP = 1 shl 1
const val PEN_RIGHT = 1 shl 2
const val PEN_MIDDLE = 1 shl 3
const val HOVER_TIMEOUT_MS = 2_000L
const val EXIT_GRACE_MS = 50L
private val PEN_NAME = Regex("\\b(pen|stylus)", RegexOption.IGNORE_CASE)
fun isPen(event: MotionEvent, index: Int): Boolean = when (event.getToolType(index)) {
MotionEvent.TOOL_TYPE_STYLUS, MotionEvent.TOOL_TYPE_ERASER -> true
MotionEvent.TOOL_TYPE_UNKNOWN -> event.isFromSource(InputDevice.SOURCE_STYLUS)
else -> false
}
fun penConnected(): Boolean =
InputDevice.getDeviceIds().any { id -> InputDevice.getDevice(id)?.let { isPenDevice(it.sources) } == true }
// Before Android 14 a touchscreen that declares ABS_MT_TOOL_TYPE reports SOURCE_STYLUS without any pen.
fun isPenDevice(sources: Int, sdk: Int = Build.VERSION.SDK_INT): Boolean =
sources and InputDevice.SOURCE_STYLUS == InputDevice.SOURCE_STYLUS &&
(sources and InputDevice.SOURCE_TOUCHSCREEN != InputDevice.SOURCE_TOUCHSCREEN || sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
fun penIndex(event: MotionEvent): Int {
for (index in 0 until event.pointerCount) if (isPen(event, index)) return index
return -1
}
fun isPenAction(event: MotionEvent, index: Int): Boolean = when (event.actionMasked) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> true
MotionEvent.ACTION_POINTER_DOWN, MotionEvent.ACTION_POINTER_UP -> event.actionIndex == index
else -> false
}
fun isPenKey(event: KeyEvent): Boolean {
val device = event.device ?: return false
return isPenKeyboard(device.name, device.sources, Build.VERSION.SDK_INT < Build.VERSION_CODES.Q || device.isExternal,
device.keyboardType == InputDevice.KEYBOARD_TYPE_ALPHABETIC)
}
fun isPenKeyboard(name: String?, sources: Int, external: Boolean, alphabetic: Boolean): Boolean =
external && !alphabetic && sources == InputDevice.SOURCE_KEYBOARD && name != null && PEN_NAME.containsMatchIn(name)
fun buttonFlags(primary: Boolean, secondary: Boolean, sideButton: String): Int {
val first = when (sideButton) {
SessionPrefs.PEN_BUTTON_RIGHT -> PEN_RIGHT
SessionPrefs.PEN_BUTTON_MIDDLE -> PEN_MIDDLE
else -> 0
}
val second = if (sideButton == SessionPrefs.PEN_BUTTON_RIGHT) PEN_MIDDLE else PEN_RIGHT
return (if (primary) first else 0) or (if (secondary) second else 0)
}
}
}
@@ -23,13 +23,20 @@ internal fun MotionEvent.pointerSubset(pointerIdBits: Int): MotionEvent? {
}
val properties = Array(indices.size) { MotionEvent.PointerProperties() }
val coordinates = Array(indices.size) { MotionEvent.PointerCoords() }
indices.forEachIndexed { target, index ->
getPointerProperties(index, properties[target])
getPointerCoords(index, coordinates[target])
indices.forEachIndexed { target, index -> getPointerProperties(index, properties[target]) }
fun sample(position: Int): Array<MotionEvent.PointerCoords> {
indices.forEachIndexed { target, index ->
if (position < historySize) getHistoricalPointerCoords(index, position, coordinates[target])
else getPointerCoords(index, coordinates[target])
}
return coordinates
}
return MotionEvent.obtain(
downTime, eventTime, splitAction, indices.size, properties, coordinates,
fun time(position: Int) = if (position < historySize) getHistoricalEventTime(position) else eventTime
val split = MotionEvent.obtain(
downTime, time(0), splitAction, indices.size, properties, sample(0),
metaState, buttonState, xPrecision, yPrecision,
deviceId, edgeFlags, source, flags,
)
for (position in 1..historySize) split.addBatch(time(position), sample(position), metaState)
return split
}
@@ -1,14 +1,17 @@
package com.droiddeck.launcher.input
import android.accessibilityservice.AccessibilityService
import android.app.Service
import android.content.Context
import android.content.Intent
import android.hardware.input.InputManager
import android.os.Binder
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Parcel
import android.view.KeyEvent
import android.view.accessibility.AccessibilityEvent
import com.droiddeck.launcher.HomeApp
import com.droiddeck.shortcuts.Relay
object HomeButtonShortcuts {
private var owner: Any? = null
@@ -101,38 +104,78 @@ object SystemKeyCapture {
}
}
class HomeButtonService : AccessibilityService(), InputManager.InputDeviceListener {
class ShortcutsRelay : Service(), InputManager.InputDeviceListener {
private val main = Handler(Looper.getMainLooper())
private val trusted = java.util.concurrent.ConcurrentHashMap.newKeySet<Int>()
private var bottomScreen: BottomScreenWatch? = null
override fun onServiceConnected() {
getSystemService(InputManager::class.java).registerInputDeviceListener(this, Handler(Looper.getMainLooper()))
if (bottomScreen == null && BottomScreenGuests.supported()) bottomScreen = BottomScreenWatch(this).also { it.start() }
private val binder = object : Binder() {
override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean {
if (code !in Relay.CONFIG..Relay.WINDOWS) return super.onTransact(code, data, reply, flags)
data.enforceInterface(Relay.DESCRIPTOR)
if (!trusts(Binder.getCallingUid())) return false
when (code) {
Relay.CONFIG -> reply?.writeInt(if (bottomScreen != null) Relay.WANTS_WINDOWS else 0)
Relay.KEY -> reply?.writeInt(if (onMain(KeyEvent.CREATOR.createFromParcel(data))) 1 else 0)
Relay.INTERRUPT -> main.post { HomeButtonShortcuts.release() }
Relay.ARRIVAL -> bottomScreen?.onArrival(data.readInt(), data.readString() ?: return true, data.readLong())
Relay.WINDOWS -> bottomScreen?.onWindows(Relay.decode(data.createByteArray() ?: return true))
}
return true
}
}
private fun stopBottomScreen() {
bottomScreen?.stop()
bottomScreen = null
private fun trusts(uid: Int): Boolean {
if (uid !in trusted) {
if (!packageManager.getPackagesForUid(uid).orEmpty().contains(Relay.PACKAGE)) return false
trusted += uid
}
return com.droiddeck.launcher.core.SteamIntegration.shortcutsEnabled(this)
}
private fun onMain(event: KeyEvent): Boolean {
// A key the companion already gave up on must not run later and leave a press without its release.
val claimed = java.util.concurrent.atomic.AtomicBoolean(false)
val task = java.util.concurrent.FutureTask {
claimed.compareAndSet(false, true) &&
(SystemKeyCapture.onKeyEvent(event) || HomeButtonShortcuts.onKeyEvent(this, event))
}
main.postAtFrontOfQueue(task)
return try {
task.get(KEY_TIMEOUT_MS, java.util.concurrent.TimeUnit.MILLISECONDS)
} catch (e: java.util.concurrent.TimeoutException) {
if (claimed.compareAndSet(false, true)) false else runCatching { task.get() }.getOrDefault(false)
} catch (e: Exception) {
false
}
}
override fun onCreate() {
super.onCreate()
getSystemService(InputManager::class.java).registerInputDeviceListener(this, main)
if (BottomScreenGuests.supported()) bottomScreen = BottomScreenWatch(this).also { it.start() }
}
override fun onBind(intent: Intent?): IBinder = binder
override fun onUnbind(intent: Intent?): Boolean {
HomeButtonShortcuts.release()
return super.onUnbind(intent)
}
override fun onKeyEvent(event: KeyEvent) =
SystemKeyCapture.onKeyEvent(event) || HomeButtonShortcuts.onKeyEvent(this, event)
override fun onAccessibilityEvent(event: AccessibilityEvent?) { event?.let { bottomScreen?.onEvent(it) } }
override fun onInterrupt() { HomeButtonShortcuts.release() }
override fun onInputDeviceAdded(deviceId: Int) {}
override fun onInputDeviceChanged(deviceId: Int) {}
override fun onInputDeviceRemoved(deviceId: Int) { HomeButtonShortcuts.onDeviceRemoved(deviceId) }
override fun onUnbind(intent: Intent?): Boolean {
HomeButtonShortcuts.release()
stopBottomScreen()
com.droiddeck.launcher.core.SteamIntegration.syncShortcutsListing(this)
return super.onUnbind(intent)
}
override fun onDestroy() {
HomeButtonShortcuts.release()
stopBottomScreen()
bottomScreen?.stop()
bottomScreen = null
getSystemService(InputManager::class.java).unregisterInputDeviceListener(this)
super.onDestroy()
}
private companion object {
const val KEY_TIMEOUT_MS = 200L
}
}
@@ -129,8 +129,9 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
}
}
}
g.disconnect()
g.close()
// Android can refuse these (BLUETOOTH_CONNECT revoked); an exception on this thread would end the app.
runCatching { g.disconnect() }.onFailure { Log.w(TAG, "disconnect failed", it) }
runCatching { g.close() }.onFailure { Log.w(TAG, "close failed", it) }
Log.i(TAG, "disconnected: $why")
listener?.invoke()
}
@@ -390,7 +390,8 @@ object SteamTouchConfig {
options: Options? = null,
): File? {
val dir = configDir(context) ?: return null
val source = bindings.entries.fold(config.text ?: return null) { text, (ref, change) ->
val base = config.text ?: if (config.file == null && bindings.isEmpty()) "\"controller_mappings\"\n{\n\t\"controller_type\"\t\t\"controller_mobile_touch\"\n}\n" else return null
val source = bindings.entries.fold(base) { text, (ref, change) ->
SteamTouchBindings.rewrite(text, ref, change) ?: text
}
val key = steamKey(context, appId)
@@ -0,0 +1,262 @@
package com.droiddeck.launcher.input
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbConstants
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbEndpoint
import android.hardware.usb.UsbInterface
import android.hardware.usb.UsbManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import android.view.InputDevice
/**
* Reads a USB mouse from its HID interface, detaching it from Android meanwhile. Android only grants pointer
* capture on the focused display, so an app shown elsewhere, as in REDMAGIC's cast mode, gets a cursor that
* stops at the screen edge.
*/
class UsbMouse(private val context: Context, private val listener: Listener) {
interface Listener {
fun onMove(dx: Int, dy: Int)
fun onButton(index: Int, down: Boolean)
fun onWheel(steps: Int)
fun onChanged()
/** The mouse stopped responding while read here, so buttons held then never got their releases. */
fun onLost()
}
private val usb by lazy { context.getSystemService(Context.USB_SERVICE) as UsbManager }
private val main = Handler(Looper.getMainLooper())
private val permissionAction by lazy { context.packageName + ".USB_MOUSE_PERMISSION" }
private val asked = mutableSetOf<String>()
private val failed = mutableSetOf<String>()
private var receiverRegistered = false
@Volatile private var grab: Grab? = null
private var lastReader: Thread? = null
val active: Boolean get() = grab != null
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
Log.i(TAG, "USB mouse access ${if (granted) "granted" else "denied"}")
if (granted) listener.onChanged()
}
}
/**
* Returns whether the mouse is now read here, setting it up on the reader thread; asks for access once per
* plugged-in mouse. A mouse that fails setup after being claimed isn't tried again until it is replugged, since
* releasing it re-adds Android's mouse, which would start another attempt.
*/
fun grab(): Boolean {
if (grab != null) return true
val (device, mouse) = findMouse() ?: return false
if (device.deviceName in failed) return false
if (!usb.hasPermission(device)) {
if (asked.add(device.deviceName)) askPermission(device)
return false
}
val endpoint = (0 until mouse.endpointCount).map(mouse::getEndpoint).firstOrNull {
it.direction == UsbConstants.USB_DIR_IN && it.type == UsbConstants.USB_ENDPOINT_XFER_INT
} ?: return false
grab = Grab(device, mouse, endpoint, lastReader).also {
lastReader = it.thread
it.thread.start()
}
return true
}
/** Hands the mouse back to Android. */
fun release() {
val current = grab ?: return
grab = null
current.cancel()
}
fun close() {
release()
if (receiverRegistered) runCatching { context.unregisterReceiver(receiver) }
receiverRegistered = false
}
private fun findMouse(): Pair<UsbDevice, UsbInterface>? {
val androidMice = InputDevice.getDeviceIds().asList().mapNotNull { InputDevice.getDevice(it) }
.filter { !it.isVirtual && it.supportsSource(InputDevice.SOURCE_MOUSE) }
.map { it.vendorId to it.productId }.toSet()
return usb.deviceList.values.filter { (it.vendorId to it.productId) in androidMice }.firstNotNullOfOrNull { device ->
(0 until device.interfaceCount).map(device::getInterface).firstOrNull(::isBootMouse)?.let { device to it }
}
}
private fun askPermission(device: UsbDevice) {
if (!receiverRegistered) {
val filter = IntentFilter(permissionAction)
if (Build.VERSION.SDK_INT >= 33) context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
else context.registerReceiver(receiver, filter)
receiverRegistered = true
}
val flags = if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE else 0
val intent = PendingIntent.getBroadcast(context, 0, Intent(permissionAction).setPackage(context.packageName), flags)
runCatching { usb.requestPermission(device, intent) }.onFailure {
asked.remove(device.deviceName)
Log.w(TAG, "requestPermission", it)
}
}
private inner class Grab(
private val device: UsbDevice,
private val mouse: UsbInterface,
private val endpoint: UsbEndpoint,
private val previous: Thread?,
) {
@Volatile private var running = true
private val claimLock = Any()
val thread = Thread(::run, "usb-mouse")
/** Once this returns, the reader either never claims the interface or sees the cancellation after claiming. */
fun cancel() = synchronized(claimLock) { running = false }
// The reader owns the connection: closing it while a transfer is pending would free it under the transfer.
// A previous reader may still hold the interface, which would make this claim fail.
private fun run() {
runCatching { previous?.join() }
val connection = if (running) usb.openDevice(device) else null
if (connection == null) {
main.post { ended(markFailed = false) }
return
}
var claimed = false
var boot = false
try {
claimed = synchronized(claimLock) { running && connection.claimInterface(mouse, true) }
if (!claimed) {
main.post { ended(markFailed = false) }
return
}
if (!running) return
val format = setUp(connection)
if (format == null) {
main.post { ended(markFailed = true) }
return
}
boot = format === HidMouseReport.BOOT
if (!running) return
Log.i(TAG, String.format(java.util.Locale.ROOT, "reading USB mouse %04x:%04x \"%s\" directly (%s)",
device.vendorId, device.productId, device.productName, if (boot) "boot protocol" else "report ${format.reportId}"))
read(connection, format)
} finally {
if (claimed) {
if (boot) connection.controlTransfer(0x21, SET_PROTOCOL, HID_REPORT_PROTOCOL, mouse.id, null, 0, CONTROL_TIMEOUT_MS)
connection.releaseInterface(mouse)
}
connection.close()
}
}
/** HID 1.11 7.2.6: a host must not assume the protocol a device is in, so it is set either way. */
private fun setUp(connection: UsbDeviceConnection): HidMouseReport? {
val descriptor = ByteArray(1024)
val length = connection.controlTransfer(0x81, GET_DESCRIPTOR, HID_REPORT_DESCRIPTOR shl 8, mouse.id,
descriptor, descriptor.size, CONTROL_TIMEOUT_MS)
val parsed = if (length > 0) HidMouseReport.parse(descriptor.copyOf(length)) else null
if (parsed != null && running &&
connection.controlTransfer(0x21, SET_PROTOCOL, HID_REPORT_PROTOCOL, mouse.id, null, 0, CONTROL_TIMEOUT_MS) >= 0) return parsed
val boot = running &&
connection.controlTransfer(0x21, SET_PROTOCOL, HID_BOOT_PROTOCOL, mouse.id, null, 0, CONTROL_TIMEOUT_MS) >= 0
return HidMouseReport.BOOT.takeIf { boot }
}
private fun read(connection: UsbDeviceConnection, format: HidMouseReport) {
val report = ByteArray(maxOf(endpoint.maxPacketSize, 8))
var buttons = 0
var failures = 0
while (running) {
val started = SystemClock.uptimeMillis()
val length = connection.bulkTransfer(endpoint, report, report.size, READ_TIMEOUT_MS)
if (length <= 0) {
if (SystemClock.uptimeMillis() - started < READ_TIMEOUT_MS / 2 && ++failures >= MAX_FAILURES) {
main.post { lost() }
return
}
continue
}
failures = 0
val state = format.decode(report, length) ?: continue
val changed = buttons xor state.buttons
buttons = state.buttons
main.post { deliver(state, changed) }
}
}
private fun ended(markFailed: Boolean) {
if (grab !== this) return
if (markFailed) failed += device.deviceName
Log.i(TAG, "USB mouse \"${device.productName}\" could not be set up")
grab = null
}
private fun deliver(state: HidMouseReport.State, changed: Int) {
if (grab !== this) return
if (state.dx != 0 || state.dy != 0) listener.onMove(state.dx, state.dy)
for (i in 0 until BUTTONS) if (changed and (1 shl i) != 0) listener.onButton(i, state.buttons and (1 shl i) != 0)
if (state.wheel != 0) listener.onWheel(state.wheel)
}
private fun lost() {
if (grab !== this) return
failed += device.deviceName
Log.i(TAG, "USB mouse stopped responding")
grab = null
listener.onLost()
}
}
companion object {
private const val TAG = "UsbMouse"
private const val GET_DESCRIPTOR = 0x06
private const val SET_PROTOCOL = 0x0b
private const val HID_BOOT_PROTOCOL = 0
private const val HID_REPORT_PROTOCOL = 1
private const val HID_REPORT_DESCRIPTOR = 0x22
private const val SUBCLASS_BOOT = 1
private const val PROTOCOL_MOUSE = 2
private const val CONTROL_TIMEOUT_MS = 1000
private const val READ_TIMEOUT_MS = 100
private const val MAX_FAILURES = 5
private const val BUTTONS = 5
private fun isBootMouse(iface: UsbInterface) = iface.interfaceClass == UsbConstants.USB_CLASS_HID &&
iface.interfaceSubclass == SUBCLASS_BOOT && iface.interfaceProtocol == PROTOCOL_MOUSE
/**
* A process killed while reading a mouse leaves it with no driver until it is replugged. Claiming without
* force only succeeds when no driver has the interface, and releasing it reattaches Android's.
*/
fun returnLeftover(context: Context) {
Thread({
runCatching {
val usb = context.getSystemService(Context.USB_SERVICE) as UsbManager
for (device in usb.deviceList.values) {
if (!usb.hasPermission(device)) continue
val mouse = (0 until device.interfaceCount).map(device::getInterface).firstOrNull(::isBootMouse) ?: continue
val connection = usb.openDevice(device) ?: continue
if (connection.claimInterface(mouse, false)) {
connection.releaseInterface(mouse)
Log.i(TAG, "returned USB mouse \"${device.productName}\" to Android")
}
connection.close()
}
}.onFailure { Log.w(TAG, "returning a USB mouse to Android failed", it) }
}, "usb-mouse-return").start()
}
}
}
@@ -384,7 +384,7 @@ object BwrapSpawner {
val program = plan.argv.firstOrNull()?.takeIf { it.startsWith("/") }?.let(::host)?.canonicalFile
?.takeIf { it.isFile && isStaticElf(it) } ?: return null
if (!linkMounts(plan)) return null
return (listOf(program.path) + plan.argv.drop(1)) to plan.env
return (NativeGuest.execPrefix(program.path) + listOf(program.path) + plan.argv.drop(1)) to plan.env
}
val loader = SANDBOX_LOADERS.map(::host).firstOrNull { it.isFile }?.canonicalFile ?: return null
val libc = SANDBOX_LIBCS.map(::host).firstOrNull { it.isFile }?.canonicalFile ?: return null
@@ -411,13 +411,14 @@ object BwrapSpawner {
plan.env.map { (k, v) -> "$k=$v" } + plan.argv
val env = linkedMapOf(
"DDNATV_ROOT" to sandbox,
"DDNATV_EXEC" to NativeGuest.execLoader.orEmpty(),
"DDNATV_LINK_ROOT" to rootfs.path,
"DDNATV_BINDS" to plan.binds.joinToString("|") { "${it.host}:${it.guest}" },
"DDNATV_HOSTNAME" to SessionPrefs.guestHostname(context),
"LD_LIBRARY_PATH" to SANDBOX_LIB_DIRS.map(::host).filter { it.isDirectory }.joinToString(":") { it.path },
"LD_PRELOAD" to hook.path,
).filterValues { it.isNotEmpty() }
return (NativeGuest.simulator(rootfs)?.let { it + launch } ?: launch) to env
return (NativeGuest.simulator(rootfs)?.let { it + launch } ?: (NativeGuest.execPrefix(loader.path) + launch)) to env
}
private val runpathDirs = java.util.concurrent.ConcurrentHashMap<String, List<String>>()
@@ -542,7 +543,7 @@ object BwrapSpawner {
.also { b -> b.environment().apply { clear(); putAll(native.second) } }
} else {
val cmd = LinuxRuntime.prootPrefix(context, plan.root, plan.cwd)
if (verbose != null) { cmd.add(1, "-v"); cmd.add(2, verbose.toString()) }
if (verbose != null) { cmd.add("-v"); cmd.add(verbose.toString()) }
plan.binds.forEach { cmd.add("-b"); cmd.add(it.spec) }
val envTool = hasEnvTool(plan)
if (envTool) {
@@ -95,10 +95,13 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
permissionNotified = false
context.contentResolver.registerContentObserver(Settings.System.CONTENT_URI, true, observer)
requests.startWatching()
context.registerReceiver(volumeSteps, IntentFilter().apply {
val volumeFilter = IntentFilter().apply {
addAction(VOLUME_CHANGED_ACTION)
addAction(STREAM_MUTE_CHANGED_ACTION)
}, null, handler)
}
if (android.os.Build.VERSION.SDK_INT >= 33)
context.registerReceiver(volumeSteps, volumeFilter, null, handler, Context.RECEIVER_NOT_EXPORTED)
else context.registerReceiver(volumeSteps, volumeFilter, null, handler)
refresh.run()
}
}
@@ -58,7 +58,7 @@ object GuestCommand {
NativeGuest.processBuilder(context, root, binds, guest).redirectErrorStream(true)
} else {
val cmd = LinuxRuntime.prootPrefix(context, root, "/root", fakeRoot)
if (linkDir != null) cmd.add(1, "--link2symlink")
if (linkDir != null) cmd.add("--link2symlink")
binds.forEach { cmd.add("-b"); cmd.add(it) }
cmd += guest
ProcessBuilder(cmd).directory(root).redirectErrorStream(true).also { b ->
@@ -106,13 +106,15 @@ class LinuxNetworkLinkComponent(
synchronized(lock) { writeNetworkState(currentProperties, currentCapabilities) }
}
}
appContext.registerReceiver(receiver, IntentFilter().apply {
val wifiFilter = IntentFilter().apply {
addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
addAction(WifiManager.RSSI_CHANGED_ACTION)
addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION)
addAction(LocationManager.MODE_CHANGED_ACTION)
})
}
if (android.os.Build.VERSION.SDK_INT >= 33) appContext.registerReceiver(receiver, wifiFilter, Context.RECEIVER_NOT_EXPORTED)
else appContext.registerReceiver(receiver, wifiFilter)
wifiReceiver = receiver
scanRequestStamp = File(rootDir, "etc/droiddeck-wifi-scan-request").lastModified()
scanHandler.post(scanRequests)
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.runtime;
import com.droiddeck.launcher.core.AddonPack;
import android.content.Context;
import android.os.Build;
import android.os.Process;
import android.system.ErrnoException;
import android.system.Os;
@@ -77,7 +78,18 @@ public final class LinuxRuntime {
}
private static boolean rootfsProotReady(Context context) {
return rootfsProot(context).isFile() && rootfsLoader(context).isFile();
return Build.VERSION.SDK_INT < 29 && rootfsProot(context).isFile() && rootfsLoader(context).isFile();
}
/** proot execs its loader, and targetSdk 29+ may exec only the APK's libraries, which hold the pack's matching loader. */
public static boolean stockProotAllowed(Context context) {
return Build.VERSION.SDK_INT < 29 && SessionPrefs.allowStockProot(context);
}
/** Android 10+ refuses to execute files from app data for targetSdk 29+, but executes the APK's extracted libraries. */
private static File bundledLoader(Context context) {
File file = new File(context.getApplicationInfo().nativeLibraryDir, "libproot-loader.so");
return file.isFile() ? file : null;
}
public static boolean patchedProot(Context context) {
@@ -86,22 +98,21 @@ public final class LinuxRuntime {
public static File prootBinary(Context context) {
if (AddonPack.PROOT.installed(context)) return AddonPack.PROOT.file(context, "libproot.so");
if (SessionPrefs.allowStockProot(context)) return rootfsProot(context);
if (stockProotAllowed(context)) return rootfsProot(context);
return AddonPack.PROOT.file(context, "libproot.so");
}
public static File prootLoader(Context context) {
if (AddonPack.PROOT.installed(context)) return AddonPack.PROOT.file(context, "libproot-loader.so");
if (SessionPrefs.allowStockProot(context)) return rootfsLoader(context);
return AddonPack.PROOT.file(context, "libproot-loader.so");
File bundled = bundledLoader(context);
if (AddonPack.PROOT.installed(context)) return bundled != null ? bundled : AddonPack.PROOT.file(context, "libproot-loader.so");
if (stockProotAllowed(context)) return rootfsLoader(context);
return bundled != null ? bundled : AddonPack.PROOT.file(context, "libproot-loader.so");
}
public static String prootSource(Context context) {
File bin = prootBinary(context);
if (!bin.isFile()) return PROOT_MISSING;
if (AddonPack.PROOT.installed(context)
&& bin.getPath().equals(AddonPack.PROOT.file(context, "libproot.so").getPath())) return PROOT_PACK;
return PROOT_ROOTFS;
return patchedProot(context) && !bin.equals(rootfsProot(context)) ? PROOT_PACK : PROOT_ROOTFS;
}
public static String prootLibraryPath(Context context) {
@@ -183,13 +194,13 @@ public final class LinuxRuntime {
public static List<String> rootPrefix(Context context, File root, String cwd) {
List<String> cmd = prootPrefix(context, root, cwd, true);
cmd.add(1, "--link2symlink");
cmd.add("--link2symlink");
return cmd;
}
public static List<String> prootPrefix(Context context, File root, String cwd, boolean fakeRoot) {
List<String> cmd = new ArrayList<>();
cmd.add(prootBinary(context).getPath());
cmd.addAll(com.droiddeck.launcher.core.HostProcess.dataExecutable(prootBinary(context).getPath()));
cmd.add("--kill-on-exit");
cmd.add("--kernel-release=" + guestUtsname(SessionPrefs.guestHostname(context)));
int uid = Process.myUid();
@@ -70,6 +70,7 @@ public final class LinuxRuntimeInstaller {
volatile Step step = Step.OTHER;
volatile int percent = -1;
volatile boolean ok;
volatile String failure;
final boolean removal;
boolean maintenance;
Job(boolean removal, String stage) { this.removal = removal; this.stage = stage; }
@@ -78,6 +79,9 @@ public final class LinuxRuntimeInstaller {
private static final Object JOB_LOCK = new Object();
private static Job running;
private static volatile String removalError;
private static final ThreadLocal<Job> LAST_INSTALL = new ThreadLocal<>();
private static final ThreadLocal<Job> CURRENT_INSTALL = new ThreadLocal<>();
private static final ThreadLocal<String> CATALOG_ERROR = new ThreadLocal<>();
private LinuxRuntimeInstaller() {}
@@ -105,34 +109,66 @@ public final class LinuxRuntimeInstaller {
}
public static Release fetchRelease() {
String body = Downloader.downloadString(catalogUrl());
if (body == null || body.isEmpty()) return null;
return fetchRelease(catalogUrl());
}
public static String catalogError() { return CATALOG_ERROR.get(); }
static Release fetchRelease(String catalogUrl) {
CATALOG_ERROR.remove();
String body = Downloader.downloadString(catalogUrl);
if (body == null) return catalogFailed(Downloader.lastFailure());
if (body.isEmpty()) return catalogFailed("empty catalog");
try {
JSONObject json = new JSONObject(body);
String version = json.optString("version", "");
String url = json.optString("url", "");
String sha256 = json.optString("sha256", "");
if (version.isEmpty() || url.isEmpty() || sha256.isEmpty()) return null;
if (version.isEmpty() || url.isEmpty() || sha256.isEmpty()) {
return catalogFailed("catalog lacks version, url or sha256");
}
return new Release(version, url, sha256, json.optLong("size", 0L));
} catch (Exception e) {
Log.w(TAG, "catalog: " + e);
return null;
return catalogFailed("invalid catalog: " + e);
}
}
private static Release catalogFailed(String reason) {
CATALOG_ERROR.set(reason);
Log.w(TAG, "catalog: " + reason);
return null;
}
private static final String USER_DATA = "root";
public static boolean install(Context context, Release release, ProgressListener listener) {
Job job;
boolean owner;
synchronized (JOB_LOCK) {
if (running != null && (running.removal || running.maintenance)) return false;
if (running != null && (running.removal || running.maintenance)) {
Job rejected = new Job(false, null);
rejected.failure = running.removal ? "Runtime busy: removal in progress" : "Runtime busy: maintenance in progress";
Log.w(TAG, rejected.failure);
LAST_INSTALL.set(rejected);
return false;
}
owner = running == null;
if (owner) { running = new Job(false, context.getString(R.string.user_apps_starting)); removalError = null; }
job = running;
if (listener != null) job.listeners.add(listener);
}
if (!owner) return join(job, listener);
if (!owner) {
Boolean ok = await(job, listener);
if (ok != null) {
LAST_INSTALL.set(job);
return ok;
}
Job interrupted = new Job(false, null);
interrupted.failure = "Runtime install interrupted while waiting for the running install";
LAST_INSTALL.set(interrupted);
return false;
}
CURRENT_INSTALL.set(job);
try {
Context app = context.getApplicationContext();
ProgressListener progress = new ProgressListener() {
@@ -156,9 +192,10 @@ public final class LinuxRuntimeInstaller {
if (job.ok && desktop) keepDesktop(app, progress);
return job.ok;
} finally {
synchronized (JOB_LOCK) {
running = null;
}
CURRENT_INSTALL.remove();
LAST_INSTALL.set(job);
synchronized (JOB_LOCK) { running = null; }
if (listener != null) job.listeners.remove(listener);
job.done.countDown();
}
}
@@ -247,6 +284,21 @@ public final class LinuxRuntimeInstaller {
public static String removalError() { return removalError; }
public static String installError() {
Job job = LAST_INSTALL.get();
return job == null ? null : job.failure;
}
private static boolean fail(String step, String detail) {
String reason = detail == null || detail.isEmpty() ? step : step + ": " + detail;
Job job = CURRENT_INSTALL.get();
if (job != null) job.failure = reason;
Log.w(TAG, reason);
return false;
}
private static final String SWAP_FAILED = "Cannot replace the previous runtime";
public static boolean hasRemovalPending(Context context) {
return removalDirectory(LinuxRuntime.rootDir(context)).exists();
}
@@ -266,13 +318,17 @@ public final class LinuxRuntimeInstaller {
}
private static boolean join(Job job, ProgressListener listener) {
return Boolean.TRUE.equals(await(job, listener));
}
private static Boolean await(Job job, ProgressListener listener) {
try {
if (listener != null) listener.onProgress(job.step, job.stage, job.percent);
job.done.await();
return job.ok;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
return null;
} finally {
if (listener != null) job.listeners.remove(listener);
}
@@ -328,9 +384,10 @@ public final class LinuxRuntimeInstaller {
String downloading = context.getString(R.string.rtinst_downloading);
if (listener != null) listener.onProgress(Step.DOWNLOADING, downloading, 0);
if (!LinuxRuntime.patchedProot(context) && !AddonPack.PROOT.await(context, () -> true, packProgress(listener, downloading))
&& !SessionPrefs.allowStockProot(context))
throw new IOException("Cannot download proot");
if (!AddonPack.DIRECTAUDIO.await(context, () -> true, packProgress(listener, downloading))) throw new IOException("Cannot download DirectAudio");
&& !LinuxRuntime.stockProotAllowed(context))
return fail("Cannot download proot", AddonPack.PROOT.getFailure());
if (!AddonPack.DIRECTAUDIO.await(context, () -> true, packProgress(listener, downloading)))
return fail("Cannot download DirectAudio", AddonPack.DIRECTAUDIO.getFailure());
boolean ok = Downloader.downloadFile(release.url, archive, true, release.sha256, (fraction) -> {
if (listener != null) {
listener.onProgress(Step.DOWNLOADING, downloading,
@@ -338,39 +395,36 @@ public final class LinuxRuntimeInstaller {
}
});
if (!ok) {
Log.w(TAG, "download failed");
keepPartial = true;
return false;
return fail("Cannot download the runtime", Downloader.lastFailure());
}
if (listener != null) listener.onProgress(Step.VERIFYING, context.getString(R.string.rtinst_verifying), -1);
String actual = Hashes.sha256(archive);
if (!release.sha256.equalsIgnoreCase(actual)) {
Log.w(TAG, "checksum mismatch: wanted " + release.sha256 + ", got " + actual);
return false;
}
if (!release.sha256.equalsIgnoreCase(actual))
return fail("Runtime checksum mismatch", "wanted " + release.sha256 + ", got " + actual);
File root = LinuxRuntime.rootDir(context);
File staging = new File(root.getParentFile(), LinuxRuntime.DIR + ".new");
File old = new File(root.getParentFile(), LinuxRuntime.DIR + ".old");
recoverInterruptedSwap(root, staging, old);
if (!discard(staging, null) || !staging.mkdirs()) return false;
if (!discard(staging, null) || !staging.mkdirs()) return fail("Cannot prepare " + staging.getName(), null);
if (listener != null) listener.onProgress(context.getString(R.string.rtinst_extracting), -1);
if (!extract(context, archive, staging, root, listener)) {
RuntimeFileTree.delete(staging, null);
return false;
return fail("Cannot unpack the runtime", null);
}
FileUtils.writeString(new File(staging, VERSION_FILE), release.version);
if (!discard(old, null)) {
discard(staging, null);
return false;
return fail(SWAP_FAILED, null);
}
java.util.List<String> carryPaths = root.isDirectory()
? RuntimeFileTree.existingUserPaths(root, staging) : java.util.Collections.emptyList();
if (root.isDirectory() && !root.renameTo(old)) {
RuntimeFileTree.delete(staging, null);
return false;
return fail(SWAP_FAILED, null);
}
File carryMarker = new File(staging, CARRY_MARKER);
java.util.List<String> encodedPaths = new java.util.ArrayList<>();
@@ -379,7 +433,7 @@ public final class LinuxRuntimeInstaller {
if (old.isDirectory() && !old.renameTo(root))
Log.w(TAG, "could not restore the previous runtime; retained at " + old);
discard(staging, null);
return false;
return fail(SWAP_FAILED, null);
}
java.util.List<String> carried;
@@ -396,7 +450,7 @@ public final class LinuxRuntimeInstaller {
} else {
Log.w(TAG, "incomplete rollback; retaining user data in " + staging);
}
return false;
return fail("Cannot carry user data into the new runtime", e.getMessage());
}
if (!staging.renameTo(root)) {
@@ -407,7 +461,7 @@ public final class LinuxRuntimeInstaller {
} catch (IOException e) { Log.w(TAG, "could not move all user data back after a failed swap", e); }
old.renameTo(root);
}
return false;
return fail(SWAP_FAILED, null);
}
new File(root, CARRY_MARKER).delete();
try { RuntimeFileTree.dropStaleState(root); }
@@ -415,10 +469,10 @@ public final class LinuxRuntimeInstaller {
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);
return LinuxRuntime.isInstalled(context) || fail("The runtime is incomplete after unpacking", null);
} catch (Exception e) {
Log.e(TAG, "install", e);
return false;
return fail("Install stopped", e.toString());
} finally {
if (!keepPartial) archive.delete();
}
@@ -50,6 +50,21 @@ object NativeGuest {
fun hook(root: File): File = File(root, HOOK)
/**
* libddexec.so, which starts the rootfs loader on Android 10+, where a targetSdk 29+ app may not
* execute its data files; null where the kernel still starts them directly.
*/
@Volatile var execLoader: String? = null
private set
/** What starts the program at [path] from the host: nothing before it, or [execLoader] and the path. */
fun execPrefix(path: String): List<String> = execLoader?.let { listOf(it, path) }.orEmpty()
fun init(context: Context) {
execLoader = File(context.applicationInfo.nativeLibraryDir, "libddexec.so")
.takeIf { android.os.Build.VERSION.SDK_INT >= 29 && it.isFile }?.path
}
fun loader(root: File): File? =
listOf("usr/lib/ld-linux-aarch64.so.1", "lib/ld-linux-aarch64.so.1").map { File(root, it) }.firstOrNull { it.exists() }
@@ -60,9 +75,10 @@ object NativeGuest {
/** Environment every native process starts with; a guest `env -i` is re-seeded by the hook. */
fun environment(root: File, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf(
"DDNATV_ROOT" to root.path,
"DDNATV_EXEC" to execLoader.orEmpty(),
"LD_LIBRARY_PATH" to libraryPath(root),
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
)
).filterValues { it.isNotEmpty() }
/**
* The host command line for the guest program at [program] (an absolute guest path to a real
@@ -72,7 +88,7 @@ object NativeGuest {
val loader = checkNotNull(loader(root)) { "no glibc loader in ${root.path}" }
val host = File(root, program.removePrefix("/"))
val launch = listOf(loader.path, "--argv0", host.name, host.path) + args
return simulator(root)?.let { it + launch } ?: launch
return simulator(root)?.let { it + launch } ?: (execPrefix(loader.path) + launch)
}
/** The environment of the session process: the hook's root, the mounts proot used to make, the preload list. */
@@ -80,6 +96,7 @@ object NativeGuest {
val preload = preloadList(root)
return linkedMapOf(
"DDNATV_ROOT" to root.path,
"DDNATV_EXEC" to execLoader.orEmpty(),
"DDNATV_HOSTNAME" to hostname.orEmpty(),
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
"DDNATV_PRELOAD" to preload.joinToString(":"),
@@ -11,6 +11,8 @@ import kotlin.math.abs
class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart() {
@Volatile private var running = false
private var thread: Thread? = null
private val runtimeEstimator = BatteryRuntimeEstimator()
private var lastDischarging: Boolean? = null
override fun start() {
File(dir, "BAT0").deleteRecursively()
@@ -49,11 +51,17 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
val currentAvgUa = toMicroamps(bm?.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE)?.takeIf { it != Long.MIN_VALUE && it != 0L } ?: 0L)
.takeIf { it != 0L } ?: currentNowUa
val discharging = status == BatteryManager.BATTERY_STATUS_DISCHARGING || status == BatteryManager.BATTERY_STATUS_NOT_CHARGING
if (lastDischarging != null && lastDischarging != discharging) runtimeEstimator.reset()
lastDischarging = discharging
val currentForRuntimeUa = currentNowUa.takeIf { it != 0L } ?: currentAvgUa
val chargeFullUah = if (chargeNowUah > 0 && pct > 0) chargeNowUah * 100 / pct else 0L
val energyNowUwh = chargeNowUah * voltageUv / 1_000_000L
val energyFullUwh = chargeFullUah * voltageUv / 1_000_000L
val powerNowUw = abs(currentNowUa) * voltageUv / 1_000_000L
val timeToEmptyS = if (discharging && chargeNowUah > 0 && abs(currentAvgUa) > 0) chargeNowUah * 3600L / abs(currentAvgUa) else 0L
val runtimeHours = if (discharging)
runtimeEstimator.estimateHours(chargeNowUah.toDouble(), currentForRuntimeUa.toDouble())
else null
val timeToEmptyS = BatteryRuntimeEstimator.secondsFromHours(runtimeHours)
val charging = status == BatteryManager.BATTERY_STATUS_CHARGING
val timeToFullS = if (charging && chargeFullUah > chargeNowUah && abs(currentAvgUa) > 0) (chargeFullUah - chargeNowUah) * 3600L / abs(currentAvgUa) else 0L
val statusText = when (status) {
@@ -126,9 +134,7 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
companion object {
private const val TAG = "SessionService"
private const val MILLIAMP_CEILING = 10_000L
internal fun toMicroamps(raw: Long): Long = if (abs(raw) < MILLIAMP_CEILING) raw * 1000L else raw
internal fun toMicroamps(raw: Long): Long = BatteryRuntimeEstimator.toMicroamps(raw)
private const val PERIOD_MS = 5_000L
private val VPOWER_FILES = listOf(
"ac_status", "battery_percent", "battery_status",
@@ -0,0 +1,74 @@
package com.droiddeck.launcher.session
import java.util.ArrayDeque
import kotlin.math.abs
import kotlin.math.roundToLong
class BatteryRuntimeEstimator {
private val currentSamples = ArrayDeque<Double>()
@Synchronized
fun reset() {
currentSamples.clear()
}
@Synchronized
fun estimateHours(chargeNowUah: Double, currentSampleUa: Double): Double? {
if (currentSampleUa.isFinite() && currentSampleUa != 0.0) {
currentSamples.addLast(abs(currentSampleUa))
while (currentSamples.size > MAX_SAMPLES) currentSamples.removeFirst()
}
if (!chargeNowUah.isFinite() || chargeNowUah <= 0.0 || currentSamples.isEmpty()) return null
var sum = 0.0
for (sample in currentSamples) sum += sample
val averageCurrentUa = sum / currentSamples.size
if (!averageCurrentUa.isFinite() || averageCurrentUa <= 0.0) return null
val hours = chargeNowUah / averageCurrentUa
return hours.takeIf { it.isFinite() && it > 0.0 }
}
companion object {
private const val MAX_SAMPLES = 25
private const val MILLIAMP_CEILING = 10_000L
@JvmStatic
fun toMicroamps(raw: Long): Long {
if (raw == Long.MIN_VALUE) return 0L
return if (abs(raw) < MILLIAMP_CEILING) raw * 1_000L else raw
}
@JvmStatic
fun chargeMicroampHoursFromEnergy(energyUwh: Double, voltageUv: Double): Double? {
if (!energyUwh.isFinite() || energyUwh <= 0.0 || !voltageUv.isFinite() || voltageUv <= 0.0) return null
return (energyUwh * 1_000_000.0 / voltageUv).takeIf { it.isFinite() && it > 0.0 }
}
@JvmStatic
fun currentMicroampsFromPower(powerUw: Double, voltageUv: Double): Double? {
if (!powerUw.isFinite() || voltageUv <= 0.0 || !voltageUv.isFinite()) return null
return (abs(powerUw) * 1_000_000.0 / voltageUv).takeIf { it.isFinite() && it > 0.0 }
}
@JvmStatic
fun secondsFromHours(hours: Double?): Long {
if (hours == null || !hours.isFinite() || hours <= 0.0) return 0L
val seconds = hours * 3_600.0
return if (seconds.isFinite() && seconds < Long.MAX_VALUE.toDouble()) seconds.toLong() else 0L
}
@JvmStatic
fun formatDuration(hours: Double?): String? {
if (hours == null || !hours.isFinite() || hours <= 0.0) return null
val totalMinutes = (hours * 60.0).roundToLong().coerceAtLeast(1L)
val wholeHours = totalMinutes / 60L
val minutes = totalMinutes % 60L
val hourUnit = if (wholeHours == 1L) "hr" else "hrs"
val minuteUnit = if (minutes == 1L) "min" else "mins"
return when {
wholeHours > 0L && minutes > 0L -> "$wholeHours $hourUnit $minutes $minuteUnit"
wholeHours > 0L -> "$wholeHours $hourUnit"
else -> "$minutes $minuteUnit"
}
}
}
}
@@ -15,6 +15,7 @@ object BootMovie {
const val DROIDDECK_30 = "dd30"
const val DROIDDECK_60 = "dd60"
const val CUSTOM = "custom"
private const val SKIP = "skip"
const val MAX_BYTES = 50L shl 20
const val MAX_CONVERT_SECONDS = 60
val PICKER_EXTENSIONS = listOf("webm", "mkv", "mp4", "mov", "m4v", "3gp")
@@ -22,6 +23,7 @@ object BootMovie {
private val ASSETS = mapOf(
DROIDDECK_30 to "droiddeck-startup.webm",
DROIDDECK_60 to "droiddeck-startup-60.webm",
SKIP to "skip-startup.webm",
)
internal val VIDEO_CODECS = setOf(MediaFormat.MIMETYPE_VIDEO_VP8, MediaFormat.MIMETYPE_VIDEO_VP9, MediaFormat.MIMETYPE_VIDEO_AV1)
@@ -74,6 +76,7 @@ object BootMovie {
fun prepare(context: Context): File? {
BootMovieLibrary.restore(context)
if (SessionPrefs.skipBootMovie(context)) return assetFile(context, SKIP)
val source = sourceOf(context, choice(context)) ?: return null
return variant(context, source)
}
@@ -147,8 +150,37 @@ object BootMovie {
folder.listFiles()?.forEach { if (it.name != keep) it.delete() }
}
internal fun syncShuffleFromSteam(context: Context, config: File) = syncShuffleFromSteam(context, listOf(config))
// Staging writes Shuffle and its baseline under the same lock, so a poll never reads a half-staged value as Steam's.
internal fun syncShuffleFromSteam(context: Context, configs: List<File>) = synchronized(SessionFiles.STEAM_CONFIG) {
val read = configs.mapNotNull { config -> SessionFiles.startupMovieShuffle(config)?.let { config to it } }
val (known, unseen) = read.partition { (config, _) -> SessionPrefs.bootMovieShuffleSeen(context, config) != null }
var changed = false
known.forEach { (config, steam) ->
if (SessionPrefs.bootMovieShuffleSeen(context, config) != steam) {
SessionPrefs.setBootMovieShuffle(context, steam)
changed = true
}
SessionPrefs.setBootMovieShuffleSeen(context, config, steam)
}
// A config read for the first time only sets the choice when no known config changed, so it cannot undo a change.
unseen.forEach { (config, steam) ->
if (!changed && SessionPrefs.bootMovieShuffle(context) != steam) {
SessionPrefs.setBootMovieShuffle(context, steam)
changed = true
}
SessionPrefs.setBootMovieShuffleSeen(context, config, steam)
}
}
fun syncFromSteam(context: Context): Boolean {
val named = SessionFiles.startupMovieLocalPath(BootMovieLibrary.steamConfig(context)) ?: return false
val active = BootMovieLibrary.steamConfig(context)
syncShuffleFromSteam(
context,
BootMovieLibrary.steamRoots(context).map { File(it, "config/config.vdf") }.filter { it != active } + active,
)
val named = SessionFiles.startupMovieLocalPath(active) ?: return false
val seen = SessionPrefs.bootMovieSteamSeen(context)
if (named == seen) return false
SessionPrefs.setBootMovieSteamSeen(context, named)
@@ -67,7 +67,7 @@ object BootMovieReport {
line("== DroidDeck state")
line("choice=${BootMovie.choice(context)} saved choice=${SessionPrefs.bootMovie(context)} pending pick=${SessionPrefs.bootMovieApplyNext(context)}")
line("last Steam path seen=${SessionPrefs.bootMovieSteamSeen(context)}")
line("sound=${SessionPrefs.bootMovieSound(context)} volume=${SessionPrefs.bootMovieVolume(context)} seconds=${SessionPrefs.bootMovieSeconds(context)}")
line("sound=${SessionPrefs.bootMovieSound(context)} volume=${SessionPrefs.bootMovieVolume(context)} seconds=${SessionPrefs.bootMovieSeconds(context)} skip=${SessionPrefs.skipBootMovie(context)}")
line("session running=${SessionState.running}")
line()
line("== The movie list as shown")
@@ -194,7 +194,7 @@ object BottomDesktop {
send(target, Message.obtain(null, Comp.MSG_POINTER, x, y))
}
/** Button (3), wheel (4) and smooth-scroll (12) input, as `WaylandCompositor.nativeSendSceneInput` takes it. */
/** Button, wheel and finger-scroll input, using the `WaylandCompositor.SCENE_*` types `nativeSendSceneInput` takes. */
fun sendScene(type: Int, a: Int, b: Int = 0) {
val target = service ?: return
send(target, Message.obtain(null, Comp.MSG_SCENE, type, a).apply {
@@ -0,0 +1,26 @@
package com.droiddeck.launcher.session
internal class BrowserHandoff(private val timeoutMs: Long) {
private var startedAt = -1L
private var sessionLeft = false
fun begin(now: Long) {
startedAt = now
sessionLeft = false
}
fun sessionHidden() {
if (startedAt >= 0) sessionLeft = true
}
fun sessionShown() {
if (sessionLeft) clear()
}
fun clear() {
startedAt = -1L
sessionLeft = false
}
fun active(now: Long): Boolean = startedAt >= 0 && now - startedAt < timeoutMs
}
@@ -8,6 +8,7 @@ import android.os.Process
import android.system.Os
import android.system.OsConstants
import android.util.Log
import com.droiddeck.launcher.gpu.SocNames
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import kotlin.math.abs
@@ -26,13 +27,14 @@ object GameThreadHints {
private const val PACE_TOLERANCE = 0.08
private val NOT_GAMES = setOf("steam", "steamwebhelper")
private val SOCS = setOf("CQ8725S", "SM8750")
private var worker: Thread? = null
@Synchronized
fun start(context: Context): String {
if (!SessionPrefs.gameThreadHints(context)) return "game thread hints: off"
if (Build.VERSION.SDK_INT < 31 || Build.SOC_MODEL != "CQ8725S") return "game thread hints: Odin 3 only"
if (Build.VERSION.SDK_INT < 31 || !supported(Build.SOC_MODEL)) return "game thread hints: Snapdragon 8 Elite only"
val hm = context.getSystemService(PerformanceHintManager::class.java)
?: return "game thread hints: no PerformanceHintManager"
val pm = context.getSystemService(PowerManager::class.java)
@@ -99,6 +101,8 @@ object GameThreadHints {
}
}
internal fun supported(soc: String): Boolean = SocNames.normalizedModel(soc) in SOCS
internal fun holdsPace(fps: Double, refreshHz: Double): Boolean =
fps >= 10 && refreshHz > 0 && (1..4).any { k -> abs(fps - refreshHz / k) < PACE_TOLERANCE * refreshHz / k }
@@ -60,17 +60,19 @@ object GraphicsReport {
appendLine("-- path")
appendLine("path: " + path(context))
appendLine("driver mode: " + SessionPrefs.gpuDriverMode(context))
appendLine("display driver (compositor): " + SessionPrefs.androidDriver(context).ifEmpty {
if (DeviceSupport.adreno()) "(auto: bundled Turnip)" else "(auto: the phone's own Vulkan driver, ${SystemVulkanDriver.hal() ?: "vendor HAL"})"
})
val display = SessionPrefs.androidDriver(context)
val shown = com.droiddeck.launcher.gpu.TurnipDriver(context).effectiveId()
appendLine("display driver (compositor): " +
(if (shown == "system") "the phone's own Vulkan driver, ${SystemVulkanDriver.hal() ?: "vendor HAL"}" else shown) +
if (display.isEmpty()) " (auto)" else if (display != shown) " (picked $display, not used)" else "")
appendLine("display driver chosen by: " + when {
display.isEmpty() -> "auto (or a pair on a non-Adreno GPU: the phone's own driver)"
DriverBundle.containing(context, display, false) != null -> "pair (its display half)"
else -> "user (picked on its own)"
})
val linux = SessionPrefs.linuxDriver(context)
appendLine("runtime driver: " + linux.ifEmpty { "(runtime default)" })
appendLine("runtime driver: " + (com.droiddeck.launcher.gpu.DeviceInfo.hostRoute(context)
?.let { "$it (picked ${linux.ifEmpty { "runtime default" }}, not used)" } ?: linux.ifEmpty { "(runtime default)" }))
if (linux.isNotEmpty()) {
val dir = com.droiddeck.launcher.gpu.LinuxVulkanDriverManager(context).getDriverDir(linux)
appendLine("runtime driver dir: ${dir.path} (" + (dir.listFiles()?.filter { it.name.endsWith(".so") }?.joinToString { it.name } ?: "missing") + ")")
@@ -161,8 +163,8 @@ object GraphicsReport {
private fun read(path: String): String? = FileUtils.readString(File(path))?.trim()?.takeIf { it.isNotEmpty() }
/** The compositor's driver lines from the app's own log. */
private val COMPOSITOR = Regex(
"""vk_present|waylandcomp|vk_loader|compositor|vkCreateDevice|extension|adrenotools|TurnipDriver|""" +
internal val COMPOSITOR = Regex(
"""vk_present|waylandcomp|vk_loader|compositor|vkCreateDevice|extension|adrenotools|hook_impl|TurnipDriver|""" +
"""graphics driver|display driver|DD_PRESENT_FAULT|SystemVulkan|vkbridge|VkBridge|mali_gralloc|panvk|PanVK|radv|MESA|native buffer|first frame|present|""" +
"""lsfg|FrameGen|device gates|AAudio|directaudio|pulse|gralloc|dma.?buf|modifier|import""",
RegexOption.IGNORE_CASE,
@@ -49,9 +49,14 @@ object NoSteamLaunch {
return com.droiddeck.launcher.core.GameResolution.resolve(choice, output)
}
fun needsAddedGame(game: Library.SteamGame): Boolean = game.library == Library.ADDED && !viaBattleNet(game)
private fun viaBattleNet(game: Library.SteamGame): Boolean =
game.library == Library.ADDED && game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id
fun command(game: Library.SteamGame, added: AddedGames.Game?): Command? = when {
game.library == Library.EPIC_LAUNCHER -> Command(EPIC, listOf("run"), game.name)
game.library == Library.ADDED && game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id ->
viaBattleNet(game) ->
game.storeId?.let(com.droiddeck.launcher.runtime.BattleNet::title)?.let { Command(BATTLENET, listOf("launch", it.code), game.name) }
game.library == Library.ADDED -> added?.let { a -> a.steamAppId?.let { Command(PROTON_RUN, listOf("--app", it.toString()), a.name) } ?: addedCommand(a) }
game.appId > 0 -> Command(PROTON_RUN, listOf("--app", game.appId.toString()), game.name)
@@ -70,7 +75,7 @@ object NoSteamLaunch {
fun addedGame(context: Context, game: Library.SteamGame): AddedGames.Game? {
val id = game.appId.toLong() and 0xFFFFFFFFL
val one = game.gameFiles?.let { AddedGames.single(context, it.path) }
val one = game.gameFiles?.let { AddedGames.single(context, it.path, reuse = true) }
return one?.takeIf { settingsId(it) == id } ?: AddedGames.scan(context).firstOrNull { settingsId(it) == id }
}
@@ -11,6 +11,7 @@ import android.view.Display
object PerfMode {
private const val TAG = "PerfMode"
const val BFI_MIN_REFRESH_HZ = 100f
fun apply(a: Activity, fpsLimit: Int = 0, refreshLimit: Int = 0): String {
val parts = ArrayList<String>(2)
@@ -19,6 +19,7 @@ import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.JoyCon
import com.droiddeck.launcher.input.PadBridge
import java.io.DataInputStream
import java.io.File
import kotlin.math.max
class RumbleComponent : SessionPart() {
@@ -39,6 +40,10 @@ class RumbleComponent : SessionPart() {
internal var controllerMotors: (Int) -> Motors? = ::lookupController
internal var motorLooper: Looper? = null
internal var processStart: (Int) -> String? = ::readProcessStart
internal var gameRunning: () -> Boolean = { SteamGameProcess.running() }
private var gameCheckedAt = Long.MIN_VALUE
private var gameLastSeen = false
@Synchronized private fun refreshEnabled() {
enabled = app()?.let { ControllerPrefs.rumbleEnabled(it) } == true
@@ -66,7 +71,9 @@ class RumbleComponent : SessionPart() {
try {
val bytes = ByteArray(8)
DataInputStream(client.inputStream).readFully(bytes)
buzz(u16(bytes, 0), u16(bytes, 2), u16(bytes, 4), u16(bytes, 6))
val peer = runCatching { client.peerCredentials }.getOrNull()
buzz(u16(bytes, 0), u16(bytes, 2), u16(bytes, 4), u16(bytes, 6), peer?.pid ?: 0,
peer?.uid == android.os.Process.myUid())
} catch (e: Exception) {
} finally {
try { client.close() } catch (e: Exception) { }
@@ -94,7 +101,9 @@ class RumbleComponent : SessionPart() {
private fun u16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8)
@Synchronized private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int) {
private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int) = buzz(strong, weak, ms, slot, 0, false)
@Synchronized private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int, sender: Int, ownUser: Boolean) {
if (!enabled || quiet) return
val target = target(slot)
val previous = playing[slot]
@@ -105,10 +114,19 @@ class RumbleComponent : SessionPart() {
target?.let { Log.i(TAG, "rumble: slot $slot playing on ${it.name}") }
}
if (target == null) return
if ((strong == 0 && weak == 0) || ms == 0) { target.cancel(); forget(slot); return }
if ((strong == 0 && weak == 0) || ms == 0) {
val from = effects[slot]?.from ?: 0
if (sender > 0 && from > 0 && from != sender) return
target.cancel()
forget(slot)
return
}
val handler = handler ?: return
val effect = effects.getOrPut(slot) { Effect(slot) }
val held = effect.hold
effect.want(strong, weak, ms)
effect.from = sender
if (effect.hold && (!held || effect.owner != sender)) effect.claim(sender, ownUser)
val now = SystemClock.uptimeMillis()
if (effect.playing(now)) return
handler.removeCallbacks(effect)
@@ -116,19 +134,37 @@ class RumbleComponent : SessionPart() {
if (wait > 0) handler.postDelayed(effect, wait) else play(effect)
}
@Synchronized private fun play(effect: Effect) {
@Synchronized private fun play(effect: Effect, keepalive: Boolean = false) {
val target = playing[effect.slot]
if (target == null || effects[effect.slot] !== effect) return
if (keepalive && effect.hold && effect.armed) effect.orphaned()?.let { why ->
Log.i(TAG, "rumble: slot ${effect.slot} stopped, $why")
target.cancel()
forget(effect.slot)
return
}
val duration = if (effect.hold) HOLD_EFFECT_MS else effect.ms.toLong().coerceIn(1L, 5000L)
try {
target.play(effect.strong, effect.weak, duration)
effect.played(SystemClock.uptimeMillis(), duration)
if (effect.hold) handler?.postDelayed(effect, KEEPALIVE_MS)
if (effect.hold) {
effect.armed = true
handler?.postDelayed(effect, KEEPALIVE_MS)
}
} catch (e: Exception) {
Log.w(TAG, "rumble: ${target.name}: $e")
}
}
private fun gameRecently(): Boolean {
val now = SystemClock.uptimeMillis()
if (!gameLastSeen || now - gameCheckedAt >= GAME_CHECK_MS) {
gameLastSeen = gameRunning()
gameCheckedAt = now
}
return gameLastSeen
}
private fun forget(slot: Int) {
effects.remove(slot)?.let { handler?.removeCallbacks(it) }
}
@@ -170,8 +206,32 @@ class RumbleComponent : SessionPart() {
private var playedWeak = 0
private var playedMs = 0
private var until = 0L
var owner = 0
var from = 0
private var ownerSeen = false
private var ownerStart: String? = null
private var duringGame = false
var armed = false
val hold get() = ms == HOLD_MS
fun claim(sender: Int, ownUser: Boolean) {
owner = sender
val start = if (sender > 0) processStart(sender) else null
ownerSeen = sender > 0 && (start != null || ownUser)
ownerStart = start?.takeIf { it != UNKNOWN_START }
duringGame = gameRecently()
armed = false
}
fun orphaned(): String? {
if (ownerSeen) {
val start = processStart(owner)
if (start == null || (ownerStart != null && start != UNKNOWN_START && start != ownerStart))
return "process $owner that started it is gone"
}
return if (duringGame && !gameRunning()) "the game it started in has exited" else null
}
fun want(strong: Int, weak: Int, ms: Int) { this.strong = strong; this.weak = weak; this.ms = ms }
fun playing(now: Long) = playedMs != 0 && playedStrong == strong && playedWeak == weak && playedMs == ms &&
@@ -185,7 +245,7 @@ class RumbleComponent : SessionPart() {
until = now + duration
}
override fun run() = play(this)
override fun run() = play(this, keepalive = true)
}
internal interface Motors {
@@ -256,6 +316,7 @@ class RumbleComponent : SessionPart() {
const val HOLD_MS = 0xFFFF
const val HOLD_EFFECT_MS = 2000L
const val KEEPALIVE_MS = 1500L
const val GAME_CHECK_MS = 1000L
private fun oneShot(vibrator: Vibrator, strength: Int, ms: Long): VibrationEffect {
val amplitude = if (vibrator.hasAmplitudeControl()) (strength * 255L / 65535L).toInt().coerceIn(1, 255)
@@ -263,6 +324,13 @@ class RumbleComponent : SessionPart() {
return VibrationEffect.createOneShot(ms, amplitude)
}
const val UNKNOWN_START = "?"
internal fun readProcessStart(pid: Int): String? = runCatching {
val stat = File("/proc/$pid/stat").readText()
stat.substring(stat.lastIndexOf(')') + 2).split(' ')[19]
}.getOrElse { if (File("/proc/$pid").exists()) UNKNOWN_START else null }
private fun lookupController(id: Int): Motors? {
val device = InputDevice.getDevice(id) ?: return null
val name = "\"${device.name}\""
@@ -75,6 +75,17 @@ object SessionEvents {
}
}
inline fun <T> step(name: String, block: () -> T): T {
val dir = SessionState.logDirectory ?: SessionPaths.current()
record("start.step", mapOf("step" to name, "state" to "begin"), dir)
val began = android.os.SystemClock.elapsedRealtime()
try {
return block()
} finally {
record("start.step", mapOf("step" to name, "state" to "end", "ms" to android.os.SystemClock.elapsedRealtime() - began), dir)
}
}
fun fail(code: String, message: String, status: Int? = null) {
synchronized(SessionState) {
SessionState.phase = SessionPhase.FAILED
@@ -14,6 +14,9 @@ import com.droiddeck.launcher.runtime.ProotFastPath
import java.io.File
object SessionFiles {
// Session start and Flatpak staging can both rewrite Steam's config.vdf; one writer at a time.
internal val STEAM_CONFIG = Any()
private const val TAG = "SessionFiles"
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio"
@@ -33,35 +36,60 @@ object SessionFiles {
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
)
private const val UBISOFT_SERVICE = "usr/local/lib/droiddeck-ubisoft/droiddeck-upc.exe"
private val SERVICE_PACKS = mapOf(
AddonPack.UBISOFT to "usr/local/lib/droiddeck-ubisoft",
AddonPack.ROCKSTAR to "usr/local/lib/droiddeck-rockstar",
AddonPack.DIRT to "usr/local/lib/droiddeck-dirt",
)
/** Fetches the Ubisoft pack and, once it lands, stages the service so a running session gets it without restarting. */
fun ensureUbisoftService(context: Context) {
AddonPack.UBISOFT.ensure(context) { app ->
fun ensureUbisoftService(context: Context) = ensureStoreService(context, AddonPack.UBISOFT)
fun ensureRockstarService(context: Context) = ensureStoreService(context, AddonPack.ROCKSTAR)
/** The DiRT 3 / DiRT Showdown ws2_32 stand-in; droiddeck-game-env applies it only when it is staged. */
fun ensureDirtStandIn(context: Context) = ensureStoreService(context, AddonPack.DIRT)
private fun ensureStoreService(context: Context, pack: AddonPack) {
pack.ensure(context) { app ->
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app).takeIf { it.isDirectory }
?.let { stageUbisoftService(app, it, null) }
?.let { stageStoreService(app, it, pack, null) }
}
}
/** Blocks until the store's service pack is installed and staged in [root]; false when it could not be fetched. */
fun awaitStoreService(context: Context, store: String, root: File): Boolean {
val pack = SERVICE_PACKS.keys.firstOrNull { it.name == store } ?: return false
if (!pack.await(context)) return false
return stageStoreService(context, root, pack, null)
}
@Synchronized
private fun stageUbisoftService(context: Context, root: File, ledger: StageLedger?) {
val pack = AddonPack.UBISOFT.takeIf { it.installed(context) }?.dir(context) ?: return
val target = File(root, UBISOFT_SERVICE)
if (ledger?.current(UBISOFT_SERVICE, target) == true) return
val staged = File(target.parentFile, target.name + ".staged")
var installed = false
try {
target.parentFile?.mkdirs()
File(pack, "droiddeck-upc.exe").inputStream().use { input ->
staged.outputStream().use { output -> FileUtils.copy(input, output) }
private fun stageStoreService(context: Context, root: File, pack: AddonPack, ledger: StageLedger?): Boolean {
val dir = pack.takeIf { it.installed(context) }?.dir(context) ?: return false
val base = SERVICE_PACKS.getValue(pack)
var all = true
for (file in dir.listFiles().orEmpty().filter { it.isFile && it.name != AddonPack.COMPLETE }.sortedBy { it.name }) {
val relative = "$base/${file.name}"
val target = File(root, relative)
if (ledger?.current(relative, target) == true) continue
val staged = File(target.parentFile, target.name + ".staged")
var installed = false
try {
target.parentFile?.mkdirs()
file.inputStream().use { input ->
staged.outputStream().use { output -> FileUtils.copy(input, output) }
}
installed = staged.setExecutable(true, false) && staged.renameTo(target)
} catch (e: Exception) {
Log.w(TAG, "could not stage the ${pack.name} pack", e)
} finally {
if (!installed) staged.delete()
}
installed = staged.setExecutable(true, false) && staged.renameTo(target)
} catch (e: Exception) {
Log.w(TAG, "could not stage the Ubisoft launcher service", e)
} finally {
if (!installed) staged.delete()
if (installed) ledger?.staged(relative, target) else Log.e(TAG, "$relative NOT staged")
all = all && installed
}
if (installed) ledger?.staged(UBISOFT_SERVICE, target) else Log.e(TAG, "$UBISOFT_SERVICE NOT staged")
return all
}
fun stage(context: Context, root: File, startsSession: Boolean = false) {
@@ -70,9 +98,8 @@ object SessionFiles {
GameEnvironmentStore.publish(context)
WinComponents.publish(context)
val files = arrayOf(
"rockstar/helpers/Launcher32.exe" to "usr/local/lib/droiddeck-rockstar/Launcher32.exe",
"rockstar/helpers/Launcher64.exe" to "usr/local/lib/droiddeck-rockstar/Launcher64.exe",
"usr/local/bin/droiddeck-game-env" to "usr/local/bin/droiddeck-game-env",
"usr/local/bin/droiddeck-game-debug" to "usr/local/bin/droiddeck-game-debug",
"usr/local/bin/droiddeck-game-gpu" to "usr/local/bin/droiddeck-game-gpu",
"usr/local/bin/droiddeck-diagnostic-inventory" to "usr/local/bin/droiddeck-diagnostic-inventory",
"usr/local/bin/droiddeck-wincomponents" to "usr/local/bin/droiddeck-wincomponents",
@@ -104,6 +131,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-steam-share" to "usr/local/bin/droiddeck-steam-share",
"usr/local/bin/droiddeck-seed-redists" to "usr/local/bin/droiddeck-seed-redists",
"usr/local/bin/droiddeck-launcher-cores" to "usr/local/bin/droiddeck-launcher-cores",
"usr/local/bin/droiddeck-pace-cores" to "usr/local/bin/droiddeck-pace-cores",
"usr/local/bin/droiddeck-proton-extra" to "usr/local/bin/droiddeck-proton-extra",
"usr/local/bin/droiddeck-netmanager" to "usr/local/bin/droiddeck-netmanager",
"usr/local/bin/droiddeck-login1" to "usr/local/bin/droiddeck-login1",
@@ -229,7 +257,6 @@ object SessionFiles {
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
"usr/local/lib/droiddeck-dirt/ws2_32.dll" to "usr/local/lib/droiddeck-dirt/ws2_32.dll",
) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
val dir = asset.substringBeforeLast('/')
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
@@ -243,7 +270,7 @@ object SessionFiles {
var installed = false
try {
target.parentFile?.mkdirs()
(if (asset.startsWith("rockstar/")) requireNotNull(javaClass.getResourceAsStream("/$asset")) else context.assets.open("linuxfs/$asset")).use { input ->
context.assets.open("linuxfs/$asset").use { input ->
staged.outputStream().use { output -> FileUtils.copy(input, output) }
}
installed = staged.setExecutable(true, false) && staged.renameTo(target)
@@ -285,7 +312,7 @@ object SessionFiles {
}
if (installed) ledger.staged(key, target) else Log.e(TAG, "DirectAudio $set/$relative NOT staged")
}
stageUbisoftService(context, root, ledger)
for (pack in SERVICE_PACKS.keys) stageStoreService(context, root, pack, ledger)
ledger.save()
for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively()
val preload = StringBuilder("/usr/local/lib/libblsession.so\n")
@@ -354,7 +381,15 @@ object SessionFiles {
"stage session=$startsSession pending=$force choice=${SessionPrefs.bootMovie(context)} movie=${startupMovie?.path} " +
"staged=$bigPictureMovieInstalled done=$done steam=${home.path} config: $before -> ${startupMoviePath(config)}",
)
if (startsSession) disableIdleSleep(home)
if (startsSession) {
synchronized(STEAM_CONFIG) {
val shuffle = SessionPrefs.bootMovieShuffle(context)
setStartupMovieShuffle(config, shuffle)
if (startupMovieShuffle(config) == shuffle) SessionPrefs.setBootMovieShuffleSeen(context, config, shuffle)
}
disableIdleSleep(home)
seedUserDefaults(home)
}
if (!done) allDone = false
if (!bigPictureMovieInstalled) allInstalled = false
if (done && home.path.contains(".droiddeck-x64") == activeIsX64) seen = if (bigPictureMovieInstalled) BOOT_MOVIE_PATH else ""
@@ -364,28 +399,30 @@ object SessionFiles {
}
internal fun resetMissingStartupMovie(config: File, force: Boolean): Boolean {
if (!config.isFile) return true
val text = runCatching { config.readText() }.getOrElse {
Log.w(TAG, "could not read Steam config to reset the startup movie", it)
return false
}
val movie = activeStartupMovie(text) ?: return true
val block = text.substring(movie.keyStart, movie.close + 1)
val path = scalar(block, "LocalPath").orEmpty()
if (path.isEmpty()) return true
val missing = File(config.parentFile, "uioverrides/movies/" + path.removePrefix(BOOT_MOVIES_DIR))
val gone = path.startsWith(BOOT_MOVIES_DIR) && !missing.isFile && (force || path == BOOT_MOVIE_PATH)
if (!gone) return false
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
val updated = setScalar(setScalar(block, "MovieID", "0", newline), "LocalPath", "", newline)
val staged = File(config.parentFile, config.name + ".staged")
return try {
staged.writeText(text.replaceRange(movie.keyStart, movie.close + 1, updated))
(staged.renameTo(config)).also { if (!it) staged.delete() }
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not reset Steam startup movie selection", e)
false
synchronized(STEAM_CONFIG) {
if (!config.isFile) return true
val text = runCatching { config.readText() }.getOrElse {
Log.w(TAG, "could not read Steam config to reset the startup movie", it)
return false
}
val movie = activeStartupMovie(text) ?: return true
val block = text.substring(movie.keyStart, movie.close + 1)
val path = scalar(block, "LocalPath").orEmpty()
if (path.isEmpty()) return true
val missing = File(config.parentFile, "uioverrides/movies/" + path.removePrefix(BOOT_MOVIES_DIR))
val gone = path.startsWith(BOOT_MOVIES_DIR) && !missing.isFile && (force || path == BOOT_MOVIE_PATH)
if (!gone) return false
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
val updated = setScalar(setScalar(block, "MovieID", "0", newline), "LocalPath", "", newline)
val staged = File(config.parentFile, config.name + ".staged")
return try {
staged.writeText(text.replaceRange(movie.keyStart, movie.close + 1, updated))
(staged.renameTo(config)).also { if (!it) staged.delete() }
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not reset Steam startup movie selection", e)
false
}
}
}
@@ -486,6 +523,42 @@ object SessionFiles {
return scalar(text.substring(movie.keyStart, movie.close + 1), "LocalPath")
}
internal fun startupMovieShuffle(config: File): Boolean? {
val text = runCatching { config.readText() }.getOrNull() ?: return null
val movie = activeStartupMovie(text) ?: return false
return scalar(text.substring(movie.keyStart, movie.close + 1), "Shuffle") == "1"
}
internal fun withStartupMovieShuffle(text: String, on: Boolean): String {
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
val value = if (on) "1" else "0"
return listOfNotNull(customizationMovie(text), olderMovie(text)).sortedByDescending { it.keyStart }.fold(text) { acc, movie ->
val block = acc.substring(movie.keyStart, movie.close + 1)
if (!on && scalar(block, "Shuffle") == null) acc else acc.replaceRange(movie.keyStart, movie.close + 1, setScalar(block, "Shuffle", value, newline))
}
}
internal fun setStartupMovieShuffle(config: File, on: Boolean): Boolean {
synchronized(STEAM_CONFIG) {
if (!config.isFile) return false
val text = runCatching { config.readText() }.getOrElse {
Log.w(TAG, "could not read Steam config to set the startup movie shuffle", it)
return false
}
val updated = withStartupMovieShuffle(text, on)
if (updated == text) return true
val staged = File(config.parentFile, config.name + ".staged")
return try {
staged.writeText(updated)
staged.renameTo(config).also { if (!it) staged.delete() }
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not set Steam startup movie shuffle", e)
false
}
}
}
internal fun startupMovieBlock(config: File): String? {
val text = runCatching { config.readText() }.getOrNull() ?: return null
val parts = listOfNotNull(
@@ -508,101 +581,184 @@ object SessionFiles {
}
internal fun ensureStartupMovieDefault(config: File, force: Boolean = false): Boolean {
val path = BOOT_MOVIE_PATH
val legacyPath = "/uioverrides/movies/droiddeck-startup.webm"
var text = if (config.isFile) runCatching { config.readText() }.getOrElse {
Log.w(TAG, "could not read Steam config for startup movie", it)
return false
} else ""
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
val custom = customizationMovie(text)
val active = custom ?: olderMovie(text)
if (active != null) {
val block = text.substring(active.keyStart, active.close + 1)
val selectedId = scalar(block, "MovieID")
val selectedPath = scalar(block, "LocalPath")
if (selectedPath == path && custom != null) {
Log.i(TAG, "Steam startup movie is set to DroidDeck")
return true
}
val legacyDefault = selectedId == "0" && selectedPath == legacyPath
val hasExplicitSelection =
(!selectedId.isNullOrEmpty() && selectedId != "0") || !selectedPath.isNullOrEmpty()
if (!force && !legacyDefault && hasExplicitSelection && selectedPath != path) {
Log.i(TAG, "Steam startup movie selection preserved")
synchronized(STEAM_CONFIG) {
val path = BOOT_MOVIE_PATH
val legacyPath = "/uioverrides/movies/droiddeck-startup.webm"
var text = if (config.isFile) runCatching { config.readText() }.getOrElse {
Log.w(TAG, "could not read Steam config for startup movie", it)
return false
}
}
val targets = listOfNotNull(customizationMovie(text), olderMovie(text)).sortedByDescending { it.keyStart }
for (target in targets) text = pointAt(text, target, path, newline)
if (olderMovie(text) == null) {
val steam = findSteamBlock(text)
if (steam == null) {
if (text.isNotBlank() && customizationMovie(text) == null) {
Log.w(TAG, "Steam config has no Steam settings block; startup movie default not set")
} else ""
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
val custom = customizationMovie(text)
val active = custom ?: olderMovie(text)
if (active != null) {
val block = text.substring(active.keyStart, active.close + 1)
val selectedId = scalar(block, "MovieID")
val selectedPath = scalar(block, "LocalPath")
if (selectedPath == path && custom != null) {
Log.i(TAG, "Steam startup movie is set to DroidDeck")
return true
}
val legacyDefault = selectedId == "0" && selectedPath == legacyPath
val hasExplicitSelection =
(!selectedId.isNullOrEmpty() && selectedId != "0") || !selectedPath.isNullOrEmpty()
if (!force && !legacyDefault && hasExplicitSelection && selectedPath != path) {
Log.i(TAG, "Steam startup movie selection preserved")
return false
}
if (text.isBlank()) {
text = "\"InstallConfigStore\"${newline}{${newline}\t\"Software\"${newline}\t{${newline}\t\t\"Valve\"${newline}\t\t{${newline}\t\t\t\"Steam\"${newline}\t\t\t{${newline}"
val section = startupMovieSection("\t\t\t\t", path, newline)
text += section + newline + "\t\t\t}" + newline + "\t\t}" + newline + "\t}" + newline + "}"
}
val targets = listOfNotNull(customizationMovie(text), olderMovie(text)).sortedByDescending { it.keyStart }
for (target in targets) text = pointAt(text, target, path, newline)
if (olderMovie(text) == null) {
val steam = findSteamBlock(text)
if (steam == null) {
if (text.isNotBlank() && customizationMovie(text) == null) {
Log.w(TAG, "Steam config has no Steam settings block; startup movie default not set")
return false
}
if (text.isBlank()) {
text = "\"InstallConfigStore\"${newline}{${newline}\t\"Software\"${newline}\t{${newline}\t\t\"Valve\"${newline}\t\t{${newline}\t\t\t\"Steam\"${newline}\t\t\t{${newline}"
val section = startupMovieSection("\t\t\t\t", path, newline)
text += section + newline + "\t\t\t}" + newline + "\t\t}" + newline + "\t}" + newline + "}"
}
} else {
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' }
val section = startupMovieSection(indent + "\t", path, newline)
text = text.substring(0, lineStart) + section + newline + indent + text.substring(lineStart)
}
} else {
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' }
val section = startupMovieSection(indent + "\t", path, newline)
text = text.substring(0, lineStart) + section + newline + indent + text.substring(lineStart)
}
}
if (customizationMovie(text) == null) text = withCustomization(text, path, newline)
val staged = File(config.parentFile, config.name + ".staged")
return try {
config.parentFile?.mkdirs()
staged.writeText(text)
if (!staged.renameTo(config)) {
if (customizationMovie(text) == null) text = withCustomization(text, path, newline)
val staged = File(config.parentFile, config.name + ".staged")
return try {
config.parentFile?.mkdirs()
staged.writeText(text)
if (!staged.renameTo(config)) {
staged.delete()
Log.e(TAG, "could not write Steam startup movie selection")
false
} else {
Log.i(TAG, "Steam startup movie default selected")
true
}
} catch (e: Exception) {
staged.delete()
Log.e(TAG, "could not write Steam startup movie selection")
Log.w(TAG, "could not write Steam startup movie selection", e)
false
} else {
Log.i(TAG, "Steam startup movie default selected")
true
}
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not write Steam startup movie selection", e)
false
}
}
private const val USER_DEFAULTS_MARKER = "droiddeck-user-defaults-initialized"
private const val BATTERY_PREFERENCES = "CachedBatteryPreferences"
private const val UI_STATE = "UIStoreLocalSteamUIState"
private const val SORT_RECENT_OFF = "\\\"bSortedByRecent\\\":false"
private const val SORT_RECENT_ON = "\\\"bSortedByRecent\\\":true"
private const val BATTERY_PERCENT_ON = "{\\\"bShowBatteryPercentage\\\":true}"
/**
* Seeds opinionated first-run defaults into each Steam account's localconfig.vdf: battery percentage shown and
* download speeds in bytes rather than bits, and the library sorted by recently played. A value is written once per account and only when the key is
* absent, so a later choice made in Steam is never overridden. Runs while Steam is stopped, as it keeps the
* file in memory and rewrites it.
*/
internal fun seedUserDefaults(steamHome: File) {
val users = File(steamHome, "userdata").listFiles { f -> f.isDirectory && f.name.all(Char::isDigit) && f.name != "0" } ?: return
for (user in users) {
val configDir = File(user, "config")
val marker = File(configDir, USER_DEFAULTS_MARKER)
val file = File(configDir, "localconfig.vdf")
if (marker.exists() || !file.isFile) continue
try {
val text = file.readText()
val updated = withUserDefaults(text) ?: continue
if (updated != text) {
val staged = File(configDir, file.name + ".staged")
staged.writeText(updated)
if (!staged.renameTo(file)) { staged.delete(); continue }
}
marker.writeText("1\n")
} catch (e: Exception) {
Log.w(TAG, "could not seed Steam user defaults", e)
}
}
}
internal fun withUserDefaults(text: String): String? {
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
val root = findObject(text, "UserLocalConfigStore", 0, text.length) ?: return null
var out = text
val system = findObject(out, "system", root.open + 1, root.close)
if (system == null) {
out = insertInto(out, root, listOf("\"system\"", "{", "\t\"displayratesasbits\"\t\t\"0\"", "}"), newline)
} else if (!hasKey(out.substring(system.keyStart, system.close + 1), "displayratesasbits")) {
val block = out.substring(system.keyStart, system.close + 1)
out = out.replaceRange(system.keyStart, system.close + 1, setScalar(block, "displayratesasbits", "0", newline))
}
val reroot = findObject(out, "UserLocalConfigStore", 0, out.length) ?: return out
val web = findObject(out, "WebStorage", reroot.open + 1, reroot.close)
if (web == null) {
out = insertInto(out, reroot, listOf("\"WebStorage\"", "{", "\t\"$BATTERY_PREFERENCES\"\t\t\"$BATTERY_PERCENT_ON\"", "}"), newline)
} else if (!hasKey(out.substring(web.keyStart, web.close + 1), BATTERY_PREFERENCES)) {
val block = out.substring(web.keyStart, web.close + 1)
out = out.replaceRange(web.keyStart, web.close + 1, setScalar(block, BATTERY_PREFERENCES, BATTERY_PERCENT_ON, newline))
}
return seedRecentSort(out, newline)
}
// The library sort lives inside a JSON string; Steam writes bSortedByRecent:false until the player picks a sort,
// so the first seed flips it once and the marker file keeps a later choice.
private fun seedRecentSort(text: String, newline: String): String {
val root = findObject(text, "UserLocalConfigStore", 0, text.length) ?: return text
val web = findObject(text, "WebStorage", root.open + 1, root.close) ?: return text
val block = text.substring(web.keyStart, web.close + 1)
if (!hasKey(block, UI_STATE)) {
return text.replaceRange(web.keyStart, web.close + 1,
setScalar(block, UI_STATE, "{\\\"nVersion\\\":1,$SORT_RECENT_ON}", newline))
}
return text.replaceRange(web.keyStart, web.close + 1, block.replace(SORT_RECENT_OFF, SORT_RECENT_ON))
}
private fun hasKey(block: String, key: String) = Regex("(?m)^[\\t ]*\"${Regex.escape(key)}\"[\\t ]").containsMatchIn(block)
private fun insertInto(text: String, parent: VdfBlock, lines: List<String>, newline: String): String {
val lineStart = text.lastIndexOf('\n', parent.close).let { if (it < 0) 0 else it + 1 }
val indent = text.substring(lineStart, parent.close).takeWhile { it == '\t' || it == ' ' } + "\t"
val section = lines.joinToString(newline) { indent + it } + newline
return text.substring(0, lineStart) + section + text.substring(lineStart)
}
private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds")
internal fun disableIdleSleep(steamHome: File): Boolean {
val config = File(steamHome, "config/config.vdf")
val text = runCatching { config.readText() }.getOrNull() ?: return false
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
val steam = findSteamBlock(text) ?: return false
val system = findObject(text, "system", steam.open + 1, steam.close)
val updated = if (system != null) {
val block = text.substring(system.keyStart, system.close + 1)
text.replaceRange(system.keyStart, system.close + 1, IDLE_SLEEP_TIMERS.fold(block) { acc, key -> setScalar(acc, key, "0", newline) })
} else {
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' } + "\t"
val section = (listOf(indent + "\"system\"", indent + "{") +
IDLE_SLEEP_TIMERS.map { "$indent\t\"$it\"\t\t\"0\"" } + (indent + "}")).joinToString(newline) + newline
text.substring(0, lineStart) + section + text.substring(lineStart)
}
val staged = File(config.parentFile, config.name + ".staged")
return try {
if (updated != text) {
staged.writeText(updated)
if (!staged.renameTo(config)) { staged.delete(); return false }
synchronized(STEAM_CONFIG) {
val config = File(steamHome, "config/config.vdf")
val text = runCatching { config.readText() }.getOrNull() ?: return false
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
val steam = findSteamBlock(text) ?: return false
val system = findObject(text, "system", steam.open + 1, steam.close)
val updated = if (system != null) {
val block = text.substring(system.keyStart, system.close + 1)
text.replaceRange(system.keyStart, system.close + 1, IDLE_SLEEP_TIMERS.fold(block) { acc, key -> setScalar(acc, key, "0", newline) })
} else {
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' } + "\t"
val section = (listOf(indent + "\"system\"", indent + "{") +
IDLE_SLEEP_TIMERS.map { "$indent\t\"$it\"\t\t\"0\"" } + (indent + "}")).joinToString(newline) + newline
text.substring(0, lineStart) + section + text.substring(lineStart)
}
val staged = File(config.parentFile, config.name + ".staged")
return try {
if (updated != text) {
staged.writeText(updated)
if (!staged.renameTo(config)) { staged.delete(); return false }
}
true
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not disable Steam's idle sleep", e)
false
}
true
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not disable Steam's idle sleep", e)
false
}
}
@@ -654,7 +810,7 @@ object SessionFiles {
}
private fun setScalar(block: String, key: String, value: String, newline: String): String {
val pattern = Regex("(?m)^([\\t ]*\"${Regex.escape(key)}\"[\\t ]+)\"[^\"\\r\\n]*\"([\\t ]*)$")
val pattern = Regex("(?m)^([\\t ]*\"${Regex.escape(key)}\"[\\t ]+)\"[^\"\\r\\n]*\"([\\t ]*(?://[^\\r\\n]*)?)$")
val match = pattern.find(block)
if (match != null) return block.replaceRange(match.range, match.groupValues[1] + "\"" + value + "\"" + match.groupValues[2])
val close = block.lastIndexOf('}')
@@ -23,6 +23,9 @@ object SessionPaths {
@Volatile
private var ended: File? = null
@Volatile
private var startedAt = 0L
@Synchronized
fun beginOrCurrent(context: Context, label: String? = null): File {
dir?.let { if (it.isDirectory) return it }
@@ -38,6 +41,7 @@ object SessionPaths {
var made = File(parent, "$day-${"%02d".format(Locale.US, number)}-$what")
while (made.exists()) made = File(parent, "$day-${"%02d".format(Locale.US, ++number)}-$what")
EnhancedDiagnostics.clearRecordFor(context, made)
startedAt = System.currentTimeMillis()
if (!made.isDirectory && !made.mkdirs()) Log.e(TAG, "could not create $made")
dir = made
if (enhanced && !EnhancedDiagnostics.consumeInto(context, made)) {
@@ -49,6 +53,8 @@ object SessionPaths {
fun current(): File? = dir
fun startedAt(folder: File): Long = if (dir == folder) startedAt else 0L
fun currentSessionLogsRetained(context: Context): Boolean =
dir?.let { it.parentFile == SessionFiles.logDirectory(context) } ?: true
@@ -13,6 +13,8 @@ import com.droiddeck.launcher.gpu.TurnipDriver
import org.json.JSONObject
import java.io.File
private const val SCREEN_EFFECTS_PROFILE_UPSCALER_KEY = "upscaler"
object SessionPrefs {
data class GameTextureFiltering(val anisotropy: Int? = null, val lodBias: String? = null)
@@ -83,6 +85,12 @@ object SessionPrefs {
prefs(context).edit().putBoolean("launcherFullscreen", on).apply()
}
fun blackFrameInsertion(context: Context): Boolean = prefs(context).getBoolean("blackFrameInsertion", false)
fun setBlackFrameInsertion(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("blackFrameInsertion", on).apply()
}
fun animationsEnabled(context: Context): Boolean = prefs(context).getBoolean("animations", true)
fun setAnimationsEnabled(context: Context, on: Boolean) {
@@ -277,6 +285,12 @@ object SessionPrefs {
prefs(context).edit().putBoolean("libraryShowUninstalled", show).apply()
}
fun libraryFavorites(context: Context): Set<String> = prefs(context).getStringSet("libraryFavorites", null)?.toSet().orEmpty()
fun setLibraryFavorites(context: Context, keys: Set<String>) {
prefs(context).edit().putStringSet("libraryFavorites", keys.toSet()).apply()
}
fun storesTabOrder(context: Context): List<String> = idList(prefs(context).getString("storesTabOrder", null))
fun setStoresTabOrder(context: Context, order: List<String>) {
@@ -508,6 +522,38 @@ object SessionPrefs {
prefs(context).edit().putString("touch", mode).apply()
}
const val PEN_MOUSE = "mouse"
const val PEN_TOUCH = "touch"
const val PEN_BUTTON_RIGHT = "right"
const val PEN_BUTTON_MIDDLE = "middle"
const val PEN_BUTTON_OFF = "off"
data class Pen(val mode: String = PEN_MOUSE, val button: String = PEN_BUTTON_RIGHT)
private val PEN_SETTINGS = mapOf(
"pen" to setOf(PEN_MOUSE, PEN_TOUCH),
"penButton" to setOf(PEN_BUTTON_RIGHT, PEN_BUTTON_MIDDLE, PEN_BUTTON_OFF),
)
private fun penSetting(context: Context, key: String, default: String): String =
prefs(context).getString(key, default)?.takeIf { it in PEN_SETTINGS.getValue(key) } ?: default
fun setPenSetting(context: Context, key: String, value: String) {
require(value in PEN_SETTINGS.getValue(key))
prefs(context).edit().putString(key, value).apply()
}
fun penMode(context: Context): String = penSetting(context, "pen", PEN_MOUSE)
fun penButton(context: Context): String = penSetting(context, "penButton", PEN_BUTTON_RIGHT)
fun pen(context: Context): Pen = Pen(penMode(context), penButton(context))
fun penSeen(context: Context): Boolean = prefs(context).getBoolean("penSeen", false)
fun setPenSeen(context: Context) {
if (!penSeen(context)) prefs(context).edit().putBoolean("penSeen", true).apply()
}
const val SHAPE_AUTO = "auto"
const val SHAPE_WIDE = "16:9"
const val SHAPE_EXACT = "exact"
@@ -601,6 +647,13 @@ object SessionPrefs {
position.takeIf { it in listOf("top", "bottom", "left", "right", "center") } ?: "center").apply()
}
fun integerScaling(context: Context): Boolean =
prefs(context).getBoolean("integerScaling", false)
fun setIntegerScaling(context: Context, enabled: Boolean) {
prefs(context).edit().putBoolean("integerScaling", enabled).apply()
}
fun returnAfterGame(context: Context): Boolean = prefs(context).getBoolean("returnAfterGame", true)
fun setReturnAfterGame(context: Context, on: Boolean) {
@@ -654,6 +707,18 @@ object SessionPrefs {
fun micAsked(context: Context): Boolean = prefs(context).getBoolean("micAsked", false)
fun allFilesAsked(context: Context): Boolean = prefs(context).getBoolean("allFilesAsked", false)
fun setAllFilesAsked(context: Context) {
prefs(context).edit().putBoolean("allFilesAsked", true).apply()
}
fun bluetoothAsked(context: Context): Boolean = prefs(context).getBoolean("bluetoothAsked", false)
fun setBluetoothAsked(context: Context) {
prefs(context).edit().putBoolean("bluetoothAsked", true).apply()
}
fun setMicAsked(context: Context) {
prefs(context).edit().putBoolean("micAsked", true).apply()
}
@@ -750,6 +815,12 @@ object SessionPrefs {
prefs(context).edit().putBoolean("syncFallback", on).apply()
}
fun paceCores(context: Context): Boolean = prefs(context).getBoolean("paceCores", true)
fun setPaceCores(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("paceCores", on).apply()
}
fun gamescopeRealtime(context: Context): Boolean = prefs(context).getBoolean("gamescopeRealtime", false)
fun setGamescopeRealtime(context: Context, on: Boolean) {
@@ -768,6 +839,12 @@ object SessionPrefs {
prefs(context).edit().putBoolean("zramClient", on).apply()
}
fun zramIdle(context: Context): Boolean = prefs(context).getBoolean("zramIdle", true)
fun setZramIdle(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("zramIdle", on).apply()
}
fun vramCapMb(context: Context): Int = prefs(context).getInt("vramCapMb", 0).coerceAtLeast(0)
fun setVramCapMb(context: Context, mb: Int) {
@@ -861,8 +938,12 @@ object SessionPrefs {
@JvmStatic
fun vkBridge(context: Context): Boolean = prefs(context).getBoolean("vkBridge", com.droiddeck.launcher.core.DeviceSupport.mali())
fun vkBridgeExplicit(context: Context): Boolean = prefs(context).contains("vkBridge")
fun venus(context: Context): Boolean = prefs(context).getBoolean("venus", false)
fun venusExplicit(context: Context): Boolean = prefs(context).contains("venus")
fun hostVulkanApi(context: Context): String = prefs(context).getString("hostVulkanApi", "").orEmpty()
fun setHostVulkanApi(context: Context, api: String) {
@@ -883,7 +964,7 @@ object SessionPrefs {
prefs(context).edit().putBoolean("steamGpuCompositing", false).apply()
return false
}
return prefs(context).getBoolean("steamGpuCompositing", false)
return prefs(context).getBoolean("steamGpuCompositing", true)
}
fun steamGpuCompositingAllowed(): Boolean =
@@ -1164,10 +1245,22 @@ object SessionPrefs {
fun setBootMovieVolume(context: Context, percent: Int) { prefs(context).edit().putInt("bootMovieVolume", percent.coerceIn(0, 100)).apply() }
fun bootMovieSeconds(context: Context): Int = prefs(context).getInt("bootMovieSeconds", 0).coerceAtLeast(0)
fun setBootMovieSeconds(context: Context, seconds: Int) { prefs(context).edit().putInt("bootMovieSeconds", seconds.coerceAtLeast(0)).apply() }
fun skipBootMovie(context: Context): Boolean = prefs(context).getBoolean("skipBootMovie", false)
fun setSkipBootMovie(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("skipBootMovie", on).apply()
setBootMovieApplyNext(context, true)
}
fun bootMovieApplyNext(context: Context): Boolean = prefs(context).getBoolean("bootMovieApplyNext", false)
fun setBootMovieApplyNext(context: Context, on: Boolean) { prefs(context).edit().putBoolean("bootMovieApplyNext", on).apply() }
fun bootMovieSteamSeen(context: Context): String? = prefs(context).getString("bootMovieSteamSeen", null)
fun setBootMovieSteamSeen(context: Context, path: String) { prefs(context).edit().putString("bootMovieSteamSeen", path).apply() }
fun bootMovieShuffle(context: Context): Boolean = prefs(context).getBoolean("bootMovieShuffle", false)
fun setBootMovieShuffle(context: Context, on: Boolean) { prefs(context).edit().putBoolean("bootMovieShuffle", on).apply() }
fun bootMovieShuffleSeen(context: Context, config: java.io.File): Boolean? {
val key = "bootMovieShuffleSeen:${config.path}"
return prefs(context).takeIf { it.contains(key) }?.getBoolean(key, false)
}
fun setBootMovieShuffleSeen(context: Context, config: java.io.File, on: Boolean) { prefs(context).edit().putBoolean("bootMovieShuffleSeen:${config.path}", on).apply() }
fun bootMovieCustomName(context: Context): String? = prefs(context).getString("bootMovieCustomName", null)
fun setBootMovieCustomName(context: Context, name: String?) {
prefs(context).edit().apply { if (name == null) remove("bootMovieCustomName") else putString("bootMovieCustomName", name) }.apply()
@@ -1357,6 +1450,13 @@ object SessionPrefs {
prefs(context).edit().putInt("gradientPrimary", primary).putInt("gradientSecondary", secondary).apply()
}
fun trueBlackHighlight(context: Context): Int =
prefs(context).getInt("trueBlackHighlight", com.droiddeck.launcher.ui.Themes.DEFAULT_HIGHLIGHT)
fun setTrueBlackHighlight(context: Context, highlight: Int) {
prefs(context).edit().putInt("trueBlackHighlight", highlight).apply()
}
private fun customResolution(context: Context, mode: String): Pair<Int, Int>? =
parseResolution(prefs(context).getString("customRes.$mode", null))
@@ -1426,15 +1526,136 @@ object SessionPrefs {
}
private const val SCREEN_EFFECTS_PROFILES_KEY = "screenEffects.profiles"
const val SCREEN_EFFECTS_ACTIVE_PROFILE_KEY = "screenEffects.activeProfile"
fun screenEffectsProfileId(mode: String, gameId: String?, program: String?): String? {
if (mode == SessionService.MODE_DESKTOP) return "desktop"
val id = gameId?.trim()?.takeIf { it.isNotEmpty() }
if (id != null) return "game:$id"
return if (mode == SessionService.MODE_RUN) {
program?.trim()?.takeIf { it.isNotEmpty() }?.let { "program:$it" }
} else null
}
fun activeScreenEffectsProfileId(context: Context): String? =
prefs(context).getString(SCREEN_EFFECTS_ACTIVE_PROFILE_KEY, null)?.takeIf { it.isNotBlank() }
fun setActiveScreenEffectsProfile(context: Context, profileId: String?) {
prefs(context).edit().putString(SCREEN_EFFECTS_ACTIVE_PROFILE_KEY, profileId.orEmpty()).apply()
}
fun screenEffects(context: Context): ScreenEffects {
val text = prefs(context).getString("screenEffects", null) ?: return ScreenEffects.OFF
return runCatching { ScreenEffects.decode(JSONObject(text)) }.getOrDefault(ScreenEffects.OFF)
}
fun screenEffects(context: Context, profileId: String?): ScreenEffects {
if (profileId.isNullOrBlank()) return screenEffects(context)
val storedProfiles = prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null)
val profile = storedProfiles?.let { raw ->
runCatching { JSONObject(raw).optJSONObject(profileId) }.getOrNull()
}
return profile?.let {
runCatching { ScreenEffects.decode(it) }.getOrDefault(ScreenEffects.OFF)
} ?: screenEffects(context)
}
fun setScreenEffects(context: Context, effects: ScreenEffects) {
prefs(context).edit().putString("screenEffects", effects.encode().toString()).apply()
}
fun setScreenEffects(context: Context, profileId: String?, effects: ScreenEffects) {
if (profileId.isNullOrBlank()) {
setScreenEffects(context, effects)
return
}
val sessionPrefs = prefs(context)
val profiles = runCatching {
JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
}.getOrDefault(JSONObject())
val encoded = effects.encode()
profiles.optJSONObject(profileId)?.let { savedProfile ->
if (savedProfile.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY)) {
encoded.put(
SCREEN_EFFECTS_PROFILE_UPSCALER_KEY,
savedProfile.optInt(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY),
)
}
}
profiles.put(profileId, encoded)
sessionPrefs.edit().putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString()).apply()
}
fun hasScreenEffectsUpscalerOverride(context: Context, profileId: String?): Boolean {
if (profileId.isNullOrBlank()) return false
return runCatching {
val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
profiles.optJSONObject(profileId)?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true
}.getOrDefault(false)
}
fun screenEffectsUpscaler(context: Context, profileId: String?): Int {
if (profileId.isNullOrBlank()) return upscaler(context)
val stored = runCatching {
val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
val profile = profiles.optJSONObject(profileId)
if (profile?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true) {
profile.optInt(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY, -1)
} else -1
}.getOrDefault(-1)
return if (stored >= 0) canonicalUpscaler(stored) else upscaler(context)
}
fun setScreenEffectsUpscaler(context: Context, profileId: String?, mode: Int) {
if (profileId.isNullOrBlank()) {
setUpscaler(context, mode)
return
}
val sessionPrefs = prefs(context)
val profiles = runCatching {
JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
}.getOrDefault(JSONObject())
val profile = profiles.optJSONObject(profileId)
?: screenEffects(context, profileId).encode()
profile.put(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY, canonicalUpscaler(mode))
profiles.put(profileId, profile)
sessionPrefs.edit().putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString()).apply()
}
fun screenEffectsProfileIds(context: Context): Set<String> {
val profiles = runCatching {
JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
}.getOrElse { JSONObject() }
return buildSet {
val keys = profiles.keys()
while (keys.hasNext()) add(keys.next())
}
}
fun hasScreenEffectsOverride(context: Context, profileId: String?): Boolean {
if (profileId.isNullOrBlank()) return prefs(context).contains("screenEffects")
return profileId in screenEffectsProfileIds(context)
}
fun resetScreenEffectsProfile(context: Context, profileId: String?) {
setScreenEffects(context, profileId, ScreenEffects.OFF)
}
fun deleteScreenEffectsProfile(context: Context, profileId: String?) {
if (profileId.isNullOrBlank()) return
val sessionPrefs = prefs(context)
val profiles = runCatching {
JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
}.getOrElse { JSONObject() }
if (!profiles.has(profileId)) return
profiles.remove(profileId)
sessionPrefs.edit().apply {
if (profiles.length() == 0) remove(SCREEN_EFFECTS_PROFILES_KEY)
else putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString())
}.apply()
}
const val CARDBOARD_KEY = "cardboard"
fun cardboard(context: Context): Cardboard {
@@ -23,6 +23,7 @@ import android.os.IBinder
import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import android.os.SystemClock
import android.hardware.display.DisplayManager
import android.view.Display
import android.util.Log
@@ -85,7 +86,12 @@ class SessionService : Service() {
private var activityDisplayId = Display.DEFAULT_DISPLAY
private var xrActivityVisible = false
private var signInHold = false
private val hasVisibleSurface get() = !SessionVisibilityPolicy.isHidden(
private val browserHandoff = BrowserHandoff(BROWSER_HANDOFF_TIMEOUT_MS)
private val browserHandoffExpired = Runnable {
suspendAttemptFailed = false
updateSuspendPolicy()
}
private val hasVisibleSurface get() = browserHandoff.active(SystemClock.elapsedRealtime()) || !SessionVisibilityPolicy.isHidden(
activityStarted = activityVisible || signInHold,
defaultDisplayOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: screenOn,
activityOnDefaultDisplay = activityDisplayId == Display.DEFAULT_DISPLAY,
@@ -108,7 +114,10 @@ class SessionService : Service() {
private var freezePending = false
private var freezeCancelled = false
private var pendingSteamGameId: String? = null
private var pendingSteamPreviousGameId: String? = null
private var pendingSteamPreviousGamePending = false
private var pendingSteamGameGeneration = -1
private var pendingSteamGameExitWatchToken = -1
@Volatile private var gameExitWatchToken = 0
private val flushSteamGame = object : Runnable {
override fun run() = flushQueuedSteamGame()
@@ -235,6 +244,7 @@ class SessionService : Service() {
ACTION_ACTIVITY_VISIBLE -> {
if (!SessionState.pipActive) pipTask = false
activityVisible = true
browserHandoff.sessionShown()
activityDisplayId = intent.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, activityDisplayId)
sessionDisplayId = intent.getIntExtra(EXTRA_DISPLAY_ID, sessionDisplayId)
screenOn = readScreenOn()
@@ -258,6 +268,7 @@ class SessionService : Service() {
}
ACTION_ACTIVITY_HIDDEN -> {
activityVisible = false
browserHandoff.sessionHidden()
activityDisplayId = intent.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, activityDisplayId)
suspendAttemptFailed = false
updateSuspendPolicy()
@@ -287,6 +298,17 @@ class SessionService : Service() {
updateSuspendPolicy()
return START_NOT_STICKY
}
ACTION_BROWSER_HANDOFF -> {
if (!SessionState.running) return START_NOT_STICKY
browserHandoff.begin(SystemClock.elapsedRealtime())
if (!activityVisible) browserHandoff.sessionHidden()
mainHandler.removeCallbacks(browserHandoffExpired)
mainHandler.postDelayed(browserHandoffExpired, BROWSER_HANDOFF_TIMEOUT_MS)
if (!manualHold) manualPauseRequested = false
suspendAttemptFailed = false
updateSuspendPolicy()
return START_NOT_STICKY
}
ACTION_MIC_CHANGED -> {
if (SessionState.running && SessionState.micAvailable && !SessionState.suspended) {
val enabled = intent.getBooleanExtra("enabled", false)
@@ -343,6 +365,8 @@ class SessionService : Service() {
activityVisible = true
xrActivityVisible = false
signInHold = false
browserHandoff.clear()
mainHandler.removeCallbacks(browserHandoffExpired)
sessionDisplayId = intent?.getIntExtra(EXTRA_DISPLAY_ID, Display.DEFAULT_DISPLAY) ?: Display.DEFAULT_DISPLAY
activityDisplayId = intent?.getIntExtra(EXTRA_ACTIVITY_DISPLAY_ID, sessionDisplayId) ?: sessionDisplayId
screenOn = readScreenOn()
@@ -369,9 +393,28 @@ class SessionService : Service() {
pipTask = false
SessionState.program = intent?.getStringExtra(EXTRA_PROGRAM)
SessionState.programArgs = intent?.getStringArrayExtra(EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
SessionState.gameId = intent?.getStringExtra(EXTRA_GAME_ID)
SessionState.steamUi = intent?.getStringExtra(EXTRA_STEAM_UI)
SessionState.steamUrl = intent?.getStringExtra(EXTRA_STEAM_URL)
val steamUrlGameId = SessionState.steamUrl
?.let { url ->
when {
url.startsWith(GAME_URL_PREFIX) ->
url.removePrefix(GAME_URL_PREFIX)
url.startsWith("steam://run/") ->
url.removePrefix("steam://run/")
else -> null
}
}
?.takeIf(GameLaunchLink::validId)
val resolvedGameId = intent?.getStringExtra(EXTRA_GAME_ID)
?.trim()
?.takeIf(GameLaunchLink::validId)
?: steamUrlGameId
SessionState.gameId = resolvedGameId
SessionPrefs.setActiveScreenEffectsProfile(
this,
SessionPrefs.screenEffectsProfileId(SessionState.mode, resolvedGameId, SessionState.program),
)
com.droiddeck.launcher.stores.battlenet.BattleNetClient.clearRequests(LinuxRuntime.sessionRoot(this))
val gen = synchronized(stopLock) {
SessionState.steamClientArch = null
@@ -392,8 +435,9 @@ class SessionService : Service() {
if (SessionPrefs.clearCachedApps(this)) clearCachedApps()
cancelQueuedSteamGame(clearMailbox = false)
clearSteamGameMailbox()
if (SessionState.mode == MODE_STEAM) SessionState.steamUrl
?.takeIf { it.startsWith(GAME_URL_PREFIX) }?.let { watchGameExit(it.removePrefix(GAME_URL_PREFIX), gen) }
if (SessionState.mode == MODE_STEAM) {
resolvedGameId?.let { watchGameExit(it, gen, ++gameExitWatchToken) }
}
acquireLocks()
Thread({
OrphanReaper.reap("session starting")
@@ -496,7 +540,7 @@ class SessionService : Service() {
}
}
if (!LinuxRuntime.patchedProot(this)) {
if (SessionPrefs.allowStockProot(this)) {
if (LinuxRuntime.stockProotAllowed(this)) {
Log.w(TAG, "proot: patched proot missing; droiddeck-stock-proot allows the rootfs copy")
} else {
val message = getString(R.string.session_proot_missing)
@@ -533,7 +577,7 @@ class SessionService : Service() {
val sessionDir = openSessionFolder()
try {
GameEnvironmentStore.publish(this)
SessionEvents.step("game-environment") { GameEnvironmentStore.publish(this) }
} catch (e: Exception) {
Log.e(TAG, "could not publish the game environment", e)
stopSession(-1, gen)
@@ -545,22 +589,22 @@ class SessionService : Service() {
runCatching { sessionLog.appendText(prootLine + "\n") }
.onFailure { Log.w(TAG, "could not write the proot line to ${sessionLog.path}", it) }
Log.i(TAG, GpuClockPin.start(this))
Log.i(TAG, GameThreadHints.start(this))
Log.i(TAG, SessionEvents.step("gpu-clock-pin") { GpuClockPin.start(this) })
Log.i(TAG, SessionEvents.step("thread-hints") { GameThreadHints.start(this) })
val size = SessionState.outputSize
val guest = ArrayList<String>()
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
runCatching { ComponentsManager.republish(this) }
runCatching { SessionEvents.step("components-republish") { ComponentsManager.republish(this) } }
.onSuccess { if (it) Log.i(TAG, "component selections published for the installed Proton builds") }
.onFailure { Log.w(TAG, "component selections", it) }
if (steamHere) {
runCatching { ComponentsManager.ensureForcedPackages(this) }
runCatching { SessionEvents.step("components-forced") { ComponentsManager.ensureForcedPackages(this) } }
.onSuccess { if (it != null) Log.i(TAG, it) }
.onFailure { Log.w(TAG, "forced components", it) }
}
try {
addClientEnvironment(guest, steamHere, agentEnvironment)
SessionEvents.step("client-environment") { addClientEnvironment(guest, steamHere, agentEnvironment) }
} catch (e: IllegalStateException) {
Log.e(TAG, "Could not resolve the selected Linux Vulkan driver", e)
failSession(gen, "VULKAN_DRIVER_UNAVAILABLE", e.message ?: "Selected Linux Vulkan driver is unavailable", -1)
@@ -570,8 +614,8 @@ class SessionService : Service() {
if (steamHere) guest.add("BL_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId)
val fastPathAt = guest.size
val pulse = startAudio(guest, sessionDir, directAudioPack)
startVkBridge(guest, sessionDir)
val pulse = SessionEvents.step("audio") { startAudio(guest, sessionDir, directAudioPack) }
SessionEvents.step("vk-bridge") { startVkBridge(guest, sessionDir) }
if (VenusComponent.wanted(this)) {
components.add(VenusComponent(File(sessionDir, "venus.log")).also { it.attach(this) })
}
@@ -617,20 +661,20 @@ class SessionService : Service() {
deckBinds = emptyList()
inputSysfs = null
if (controllersOn) {
addControllerEnvironment(guest, fakeInputDir, sessionDir)
SessionState.padBridge?.syncConnectedControllers()
SessionEvents.step("controller-environment") { addControllerEnvironment(guest, fakeInputDir, sessionDir) }
SessionEvents.step("controller-sync") { SessionState.padBridge?.syncConnectedControllers() }
}
val noSteamGame = noSteamGame()
if (noSteamGame) guest.add("BL_PIN_CORES=0")
if ((steamHere || SessionState.program == NoSteamLaunch.EPIC) && com.droiddeck.launcher.stores.epic.EpicClient.read(this).installed) {
runCatching { com.droiddeck.launcher.stores.epic.EpicClientLibrary.sync(this) }
runCatching { SessionEvents.step("epic-library") { com.droiddeck.launcher.stores.epic.EpicClientLibrary.sync(this) } }
.onFailure { Log.w(TAG, "Epic library sync failed", it) }
runCatching { com.droiddeck.launcher.stores.epic.EpicClient.prepareInstallDir(this) }
runCatching { SessionEvents.step("epic-install-dir") { com.droiddeck.launcher.stores.epic.EpicClient.prepareInstallDir(this) } }
.onFailure { Log.w(TAG, "Epic install directory setup failed", it) }
}
if (steamHere || noSteamGame) {
val added = com.droiddeck.launcher.frontend.AddedGames.scan(this)
val listing = com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added)
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
val listing = SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
guest.add("BL_ADDED_GAMES=" + listing.path)
if (OfflineMode.enabled(this)) guest.add("BL_STEAM_OFFLINE=1")
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("BL_LOSSLESS_OWNED=1")
@@ -642,7 +686,7 @@ class SessionService : Service() {
// Detailed graphics logs: per-game logs and the guest's Vulkan summary (a GPU that is not
// an Adreno, or Setup's switch), and graphics-report.txt for every session.
if (GraphicsReport.detailed(this)) guest.add("BL_GAME_LOGS=1")
GraphicsReport.begin(this, sessionDir, guest)
SessionEvents.step("graphics-report") { GraphicsReport.begin(this, sessionDir, guest) }
val shellGuest = ArrayList(guest).apply {
add("SHELL=/bin/bash")
add("TERM=xterm-256color")
@@ -670,7 +714,7 @@ class SessionService : Service() {
Log.i(TAG, "run: $program (${SessionState.programArgs.size} arguments) under gamescope")
}
FileUtils.clear(File(LinuxRuntime.liveDir(this), "shm"))
SessionEvents.step("shm-clear") { FileUtils.clear(File(LinuxRuntime.liveDir(this), "shm")) }
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir)
val nativeUserland = com.droiddeck.launcher.runtime.NativeGuest.enabled(this)
@@ -776,7 +820,7 @@ class SessionService : Service() {
watchLaunchRequests(sessionRoot)
watchSyncWanted(root)
EsyncPacks.fetchInBackground(this, root)
val pid = HostProcess.start(line, hostEnv.asArray(), root, { status ->
val pid = SessionEvents.step("guest-launch") { HostProcess.start(line, hostEnv.asArray(), root, { status ->
if (gen != sessionGen) {
Log.i(TAG, "an earlier session's process ended ($status); the current one carries on")
return@start
@@ -784,7 +828,7 @@ class SessionService : Service() {
val program = programStatus(sessionRoot)
Log.i(TAG, "session ended: $status" + if (program != null) " (program $program)" else "")
stopSession(program ?: status ?: -1, gen)
}, null, sessionLog.takeIf { "PROOT_PROFILE=1" in hostEnv.asArray() })
}, null, sessionLog.takeIf { "PROOT_PROFILE=1" in hostEnv.asArray() }) }
Log.i(TAG, "session pid $pid, log ${sessionLog.path}")
if (gen != sessionGen || !SessionState.running) {
Log.i(TAG, "session stopped while its guest was starting; taking it down")
@@ -872,7 +916,7 @@ class SessionService : Service() {
if (EnhancedDiagnostics.isActive(this, sessionDir)) SessionEvents.record("diagnostics.enhanced", mapOf("schema" to 1))
DeviceReport.write(this, File(sessionDir, "device.txt"), SessionState.mode)
NetworkReport.write(this, File(sessionDir, "network.txt"))
SessionLogCapture.start(File(sessionDir, "app.log"))
SessionLogCapture.start(File(sessionDir, "app.log"), SessionPaths.startedAt(sessionDir))
MemoryLog.start()
return sessionDir
}
@@ -985,6 +1029,7 @@ class SessionService : Service() {
guest.add("BL_SYNC=" + (if (SessionPrefs.fastSync(this)) "1" else "0"))
guest.add("BL_SYNC_FALLBACK=" + (if (SessionPrefs.syncFallback(this)) "1" else "0"))
guest.add("BL_FSYNC_FIRST=" + (if (SessionPrefs.fsyncFirst(this)) "1" else "0"))
guest.add("BL_PACE_CORES=" + (if (SessionPrefs.paceCores(this)) "1" else "0"))
guest.add("BL_GAMESCOPE_REALTIME=" + (if (SessionPrefs.gamescopeRealtime(this)) "1" else "0"))
if (SessionPrefs.cursorComposite(this)) guest.add("BL_CURSOR_COMPOSITE=1")
relativeMouseForSession().takeIf { it != 0 }?.let { guest.add("gamescope_relative_mouse=$it") }
@@ -992,11 +1037,13 @@ class SessionService : Service() {
guest.add("BL_ZRAM=1")
if (steamHere) SessionPrefs.ramCapMb(this).takeIf { it > 0 }?.let { guest.add("BL_RAM_CAP_MB=$it") }
if (!SessionPrefs.zramClient(this)) guest.add("BL_ZRAM_CLIENT=0")
if (!SessionPrefs.zramIdle(this)) guest.add("BL_ZRAM_IDLE=0")
}
SessionPrefs.vramCapMb(this).takeIf { it > 0 }?.let { guest.add("BL_VRAM_MB=$it") }
guest.add("AUDIO_DIRECT_DECAY=0")
val extra = extraEnv() + agentEnvironment
if (extra.none { it.startsWith("TU_DEBUG=") }) guest.add("$GAME_TU_DEBUG=" + (tuOverride ?: if (tuDriver) "sysmem" else ""))
guest.addAll(TurnipEnvironment.gameEnvironment(tuOverride, tuDriver, SessionPrefs.tuSysmem(this), extra))
if (extra.none { it.startsWith("MESA_NO_ERROR=") }) guest.add("${GAME_PREFIX}MESA_NO_ERROR=")
extra.forEach { guest.add(it) }
com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice(this)?.let { guest.add("${com.droiddeck.launcher.gpu.TpUbwcHint.ENV}=$it") }
val clientPinned = steamHere && SessionPrefs.clientCpusOverride(this)
@@ -1497,7 +1544,19 @@ class SessionService : Service() {
return
}
val accepted = gameId!!
if (pendingSteamGameId != null) Log.i(TAG, "replacing a queued game launch with $accepted")
if (!pendingSteamPreviousGamePending) {
pendingSteamPreviousGameId = SessionState.gameId
pendingSteamPreviousGamePending = true
}
if (pendingSteamGameId != null) {
Log.i(TAG, "replacing queued game ${pendingSteamGameId} with $accepted")
}
pendingSteamGameExitWatchToken = ++gameExitWatchToken
SessionState.gameId = accepted
val effectsProfileId = SessionPrefs.screenEffectsProfileId(MODE_STEAM, accepted, null)
SessionPrefs.setActiveScreenEffectsProfile(this, effectsProfileId)
SessionPrefs.screenEffects(this, effectsProfileId)
.push(SessionPrefs.screenEffectsUpscaler(this, effectsProfileId))
pendingSteamGameId = accepted
pendingSteamGameGeneration = sessionGen
if (SessionState.suspended) resumeSession()
@@ -1508,9 +1567,29 @@ class SessionService : Service() {
private fun flushQueuedSteamGame() {
val gameId = pendingSteamGameId ?: return
val gen = pendingSteamGameGeneration
val exitWatchToken = pendingSteamGameExitWatchToken
if (exitWatchToken != gameExitWatchToken) return
if (gen != sessionGen || !SessionState.running || SessionState.stopRequested ||
SessionState.mode != MODE_STEAM || !GameLaunchLink.validId(gameId)) {
SessionState.mode != MODE_STEAM || SessionState.gameId != gameId ||
!GameLaunchLink.validId(gameId)) {
val previousGameId = pendingSteamPreviousGameId
val queuedProfileId = SessionPrefs.screenEffectsProfileId(MODE_STEAM, gameId, null)
val canRestore = gen == sessionGen &&
SessionState.running && !SessionState.stopRequested &&
SessionState.mode == MODE_STEAM &&
SessionState.gameId == gameId &&
SessionPrefs.activeScreenEffectsProfileId(this) == queuedProfileId
cancelQueuedSteamGame()
if (canRestore) {
SessionState.gameId = previousGameId
val previousProfileId =
SessionPrefs.screenEffectsProfileId(MODE_STEAM, previousGameId, null)
SessionPrefs.setActiveScreenEffectsProfile(this, previousProfileId)
SessionPrefs.screenEffects(this, previousProfileId)
.push(SessionPrefs.screenEffectsUpscaler(this, previousProfileId))
}
return
}
if (SessionState.suspended) {
@@ -1537,33 +1616,95 @@ class SessionService : Service() {
}
pendingSteamGameId = null
pendingSteamGameGeneration = -1
pendingSteamGameExitWatchToken = -1
SessionEvents.record("steam.game_launch_requested", mapOf("gameId" to gameId, "generation" to gen))
watchGameExit(gameId, gen)
watchGameExit(gameId, gen, exitWatchToken, pendingSteamPreviousGameId)
Log.i(TAG, "queued Steam game $gameId for the running client")
}
private fun watchGameExit(gameId: String, gen: Int) {
if (!SessionPrefs.returnAfterGame(this)) return
val token = ++gameExitWatchToken
private fun watchGameExit(
gameId: String,
gen: Int,
token: Int,
previousGameId: String? = null
) {
Thread({
val startBy = android.os.SystemClock.elapsedRealtime() + GAME_START_TIMEOUT_MS
var startupRemaining = GAME_START_TIMEOUT_MS
var lastStartupCheck = android.os.SystemClock.elapsedRealtime()
var startupWasSuspended = false
var seen = false
var goneSince = 0L
while (token == gameExitWatchToken && gen == sessionGen && SessionState.running && !SessionState.stopRequested) {
val now = android.os.SystemClock.elapsedRealtime()
if (steamGameRunning()) {
if (!seen) Log.i(TAG, "game $gameId started; returning to the launcher when it closes")
val startupSuspended = SessionState.suspended || SessionState.suspending || SessionState.phase != SessionPhase.READY
if (!seen) {
if (startupSuspended) {
startupWasSuspended = true
lastStartupCheck = now
} else if (startupWasSuspended) {
startupWasSuspended = false
lastStartupCheck = now
} else {
startupRemaining -= (now - lastStartupCheck).coerceAtLeast(0L)
lastStartupCheck = now
}
}
if (steamGameRunning(gameId)) {
if (!seen) {
Log.i(TAG, "game $gameId started; tracking its exit")
mainHandler.post {
if (token == gameExitWatchToken && gen == sessionGen &&
pendingSteamPreviousGamePending &&
pendingSteamPreviousGameId == previousGameId) {
pendingSteamPreviousGameId = null
pendingSteamPreviousGamePending = false
}
}
}
seen = true
goneSince = 0L
} else if (!seen) {
if (now > startBy) {
Log.i(TAG, "game $gameId did not start; not watching for its exit")
if (!startupSuspended && startupRemaining <= 0L) {
mainHandler.post {
if (token != gameExitWatchToken || gen != sessionGen ||
!SessionState.running || SessionState.stopRequested) {
return@post
}
if (previousGameId != null && steamGameRunning(previousGameId)) {
Log.w(TAG, "game $gameId did not start; restoring previous game $previousGameId")
SessionState.gameId = previousGameId
val previousProfileId =
SessionPrefs.screenEffectsProfileId(MODE_STEAM, previousGameId, null)
val failedGameProfileId =
SessionPrefs.screenEffectsProfileId(MODE_STEAM, gameId, null)
if (SessionPrefs.activeScreenEffectsProfileId(this@SessionService) == failedGameProfileId) {
SessionPrefs.setActiveScreenEffectsProfile(this@SessionService, previousProfileId)
SessionPrefs.screenEffects(this@SessionService, previousProfileId)
.push(SessionPrefs.screenEffectsUpscaler(this@SessionService, previousProfileId))
}
pendingSteamPreviousGameId = null
pendingSteamPreviousGamePending = false
watchGameExit(previousGameId, gen, token)
} else {
Log.i(TAG, "game $gameId did not start; clearing its screen effects profile")
pendingSteamPreviousGameId = null
pendingSteamPreviousGamePending = false
clearActiveScreenEffectsProfile(gameId, gen, token)
}
}
return@Thread
}
} else if (goneSince == 0L) {
goneSince = now
} else if (now - goneSince >= GAME_EXIT_GRACE_MS) {
mainHandler.post { returnAfterGame(gameId, gen, token) }
mainHandler.post {
if (SessionPrefs.returnAfterGame(this@SessionService)) {
returnAfterGame(gameId, gen, token)
} else {
clearActiveScreenEffectsProfile(gameId, gen, token)
}
}
return@Thread
}
try { Thread.sleep(GAME_EXIT_POLL_MS) } catch (e: InterruptedException) { return@Thread }
@@ -1571,17 +1712,52 @@ class SessionService : Service() {
}, "game-exit-watch").start()
}
private fun returnAfterGame(gameId: String, gen: Int, token: Int) {
if (token != gameExitWatchToken || gen != sessionGen || !SessionState.running ||
SessionState.stopRequested || SessionState.mode != MODE_STEAM || !SessionPrefs.returnAfterGame(this)) return
val written = runCatching { File(LinuxRuntime.sessionRoot(this), "steam-stop").writeText("") }
.onFailure { Log.w(TAG, "could not ask the client to exit after game $gameId", it) }.isSuccess
if (!written) return
SessionEvents.record("steam.return_after_game", mapOf("gameId" to gameId))
Log.i(TAG, "game $gameId closed: asking the client to exit and returning to the launcher")
private fun clearActiveScreenEffectsProfile(gameId: String, gen: Int, token: Int) {
if (token != gameExitWatchToken || gen != sessionGen || !SessionState.running || SessionState.stopRequested) return
val gameProfileId = SessionPrefs.screenEffectsProfileId(MODE_STEAM, gameId, null)
if (SessionPrefs.activeScreenEffectsProfileId(this) != gameProfileId) return
SessionPrefs.setActiveScreenEffectsProfile(this, null)
SessionPrefs.screenEffects(this, null).push(SessionPrefs.screenEffectsUpscaler(this, null))
}
private fun steamGameRunning(): Boolean = SteamGameProcess.running()
private fun returnAfterGame(gameId: String, gen: Int, token: Int) {
mainHandler.postDelayed({
if (token != gameExitWatchToken || gen != sessionGen || !SessionState.running ||
SessionState.stopRequested || SessionState.mode != MODE_STEAM ||
SessionState.gameId != gameId || pendingSteamGameId != null) {
return@postDelayed
}
if (steamGameRunning(gameId)) {
Log.i(TAG, "game $gameId is running again; restarting its exit watcher")
watchGameExit(gameId, gen, token)
return@postDelayed
}
if (SteamGameProcess.running()) {
Log.i(TAG, "another Steam game is still running after $gameId; checking again")
returnAfterGame(gameId, gen, token)
return@postDelayed
}
clearActiveScreenEffectsProfile(gameId, gen, token)
if (!SessionPrefs.returnAfterGame(this)) {
Log.i(TAG, "return after game disabled; keeping the Steam session open")
return@postDelayed
}
val written = runCatching { File(LinuxRuntime.sessionRoot(this), "steam-stop").writeText("") }
.onFailure { Log.w(TAG, "could not ask the client to exit after game $gameId", it) }.isSuccess
if (!written) return@postDelayed
SessionEvents.record("steam.return_after_game", mapOf("gameId" to gameId))
Log.i(TAG, "game $gameId closed: asking the client to exit and returning to the launcher")
}, GAME_EXIT_CONFIRM_MS)
}
private fun steamGameRunning(gameId: String): Boolean =
SteamGameProcess.running(gameId)
private fun resumeSession(panelVisible: Boolean = true) {
if (SessionState.suspended) SessionState.resumeRequested = true
@@ -1601,7 +1777,11 @@ class SessionService : Service() {
private fun cancelQueuedSteamGame(clearMailbox: Boolean = true) {
mainHandler.removeCallbacks(flushSteamGame)
pendingSteamGameId = null
pendingSteamPreviousGameId = null
pendingSteamPreviousGamePending = false
pendingSteamGameGeneration = -1
pendingSteamGameExitWatchToken = -1
gameExitWatchToken++
if (clearMailbox) clearSteamGameMailbox()
}
@@ -2084,10 +2264,11 @@ class SessionService : Service() {
syncWatcher = null
val prootPid = sessionPid
sessionPid = -1
// The kept shell goes through the same teardown, which reads its descendants before signalling it.
val shell = SessionTerminal.detach(sessionGen)?.let { pid -> readStat(pid)?.second?.let { pid to it } }
val auxiliary = synchronized(auxiliaryProcessesLock) {
auxiliaryProcesses.toMap().also { auxiliaryProcesses.clear() }
}
SessionTerminal.clear(sessionGen)
} + listOfNotNull(shell)
BottomDesktop.stop(this, stoppedGen)
val controller = suspendController
suspendController = null
@@ -2376,7 +2557,7 @@ class SessionService : Service() {
private const val TRACER_NICE = -6
private const val MIC_RELEASE_TIMEOUT_MS = 5_000L
private const val TU_DEBUG_SWITCH = "Download/droiddeck-tu-debug"
private const val GAME_TU_DEBUG = "DROIDDECK_GAME_TU_DEBUG"
private const val GAME_PREFIX = "DROIDDECK_GAME_"
private const val LEGACY_ENV_SWITCH = "Download/droiddeck-env"
private const val ENV_SWITCH_NAME = "droiddeck-env"
@@ -2406,6 +2587,8 @@ class SessionService : Service() {
private const val ACTION_XR_ACTIVITY_HIDDEN = "com.droiddeck.launcher.XR_ACTIVITY_HIDDEN"
private const val ACTION_SIGN_IN_HOLD = "com.droiddeck.launcher.SIGN_IN_HOLD"
private const val EXTRA_HOLD = "hold"
private const val ACTION_BROWSER_HANDOFF = "com.droiddeck.launcher.BROWSER_HANDOFF"
private const val BROWSER_HANDOFF_TIMEOUT_MS = 10 * 60_000L
private const val ACTION_TRACK_AUXILIARY = "com.droiddeck.launcher.TRACK_AUXILIARY"
private const val ACTION_STOP_AUXILIARY = "com.droiddeck.launcher.STOP_AUXILIARY"
private const val ACTION_AUXILIARY_EXITED = "com.droiddeck.launcher.AUXILIARY_EXITED"
@@ -2422,6 +2605,7 @@ class SessionService : Service() {
private const val GAME_URL_PREFIX = "steam://rungameid/"
private const val GAME_START_TIMEOUT_MS = 20 * 60_000L
private const val GAME_EXIT_GRACE_MS = 10_000L
private const val GAME_EXIT_CONFIRM_MS = 2_000L
private const val GAME_EXIT_POLL_MS = 2_000L
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
private const val NO_UINPUT_SWITCH = "Download/droiddeck-no-uinput"
@@ -2508,6 +2692,11 @@ class SessionService : Service() {
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_SIGN_IN_HOLD).putExtra(EXTRA_HOLD, hold))
}
fun holdForBrowserHandoff(context: Context) {
if (!SessionState.running) return
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_BROWSER_HANDOFF))
}
fun pause(context: Context) {
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_PAUSE_NOW))
}
@@ -14,6 +14,12 @@ object SessionTerminal {
@Volatile private var launch: Launch? = null
private class Kept(val session: TerminalSession, val generation: Int)
// The bottom screen's presentation is dismissed whenever another app covers that display
// (a browser opened for a sign-in), so its shell is kept for the next panel.
@Volatile private var kept: Kept? = null
fun prepare(
command: List<String>,
hostEnvironment: Array<String>,
@@ -32,8 +38,41 @@ object SessionTerminal {
).also { it.mSessionName = "DroidDeck Linux shell" }
}
fun reuse(client: TerminalSessionClient): TerminalSession? {
val current = kept ?: return null
if (current.generation != launch?.generation || !current.session.isRunning) {
kept = null
return null
}
current.session.updateTerminalSessionClient(client)
return current.session
}
fun keep(session: TerminalSession) {
val generation = launch?.generation ?: return
kept = Kept(session, generation)
}
fun release(session: TerminalSession?) {
if (session != null && kept?.session === session) kept = null
}
fun clear(generation: Int? = null) {
val current = launch ?: return
if (generation == null || current.generation == generation) launch = null
if (generation == null || current.generation == generation) {
launch = null
kept?.session?.takeIf { it.pid > 0 }?.finishIfRunning()
kept = null
}
}
/** Ends this generation's terminal without killing its shell, and returns the shell's pid if it still runs. */
fun detach(generation: Int): Int? {
val current = launch ?: return null
if (current.generation != generation) return null
launch = null
val pid = kept?.session?.takeIf { it.isRunning && it.pid > 0 }?.pid
kept = null
return pid
}
}
@@ -16,17 +16,17 @@ object SettingsReset {
"dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
"gameStoresEnabled", "soundtracksEnabled", "soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "picturePosition", "railLabels", "agentTab", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"stretch16x9", "picturePosition", "integerScaling", "railLabels", "agentTab", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores", "ramCapMb", "vramCapMb", "zramClient", "zramIdle",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark",
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
"bootMovieApplyNext", "bootMovieSteamSeen",
"upscaler", "upscaleSharpness", "screenEffects", "blackFrameInsertion", "textureAnisotropy", "textureLodBias",
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds", "skipBootMovie",
"bootMovieApplyNext", "bootMovieSteamSeen", "bootMovieShuffle",
"questDefaultsV1", "telemetryAuto", "telemetryOff", "statsStrip", "statsHud", "bottomHud", "bottomStripMetrics", "bottomStripTabs", "statsDash", "statsSpeedUnit",
)
@@ -5,14 +5,59 @@ import java.io.File
object SteamGameProcess {
fun matches(cmdline: ByteArray): Boolean {
val args = String(cmdline).split('\u0000')
for (i in args.indices) {
if (args[i] == "waitforexitandrun") return true
if (args[i] == "SteamLaunch" && args.getOrNull(i + 1)?.startsWith("AppId=") == true) return true
return args.indices.any { i ->
args[i] == "waitforexitandrun" ||
(args[i] == "SteamLaunch" &&
args.getOrNull(i + 1)?.startsWith("AppId=") == true)
}
}
fun running(): Boolean =
File("/proc").listFiles()?.any { p ->
p.name.all(Char::isDigit) &&
runCatching { File(p, "cmdline").readBytes() }
.getOrNull()?.let(::matches) == true
} == true
private fun steamAppIdForGameId(gameId: String): String? {
if (gameId.isEmpty() || !gameId.all(Char::isDigit)) return null
val numericId = gameId.toULongOrNull() ?: return null
val appId = if (numericId > UInt.MAX_VALUE.toULong()) {
numericId shr 32
} else {
numericId
}
return appId.takeIf { it != 0uL }?.toString()
}
fun matches(cmdline: ByteArray, gameId: String): Boolean {
val expectedAppId = steamAppIdForGameId(gameId) ?: return false
val args = String(cmdline).split('\u0000')
for (i in args.indices) {
if (args[i] == "SteamLaunch") {
val appId = args.getOrNull(i + 1)
?.takeIf { it.startsWith("AppId=") }
?.removePrefix("AppId=")
if (appId == expectedAppId) return true
}
if (args[i] == "-applaunch" &&
args.getOrNull(i + 1) == expectedAppId
) {
return true
}
}
return false
}
fun running(proc: File = File("/proc")): Boolean = proc.listFiles()?.any { p ->
p.name.all(Char::isDigit) && runCatching { File(p, "cmdline").readBytes() }.getOrNull()?.let(::matches) == true
} == true
fun running(gameId: String, proc: File = File("/proc")): Boolean =
proc.listFiles()?.any { p ->
p.name.all(Char::isDigit) &&
runCatching { File(p, "cmdline").readBytes() }
.getOrNull()?.let { matches(it, gameId) } == true
} == true
}
@@ -0,0 +1,16 @@
package com.droiddeck.launcher.session
internal object TurnipEnvironment {
const val GAME_TU_DEBUG = "DROIDDECK_GAME_TU_DEBUG"
fun gameEnvironment(
tuOverride: String?,
tuDriver: Boolean,
tuSysmem: Boolean,
extra: List<String>,
): List<String> = if (extra.none { it.startsWith("TU_DEBUG=") }) {
listOf("$GAME_TU_DEBUG=${tuOverride ?: if (tuDriver || tuSysmem) "sysmem" else ""}")
} else {
emptyList()
}
}
@@ -25,9 +25,11 @@ object CloudSaves {
private const val PARALLEL = 6
private const val CLOUD_LAYOUT = 2
class Result(val result: String, val files: Int, val bytes: Long, val reason: String, val conflicts: Int = 0) {
class Result(val result: String, val files: Int, val bytes: Long, val reason: String, val conflicts: Int = 0, val detail: String = "") {
val ok: Boolean get() = result != "failed"
val line: String get() = "result=$result files=$files bytes=$bytes reason=$reason" + if (conflicts > 0) " conflicts=$conflicts" else ""
val line: String get() = "result=$result files=$files bytes=$bytes reason=$reason" +
(if (conflicts > 0) " conflicts=$conflicts" else "") +
if (detail.isNotEmpty()) " detail=\"$detail\"" else ""
}
class Status(val supported: Boolean, val folder: File?, val lastSync: Long, val reason: String, val conflicts: List<String> = emptyList())
@@ -126,7 +128,7 @@ object CloudSaves {
)
if (picked == null) GogConfig("", "") else GogConfig(picked.name, picked.template)
} catch (e: Exception) {
Log.w(TAG, "gog remote-config: ${e.javaClass.simpleName}")
Log.w(TAG, "gog remote-config: ${cloudFailureDetail(e)}")
null
}
}
@@ -166,7 +168,7 @@ object CloudSaves {
val galaxy = GogAuth.validToken(context)
val clientId = gogClientId(context, id, folder)
if (userId.isEmpty() || galaxy == null || clientId == null) null
else GogCloud(userId, clientId, gogScopedToken(context, id, clientId) ?: galaxy, gogLocationName(context, id, folder))
else GogCloud(userId, clientId, gogScopedToken(context, id, clientId) ?: galaxy, gogLocationName(context, id, folder), tempDir = context.cacheDir)
}
Store.EPIC -> {
val token = EpicCredentialStore.getValidAccessToken(context)
@@ -312,7 +314,7 @@ object CloudSaves {
rememberNoCloud(prefs(context, store), id)
Result("skipped", 0, 0, "no-cloud-saves")
} catch (e: Exception) {
Result("failed", 0, 0, e.javaClass.simpleName)
Result("failed", 0, 0, e.javaClass.simpleName, detail = cloudFailureDetail(e))
}
return done(store, id, way, result)
}
@@ -59,6 +59,69 @@ private fun httpDate(s: String?): Long = try {
SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US).apply { timeZone = TimeZone.getTimeZone("GMT") }.parse(s!!.trim())?.time ?: -1L
} catch (e: Exception) { -1L }
private val SECRET_PARAM = Regex("(?i)(token|secret|code|password|authorization)([\"']?\\s*[:=]\\s*[\"']?)[^\\s&\"',;}]+")
private val BEARER = Regex("(?i)bearer\\s+\\S+")
private val URL_TEXT = Regex("(?i)https?://(?:[^/\\s?#@]*@)?([^/\\s?#@]+)[^\\s]*")
private val LONG_TOKEN = Regex("[A-Za-z0-9._~+/=-]{32,}")
private val SPACES = Regex("\\s+")
private const val DETAIL_MAX = 400
internal fun scrubCloudText(text: String, longTokens: Boolean = true): String = text
.replace(BEARER, "Bearer <redacted>")
.replace(URL_TEXT) { it.groupValues[1] }
.replace(SECRET_PARAM) { it.groupValues[1] + it.groupValues[2] + "<redacted>" }
.let { if (longTokens) it.replace(LONG_TOKEN, "<redacted>") else it }
.replace(SPACES, " ")
.trim()
internal fun cloudFailureDetail(e: Throwable): String {
val parts = ArrayList<String>()
var t: Throwable? = e
while (t != null && parts.size < 3) {
val message = t.message?.let { scrubCloudText(it, longTokens = false) }.orEmpty()
parts += if (message.isEmpty()) t.javaClass.simpleName else "${t.javaClass.simpleName}: $message"
t = t.cause?.takeIf { it !== t }
}
return parts.joinToString(" <- ").take(DETAIL_MAX)
}
private const val SNIPPET_READ_MAX = 4096
private const val SNIPPET_MAX = 120
private data class CloudErrorPrefix(val text: String, val truncated: Boolean) {
fun snippet(): String {
val safe = if (truncated) text.substring(0, text.indexOfLast { it.isWhitespace() }.coerceAtLeast(0)) else text
return scrubCloudText(safe).take(SNIPPET_MAX)
}
}
private fun cloudErrorPrefix(input: InputStream?): CloudErrorPrefix {
if (input == null) return CloudErrorPrefix("", false)
return input.use { stream ->
val buffer = ByteArray(SNIPPET_READ_MAX + 1)
var read = 0
while (read < buffer.size) {
val n = stream.read(buffer, read, buffer.size - read)
if (n < 0) break
read += n
}
CloudErrorPrefix(buffer.decodeToString(0, minOf(read, SNIPPET_READ_MAX)), read > SNIPPET_READ_MAX)
}
}
internal fun cloudErrorSnippet(input: InputStream?): String =
cloudErrorPrefix(input).snippet()
private fun HttpURLConnection.errorSnippet(): String =
runCatching { cloudErrorSnippet(errorStream) }.getOrDefault("")
private fun httpFailure(step: String, name: String?, code: Int, error: String): java.io.IOException =
java.io.IOException(buildString {
append("GOG cloud ").append(step).append(" HTTP ").append(code)
if (name != null) append(" file=").append(name)
if (error.isNotEmpty()) append(" body=").append(error)
})
internal fun isGzip(data: ByteArray) =
data.size >= 10 && data[0] == 0x1f.toByte() && data[1] == 0x8b.toByte() && data[2] == 0x08.toByte()
@@ -183,6 +246,8 @@ private fun gzipFile(src: File, dst: File): GzipFile {
}
}
internal const val GOG_CLOUD_UA = "GOGGalaxyCommunicationService/2.0.13.27 (Windows_32bit) dont_sync_marker/true installation_source/gog"
/** GOG Galaxy parses `X-Object-Meta-LocalLastModified`; objects without it fail as "invalid data". */
private val GOG_STAMP = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssxxx", Locale.US)
@@ -195,9 +260,10 @@ class GogCloud(
private val token: String,
private val location: String? = null,
baseUrl: String? = null,
private val tempDir: File? = null,
) : CloudTransport {
private val base = baseUrl ?: "https://cloudstorage.gog.com/v1/$userId/$clientId"
private val ua = "GOG Galaxy"
private val ua = GOG_CLOUD_UA
private var prefix: String? = location?.let { "$it/" }
private fun key(name: String) = URLEncoder.encode(name, "UTF-8").replace("+", "%20")
@@ -209,10 +275,10 @@ class GogCloud(
val code = c.responseCode
if (code == 404) { c.disconnect(); return emptyList() }
if (code !in 200..299) {
val err = runCatching { c.errorStream?.readBytes()?.decodeToString().orEmpty() }.getOrDefault("")
val err = runCatching { cloudErrorPrefix(c.errorStream) }.getOrDefault(CloudErrorPrefix("", false))
c.disconnect()
if ("not_enabled_for_client" in err || "disabled" in err) throw NoCloudSaves()
throw java.io.IOException("GOG cloud list HTTP $code")
if ("not_enabled_for_client" in err.text || "disabled" in err.text) throw NoCloudSaves()
throw httpFailure("list", null, code, err.snippet())
}
val text = c.body().decodeToString().trim()
c.disconnect()
@@ -255,12 +321,20 @@ class GogCloud(
override fun get(file: CloudFile): Pair<ByteArray, Long> {
val c = open("$base/${cloudKey(file.name)}", "GET", token, ua)
c.setRequestProperty("Accept-Encoding", "identity")
if (c.responseCode !in 200..299) { val code = c.responseCode; c.disconnect(); throw java.io.IOException("GOG cloud get HTTP $code") }
if (c.responseCode !in 200..299) {
val code = c.responseCode
val err = c.errorSnippet()
c.disconnect()
throw httpFailure("get", file.name, code, err)
}
val modified = httpDate(c.getHeaderField("Last-Modified"))
val encoding = c.getHeaderField("Content-Encoding")
val data = c.body()
c.disconnect()
return gogDecodeCloudBody(data, encoding) to modified
val data = try { c.body() } finally { c.disconnect() }
return try {
gogDecodeCloudBody(data, encoding) to modified
} catch (e: java.io.IOException) {
throw java.io.IOException("GOG cloud get file=${file.name} bytes=${data.size} encoding=$encoding", e)
}
}
override fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long>): Map<String, Long> = files.mapValues { (name, data) ->
@@ -269,7 +343,11 @@ class GogCloud(
}
override fun putFiles(files: Map<String, File>, modifiedMs: Map<String, Long>): Map<String, CloudPut> = files.mapValues { (name, file) ->
val compressed = File.createTempFile("gog-cloud-", ".gz")
val compressed = try {
File.createTempFile("gog-cloud-", ".gz", tempDir?.apply { mkdirs() })
} catch (e: java.io.IOException) {
throw java.io.IOException("GOG cloud put file=$name temp file", e)
}
try {
val gz = gzipFile(file, compressed)
val modified = putBody(name, compressed.inputStream(), gz.length, gz.etag, modifiedMs[name] ?: file.lastModified())
@@ -287,10 +365,16 @@ class GogCloud(
c.setRequestProperty("Content-Encoding", "gzip")
c.setRequestProperty("Etag", etag)
c.setRequestProperty("X-Object-Meta-LocalLastModified", gogStamp(modified))
c.setRequestProperty("X-Object-Meta-User-Agent", ua)
c.setFixedLengthStreamingMode(length)
c.outputStream.use { out -> source.use { it.copyTo(out, 64 * 1024) } }
try {
c.outputStream.use { out -> source.use { it.copyTo(out, 64 * 1024) } }
} catch (e: java.io.IOException) {
val code = runCatching { c.responseCode }.getOrNull()
throw java.io.IOException("GOG cloud put file=$name bytes=$length" + (code?.let { " HTTP $it" } ?: ""), e)
}
val code = c.responseCode
if (code !in 200..299) throw java.io.IOException("GOG cloud put HTTP $code")
if (code !in 200..299) throw httpFailure("put", name, code, c.errorSnippet())
return CloudFile(name, -1L).also { details(it) }.modifiedMs
} finally {
c.disconnect()
@@ -80,6 +80,11 @@ object StoreLaunchRequests {
lastLaunched = Store.ROCKSTAR to request.optString("id")
com.droiddeck.launcher.stores.rockstar.RockstarLaunch.prepare(app, request.optString("id"))
}.getOrElse { JSONObject().put("ok", false).put("reason", "error-" + it.javaClass.simpleName) }
"store-service" -> runCatching {
val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app)
if (com.droiddeck.launcher.session.SessionFiles.awaitStoreService(app, request.optString("store"), root)) JSONObject().put("ok", true)
else JSONObject().put("ok", false).put("reason", "service-unavailable")
}.getOrElse { JSONObject().put("ok", false).put("reason", "error-" + it.javaClass.simpleName) }
"rockstar-exited" -> {
if (lastLaunched == (Store.ROCKSTAR to request.optString("id"))) lastLaunched = null
JSONObject().put("ok", true)
@@ -114,6 +119,7 @@ object StoreLaunchRequests {
if (!(url.startsWith("https://") || url.startsWith("http://"))) JSONObject().put("ok", false).put("reason", "not-http")
else try {
app.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
com.droiddeck.launcher.session.SessionService.holdForBrowserHandoff(app)
Log.i(TAG, "open-url: " + StoreLog.redactUrl(url))
JSONObject().put("ok", true)
} catch (e: Exception) {
@@ -111,16 +111,22 @@ object BattleNetInstall {
fun update(context: Context, game: InstalledStoreGame) {
val app = context.applicationContext
Thread({
val item = CatalogItem(
Store.BATTLENET, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover, owned = true,
extra = mapOf(INSTALL_UID to installUid(app, game)),
)
val item = updateItem(game, installUid(app, game))
game.folder.parentFile?.parentFile?.let { com.droiddeck.launcher.stores.download.SavedQueue.remember(app, item, it) }
enqueue(app, item, game.folder, update = true)
}, "battlenet-update").start()
}
internal fun updateItem(game: InstalledStoreGame, uid: String) = CatalogItem(
Store.BATTLENET, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover, owned = true,
extra = mapOf(INSTALL_UID to uid, UPDATE_FOLDER to game.folder.absolutePath),
)
internal fun updateFolder(item: CatalogItem): File? = item.extra[UPDATE_FOLDER]?.let(::File)
internal const val INSTALL_UID = "installUid"
internal const val UPDATE_FOLDER = "updateFolder"
internal const val STALLED = "stalled"
internal fun installUid(context: Context, game: InstalledStoreGame): String =
runCatching { BattleNet.games(context).firstOrNull { it.uid == game.sidecar.id }?.installUid }.getOrNull() ?: game.sidecar.id
@@ -219,6 +225,7 @@ object BattleNetInstall {
val detail = when {
reason == null -> "exit $code"
reason == "client" -> return context.getString(R.string.bnet_dl_client_first)
reason == STALLED -> return context.getString(R.string.bnet_dl_stalled)
reason.startsWith("agent ") -> context.getString(R.string.bnet_dl_agent_error, reason.removePrefix("agent "))
else -> reason.removePrefix("stopped ")
}
@@ -192,6 +192,7 @@ object BattleNetBackend : StoreBackend {
override fun install(context: Context, item: CatalogItem, root: File) {
if (!BattleNetInstall.headless(item)) return BattleNetClient.installGame(context, item.id, root)
val app = context.applicationContext
BattleNetInstall.updateFolder(item)?.let { return BattleNetInstall.enqueue(app, item, it, update = true) }
BattleNetInstall.enqueue(app, item, StoreInstallRoot.folderFor(app, store, item.id, item.title, root))
}
@@ -84,6 +84,11 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
Store.EPIC, item.id, item.title, cover = item.imageUrl, bytesTotal = item.sizeBytes,
location = StoreInstallRoot.labelFor(app, folder),
)
val launcher = item.extra["thirdPartyManagedApp"].orEmpty()
if (launcher.isNotBlank()) {
DownloadQueue.recordFailed(app, entry, app.getString(R.string.epic_third_party_managed, launcher))
return
}
DownloadQueue.enqueue(app, entry) { EpicInstaller(app, item, folder) }
}
@@ -21,19 +21,61 @@ import java.security.MessageDigest
import java.util.concurrent.atomic.AtomicBoolean
internal object EpicClientSources {
const val LAUNCHER_URL = "https://launcher-public-service-prod06.ol.epicgames.com/launcher/api/installer/download/EpicGamesLauncher-x86_64.AppImage"
const val LAUNCHER_FILE = "EpicGamesLauncher-x86_64.AppImage"
const val LAUNCHER_URL = "https://launcher-public-service-prod06.ol.epicgames.com/launcher/api/installer/download/EpicGamesLauncher-x86_64.deb"
const val LAUNCHER_FILE = "EpicGamesLauncher-x86_64.deb"
const val RUNTIME_BASE = "https://repo.steampowered.com/steamrt4/images/"
const val RUNTIME_FILE = "com.valvesoftware.SteamRuntime.Platform-amd64,i386-steamrt4-runtime.tar.gz"
const val GLES_URL = "https://deb.debian.org/debian/pool/main/libg/libglvnd/libgles2_1.7.0-1+b2_amd64.deb"
const val GLES_FILE = "libgles2_1.7.0-1+b2_amd64.deb"
const val GLES_SHA256 = "e12c18aa77939d122ee1dea520ba0440b97dc19200b7396e03dff03a3ece74c1"
const val DEBIAN = "https://deb.debian.org/debian/"
const val SNAPSHOT = "https://snapshot.debian.org/archive/debian/20261101T000000Z/"
const val USER_AGENT = "DroidDeck"
private val VERSION = Regex("[A-Za-z0-9._+-]{1,64}")
private val SUM = Regex("^([0-9a-fA-F]{64})\\s+\\*?(.+)$")
class Source(val url: String, val version: String, val sha256: String? = null)
class Package(val path: String, val sha256: String, val size: Long) {
val file: String get() = path.substringAfterLast('/')
val urls: List<String> get() = listOf(DEBIAN + path, SNAPSHOT + path)
}
val DESKTOP = listOf(
Package("pool/main/a/abseil/libabsl20240722_20240722.0-4_amd64.deb", "78c6d7692890990a27cb1d5bbd95b7bfe47a4183ffafec5b30f689f9b58ec6f7", 491548L),
Package("pool/main/a/aom/libaom3_3.12.1-1+deb13u1_amd64.deb", "743eec7c94ae30295bc557ebac3dfae948e7390e89a2743c585d56297e9d312e", 1871712L),
Package("pool/main/a/aspell/libaspell15_0.60.8.1-4_amd64.deb", "8be22785198a4e5de1e2c3a157e8cd99ec7d5843c8ac96a174ec701ba4ac28e2", 337684L),
Package("pool/main/a/at-spi2-core/libatk-bridge2.0-0t64_2.56.2-1+deb13u2_amd64.deb", "c0fe87ea1bdca2f938eaa8286af5ad38ecd15cf18c6cfb5961d7d46ac3192325", 68516L),
Package("pool/main/a/at-spi2-core/libatspi2.0-0t64_2.56.2-1+deb13u2_amd64.deb", "65e9c9ecbd820fba2d04104cddd0bad33d256cbdfe0d1cb5365f10e363df2315", 81056L),
Package("pool/main/liba/libavif/libavif16_1.2.1-1.2_amd64.deb", "ba6c334454d3562560ad583fbe2c998e203b0fc5a0e0e91112ddcd3cff4704bb", 133120L),
Package("pool/main/libc/libcloudproviders/libcloudproviders0_0.3.6-2_amd64.deb", "a626bb23ed9ebc4bc3ce446b552048de63d76768bf0fb492754965c5ee28a7e4", 29232L),
Package("pool/main/c/colord/libcolord2_1.4.7-3_amd64.deb", "f11fd3b492781122edf0790f1e1fe24c51a41c67d4bb76cff84a9426c5654fa7", 139204L),
Package("pool/main/e/enchant-2/libenchant-2-2_2.8.2+dfsg1-3_amd64.deb", "83f208d89db1c48e6ede8a23e8ffa2bcddd4f99427bfd1279201247bbf27ca58", 56756L),
Package("pool/main/libe/libepoxy/libepoxy0_1.5.10-2_amd64.deb", "4c4c8024f2175086de65bca9fdc3fbb967f2863ebf249d489c66d0c8103dd3a3", 192728L),
Package("pool/main/libe/libevdev/libevdev2_1.13.4+dfsg-1_amd64.deb", "02e85fb9461b85b23f775d5fcf5a31c55d37bec40b63fd98ca5d3a2763714ae7", 32372L),
Package("pool/main/f/flite/libflite1_2.2-7_amd64.deb", "5945190970be7d4a1f71fb6f7e3e340ba2675e770605df0754051d617a6c5ee6", 12811404L),
Package("pool/main/libg/libgav1/libgav1-1_0.19.0-3+b1_amd64.deb", "94010041e59c7a8d2d3d1f5e62afd523f002b7b1caa3189419160b66d71c0195", 352956L),
Package("pool/main/g/gst-plugins-base1.0/libgstreamer-gl1.0-0_1.26.2-1+deb13u1_amd64.deb", "efacc61acbd44a6a067612e4592b9fe81efdc5011ed4c6cf7afd8ed83c5f834a", 269984L),
Package("pool/main/g/gst-plugins-base1.0/libgstreamer-plugins-base1.0-0_1.26.2-1+deb13u1_amd64.deb", "a20aedb3f89c162b4859cec37076f4eba54b0bcc7e5cb254a26cc4a877a88a1e", 997404L),
Package("pool/main/g/gstreamer1.0/libgstreamer1.0-0_1.26.2-2_amd64.deb", "08b463307fbde5496a346b1bb300b465cd22bd326f6f4634f482bf441af28a9b", 1421116L),
Package("pool/main/g/gtk+3.0/libgtk-3-0t64_3.24.49-3_amd64.deb", "4aa8828f01365f937f3bf69f812c8107ee4c8a2b208ffdd7656e8de5de81d98f", 2768812L),
Package("pool/main/h/hidapi/libhidapi-hidraw0_0.14.0-1+b2_amd64.deb", "89c546cb55be403ce63fe668baff2515979100a30fa07e2b97de186b9c07f01e", 12664L),
Package("pool/main/h/hunspell/libhunspell-1.7-0_1.7.2+really1.7.2-10+b4_amd64.deb", "a9427e5220e71f8c04c6c0f87826c6fef98e2bab6994a87d6d82e8a120790ecf", 236980L),
Package("pool/main/h/highway/libhwy1t64_1.2.0-2+b2_amd64.deb", "540c4ff28255fbfa89468061b722dfc2b773b0c1ecf163a063202482dea5b119", 676044L),
Package("pool/main/h/hyphen/libhyphen0_2.8.8-7+b2_amd64.deb", "fa9dca7b8cf1381fd52800c44a385c5725a78a88bd705f7c39b1046a5293435e", 30664L),
Package("pool/main/w/webkit2gtk/libjavascriptcoregtk-4.1-0_2.52.6-1~deb13u1_amd64.deb", "3383ebb3e13f31225c65f41112420be58493a3de112b5993cf5c417cfedc47c8", 7511632L),
Package("pool/main/j/jpeg-xl/libjxl0.11_0.11.2-0.1~deb13u2_amd64.deb", "cd1ca3a52cb0d8fdce1d994bcbf0663de28c64add1cfe8096639ae8fa9808824", 1133312L),
Package("pool/main/l/lcms2/liblcms2-2_2.16-2+deb13u2_amd64.deb", "32e53c2002ccea8c60c02779bea0ba49ac132fef702988a30d64af79b6617806", 160264L),
Package("pool/main/libm/libmanette/libmanette-0.2-0_0.2.12-1_amd64.deb", "98841a467692c46fd1870275113235691ebbfe71a3524f6b2a0fa7e9c33c6e56", 43752L),
Package("pool/main/o/orc/liborc-0.4-0t64_0.4.41-1_amd64.deb", "5b9afe78be0dd71399c0d4d7e5f26beb6ddf207279997942d8280be1b20bd58c", 189604L),
Package("pool/main/r/rust-rav1e/librav1e0.7_0.7.1-9+b2_amd64.deb", "d5b1373a8d6905ee4523faf1db7a626dc660e03836ec91b616e57ba386f47eb6", 946396L),
Package("pool/main/libs/libsecret/libsecret-1-0_0.21.7-1_amd64.deb", "949c5428cd3427486ac6c4dfc6d9400ce786c504c02334acc903c873aa52d14f", 111224L),
Package("pool/main/s/svt-av1/libsvtav1enc2_2.3.0+dfsg-1_amd64.deb", "cdaf961c3cc4fe78a19ff18c17d83d813f78a378fdcc4c86ccbb9b54e84ae599", 2489492L),
Package("pool/main/w/webkit2gtk/libwebkit2gtk-4.1-0_2.52.6-1~deb13u1_amd64.deb", "6471d989a61a56a7801e88e420789aa6b0eaba630a9787365bba8b9576b7ba1c", 24163372L),
Package("pool/main/libx/libxslt/libxslt1.1_1.1.35-1.2+deb13u3_amd64.deb", "c8e5a745ca3afaa079b01e0c00d80a241101d1ab840407fcd4bb423de3326160", 233128L),
Package("pool/main/liby/libyuv/libyuv0_0.0.1904.20250204-1_amd64.deb", "1a6827fe94fa5572a032332df7313ed408e9c0ad78f3a1248391bddc6d920ef2", 173700L),
)
fun launcher(): Source? {
val location = redirect(LAUNCHER_URL) ?: return null
val version = launcherVersion(location) ?: return null
@@ -142,12 +184,13 @@ internal object EpicClientSources {
private fun hex(bytes: ByteArray): String = bytes.joinToString("") { "%02x".format(it) }
fun isAppImage(file: File): Boolean = runCatching {
private val DEB_MAGIC = "!<arch>\ndebian-binary".toByteArray(Charsets.US_ASCII)
fun isDeb(file: File): Boolean = runCatching {
RandomAccessFile(file, "r").use { raf ->
val head = ByteArray(11)
val head = ByteArray(DEB_MAGIC.size)
raf.readFully(head)
head[0] == 0x7f.toByte() && head[1] == 'E'.code.toByte() && head[2] == 'L'.code.toByte() && head[3] == 'F'.code.toByte() &&
head[8] == 'A'.code.toByte() && head[9] == 'I'.code.toByte() && head[10] == 2.toByte()
head.contentEquals(DEB_MAGIC)
}
}.getOrDefault(false)
}
@@ -156,9 +199,10 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
private val cancelled = AtomicBoolean(false)
@Volatile private var connection: HttpURLConnection? = null
private class Part(val url: String, val file: File, val sha256: String?, val appImage: Boolean) {
var size = -1L
private class Part(val urls: List<String>, val file: File, val sha256: String?, val launcher: Boolean, var size: Long = -1L) {
var mirror = 0
var mismatch: String? = null
val url: String get() = urls[mirror]
}
override fun run(handle: DownloadQueue.JobHandle): String? {
@@ -173,17 +217,15 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
val needRuntime = !(before.runtimeVersion == runtime.version && File(state, "runtime/${runtime.version}/.droiddeck-ready").isFile)
val dir = EpicClient.downloadsDir(app).apply { mkdirs() }
val gles = EpicClientSources.gles()
val parts = buildList {
if (needApp) add(Part(launcher.url, File(dir, "${launcher.version}-${EpicClientSources.LAUNCHER_FILE}"), null, true))
if (needRuntime) {
add(Part(runtime.url, File(dir, "steamrt4-${runtime.version}.tar.gz"), runtime.sha256, false))
add(Part(gles.url, File(dir, EpicClientSources.GLES_FILE), gles.sha256, false))
}
}
val appPart = if (needApp) Part(listOf(launcher.url), File(dir, "${launcher.version}-${EpicClientSources.LAUNCHER_FILE}"), null, true) else null
val desktopParts = if (needApp) EpicClientSources.DESKTOP.map { Part(it.urls, File(dir, it.file), it.sha256, false, it.size) } else emptyList()
val runtimePart = if (needRuntime) Part(listOf(runtime.url), File(dir, "steamrt4-${runtime.version}.tar.gz"), runtime.sha256, false) else null
val glesPart = if (needRuntime) Part(listOf(gles.url), File(dir, EpicClientSources.GLES_FILE), gles.sha256, false) else null
val parts = listOfNotNull(appPart) + desktopParts + listOfNotNull(runtimePart, glesPart)
val keep = parts.flatMap { listOf(it.file.name, it.file.name + PARTIAL, it.file.name + TAG) }.toSet()
dir.listFiles()?.forEach { if (it.name !in keep) it.deleteRecursively() }
if (parts.isNotEmpty()) {
parts.forEach { it.size = length(it.url) }
parts.forEach { if (it.size <= 0) it.size = length(it.url) }
val total = parts.sumOf { it.size.coerceAtLeast(0L) }
val have = parts.sumOf { p -> if (p.file.isFile) p.file.length() else File(p.file.path + PARTIAL).length() }
val needed = (total - have).coerceAtLeast(0L) + (if (needApp) APP_ROOM else 0L) + (if (needRuntime) RUNTIME_ROOM else 0L)
@@ -202,8 +244,9 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
handle.stage(DownloadStage.INSTALL, app.getString(R.string.epic_client_unpacking))
val argv = mutableListOf(EpicClient.PROGRAM, "install", "--app-version", launcher.version, "--runtime-version", runtime.version)
fun guest(file: File) = EpicClient.guestPath(app, file) ?: throw IllegalStateException(app.getString(R.string.epic_client_unpack_failed, file.name))
if (needApp) argv += listOf("--app", guest(parts[0].file))
if (needRuntime) argv += listOf("--runtime", guest(parts[parts.size - 2].file), "--gles", guest(parts[parts.size - 1].file))
appPart?.let { argv += listOf("--app", guest(it.file)) }
desktopParts.forEach { argv += listOf("--desktop", guest(it.file)) }
if (runtimePart != null && glesPart != null) argv += listOf("--runtime", guest(runtimePart.file), "--gles", guest(glesPart.file))
var answer: JSONObject? = null
val code = GuestCommand.run(app, argv, fakeRoot = true, logName = "epic-client") { line ->
if (line.startsWith("{")) runCatching { JSONObject(line) }.getOrNull()?.let { answer = it }
@@ -298,6 +341,10 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
}
200 -> false
416 -> { partial.delete(); tag.delete(); throw IOException("HTTP 416") }
404, 410 -> {
if (part.mirror + 1 < part.urls.size) { part.mirror++; tag.delete() }
throw IOException("HTTP $code")
}
else -> throw IOException("HTTP $code")
}
val served = conn.getHeaderField("ETag")?.takeIf { it.isNotBlank() }
@@ -334,8 +381,8 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
part.sha256?.let { want ->
if (EpicClientSources.sha256(file) != want) { file.delete(); throw IOException("checksum mismatch") }
}
if (part.appImage) {
if (!EpicClientSources.isAppImage(file)) { file.delete(); throw IOException("not an AppImage") }
if (part.launcher) {
if (!EpicClientSources.isDeb(file)) { file.delete(); throw IOException("not a Debian package") }
if (EpicClientSources.etagMatches(file, etag) == false) {
val seen = EpicClientSources.sha256(file)
if (part.mismatch != seen) {
@@ -351,7 +398,7 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
const val PARTIAL = ".part"
const val TAG = ".etag"
const val ATTEMPTS = 6
const val APP_ROOM = 600L shl 20
const val APP_ROOM = 700L shl 20
const val RUNTIME_ROOM = 560L shl 20
}
}
@@ -26,6 +26,7 @@ data class EpicGame(
val publisher: String = "",
val isDlc: Boolean = false,
val artLogo: String = "",
val thirdPartyManagedApp: String = "",
)
object EpicLibrary {
@@ -52,7 +53,10 @@ object EpicLibrary {
.put("developer", g.developer).put("description", g.description).put("version", g.version)
.put("installSize", g.installSize).put("canRunOffline", g.canRunOffline)
.put("releaseDate", g.releaseDate).put("publisher", g.publisher)
.apply { if (g.artLogo.isNotEmpty()) put("artLogo", g.artLogo) },
.apply {
if (g.artLogo.isNotEmpty()) put("artLogo", g.artLogo)
if (g.thirdPartyManagedApp.isNotEmpty()) put("thirdPartyManagedApp", g.thirdPartyManagedApp)
},
)
}.toString()
@@ -76,6 +80,7 @@ object EpicLibrary {
releaseDate = o.optString("releaseDate", ""),
publisher = o.optString("publisher", ""),
artLogo = o.optString("artLogo", ""),
thirdPartyManagedApp = o.optString("thirdPartyManagedApp", ""),
)
}
return tidy(games)
@@ -108,7 +113,12 @@ object EpicLibrary {
owned = true,
sizeBytes = prefs.getLong("size_${game.appName}", 0L).takeIf { it > 0 } ?: game.installSize,
storeUrl = "https://store.epicgames.com/en-US/browse?q=" + URLEncoder.encode(title, "UTF-8"),
extra = mapOf("namespace" to game.namespace, "catalogItemId" to game.catalogItemId, "version" to game.version),
extra = mapOf(
"namespace" to game.namespace,
"catalogItemId" to game.catalogItemId,
"version" to game.version,
"thirdPartyManagedApp" to game.thirdPartyManagedApp,
),
logoUrl = game.artLogo.ifEmpty { null },
)
}
@@ -133,6 +143,7 @@ object EpicLibrary {
publisher = pick("publisher", before?.publisher.orEmpty()),
isDlc = d.optBoolean("dlc", false),
artLogo = pick("logo", before?.artLogo.orEmpty()),
thirdPartyManagedApp = details?.optString("thirdPartyManagedApp", "") ?: before?.thirdPartyManagedApp.orEmpty(),
)
}
@@ -141,6 +141,7 @@ object RockstarAuth {
StoreAccounts.clear(context.applicationContext, Store.ROCKSTAR)
return "ticket"
}
com.droiddeck.launcher.session.SessionFiles.ensureRockstarService(context)
return null
}
@@ -61,7 +61,7 @@ internal object XboxRuntime {
val view = result.get(90, java.util.concurrent.TimeUnit.SECONDS)
check(renew(app, id, token) && synchronized(state) { generation == current }) { "Xbox launch was cancelled" }
return JSONObject().put("ok", true).put("socket", socket.path).put("lease", token)
.put("exe", view.getString("exe")).put("playfab", view.opt("playfab"))
.put("exe", view.getString("exe")).put("playfab", view.opt("playfab")).put("mountRoot", view.opt("mountRoot"))
} catch (e: Exception) { released(token); throw e }
}
@@ -301,6 +301,9 @@ internal fun rememberShown(onDismiss: () -> Unit): MutableTransitionState<Boolea
return shown
}
private val DIALOG_MARGIN = 12.dp
private val SIDE_GAP = 24.dp
@Composable
internal fun AppDialog(
shown: MutableTransitionState<Boolean>, close: () -> Unit, label: String, wide: Boolean,
@@ -309,17 +312,23 @@ internal fun AppDialog(
back: (() -> Unit)? = null,
scrollable: Boolean = true,
scrollState: androidx.compose.foundation.ScrollState = rememberScrollState(),
side: (@Composable () -> Unit)? = null,
sideRoom: Dp = 0.dp,
content: @Composable ColumnScope.() -> Unit,
) {
val pal = LocalPalette.current
val panelCap = maxWidth ?: if (wide) 860.dp else 560.dp
VeilRing()
Dialog(onDismissRequest = back ?: close, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) {
CompositionLocalProvider(LocalFrontFocus provides null) {
Box(
BoxWithConstraints(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize().imePadding()
.tapOutside(close),
) {
val panel = (this.maxWidth - DIALOG_MARGIN * 2).coerceAtMost(panelCap)
val free = (this.maxWidth - panel) / 2 - SIDE_GAP
val beside = side != null && free >= sideRoom
AnimatedVisibility(
visibleState = shown,
enter = fadeIn(Motion.tw(180)) + scaleIn(Motion.sp(0.7f), initialScale = 0.94f),
@@ -329,8 +338,8 @@ internal fun AppDialog(
Column(
verticalArrangement = Arrangement.spacedBy(14.dp),
modifier = Modifier
.padding(12.dp)
.widthIn(max = maxWidth ?: if (wide) 860.dp else 560.dp)
.padding(DIALOG_MARGIN)
.widthIn(max = panelCap)
.then(
when {
width != null -> Modifier.width(width)
@@ -348,8 +357,21 @@ internal fun AppDialog(
.then(modifier)
.then(if (scrollable) Modifier.verticalScroll(scrollState) else Modifier)
.padding(horizontal = 18.dp, vertical = 16.dp),
content = content,
)
) {
content()
if (side != null && !beside) side()
}
}
if (side != null && beside) {
AnimatedVisibility(
visibleState = shown,
enter = fadeIn(Motion.tw(180)),
exit = fadeOut(Motion.tw(140)),
modifier = Modifier.align(Alignment.CenterEnd).padding(end = SIDE_GAP),
label = "$label-side",
) {
Box(Modifier.widthIn(max = free).blockTouches()) { side() }
}
}
}
}
@@ -33,6 +33,7 @@ import androidx.compose.runtime.key
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.produceState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
@@ -73,8 +74,10 @@ import com.droiddeck.launcher.frontend.LogoPosition
import com.droiddeck.launcher.frontend.SoundtrackCollectionArt
import com.droiddeck.launcher.frontend.SteamGameArt
import com.droiddeck.launcher.frontend.SteamGridDb
import com.droiddeck.launcher.frontend.SteamInputOverride
import com.droiddeck.launcher.frontend.SteamLaunchOptions
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -336,6 +339,107 @@ internal fun SteamLaunchOptionsPanel(appId: Int) {
}
}
@Composable
internal fun SteamInputOverridePanel(appId: Int) {
val app = LocalContext.current.applicationContext
val colors = MaterialTheme.colorScheme
val scope = rememberCoroutineScope()
var selected by remember(appId) { mutableStateOf<SteamInputOverride.Mode?>(null) }
var version by remember(appId) { mutableIntStateOf(0) }
var saving by remember(appId) { mutableStateOf(false) }
var loading by remember(appId) { mutableStateOf(true) }
var error by remember(appId) { mutableStateOf<Int?>(null) }
var saves by remember(appId) { mutableIntStateOf(0) }
// SessionState.running is not snapshot state, so the panel polls it while shown.
val sessionRunning by produceState(SessionState.running) {
while (true) {
value = SessionState.running
kotlinx.coroutines.delay(1000)
}
}
LaunchedEffect(appId, version) {
val savesAtStart = saves
val read = withContext(Dispatchers.IO) { SteamInputOverride.current(app, appId) }
// A save that finished while this read ran already set the selection; the read may predate it.
if (!saving && saves == savesAtStart) selected = read
loading = false
}
var wasRunning by remember(appId) { mutableStateOf(SessionState.running) }
LaunchedEffect(sessionRunning) {
// Steam may have changed the override while it ran, so every stop reloads it.
if (wasRunning && !sessionRunning) {
if (error == R.string.edit_steam_input_running) error = null
loading = true
version++
}
wasRunning = sessionRunning
}
val lifecycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle, appId) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME && !saving) {
loading = true
version++
}
}
lifecycle.addObserver(observer)
onDispose { lifecycle.removeObserver(observer) }
}
val choices = listOf(
SteamInputOverride.Mode.DEFAULT to R.string.edit_steam_input_default,
SteamInputOverride.Mode.ENABLED to R.string.edit_steam_input_enable,
SteamInputOverride.Mode.DISABLED to R.string.edit_steam_input_disable,
)
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
stringResource(R.string.edit_steam_input_override),
fontSize = 13.sp,
fontWeight = FontWeight.SemiBold,
color = colors.onSurfaceVariant,
modifier = Modifier.padding(start = 4.dp, bottom = 2.dp),
)
choices.forEach { (mode, label) ->
MenuItem(
stringResource(label),
checked = selected == mode,
enabled = selected != null && !saving && !loading && !sessionRunning && selected != mode,
) {
val before = selected ?: return@MenuItem
saving = true
scope.launch {
try {
val saved = withContext(Dispatchers.IO) { SteamInputOverride.set(app, appId, mode, before) }
error = when (saved) {
SteamInputOverride.Saved.YES -> null
SteamInputOverride.Saved.NO -> R.string.edit_steam_input_not_saved
SteamInputOverride.Saved.RUNNING -> R.string.edit_steam_input_running
}
if (saved == SteamInputOverride.Saved.YES) {
saves++
selected = mode
} else version++
} finally {
saving = false
}
}
}
}
val message = error ?: when {
sessionRunning -> R.string.edit_steam_input_running
selected == null && !loading -> R.string.edit_steam_input_unavailable
else -> R.string.edit_steam_input_hint
}
Text(
stringResource(message),
fontSize = 12.sp,
color = if (error == null) colors.onSurfaceVariant else colors.error,
modifier = Modifier.padding(start = 4.dp),
)
}
}
private class LoadedPosition(val value: LogoPosition.Value?)
@Composable
@@ -6,6 +6,8 @@ import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
@@ -19,6 +21,7 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.CheckCircle
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Description
import androidx.compose.material.icons.outlined.ContentCopy
import androidx.compose.material.icons.outlined.ErrorOutline
import androidx.compose.material.icons.outlined.ExpandLess
import androidx.compose.material.icons.outlined.ExpandMore
@@ -39,6 +42,8 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
@@ -53,9 +58,13 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentAttachments
import com.droiddeck.launcher.agent.AgentHost
import com.droiddeck.launcher.agent.AgentHost.Entry
import com.droiddeck.launcher.agent.choices
@Composable
internal fun AgentEntry(entry: Entry, running: Boolean, last: Boolean = false, changes: Changes? = null, onRevise: () -> Unit = {}) {
internal fun AgentEntry(
entry: Entry, running: Boolean, last: Boolean = false, changes: Changes? = null, answerable: Boolean = false,
children: List<Entry.Used> = emptyList(), turn: List<Entry> = emptyList(), onRevise: () -> Unit = {}, onSent: () -> Unit = {},
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
when (entry) {
@@ -66,24 +75,44 @@ internal fun AgentEntry(entry: Entry, running: Boolean, last: Boolean = false, c
modifier = Modifier.widthIn(max = 560.dp).clip(Shape16).background(pal.primary).padding(horizontal = 14.dp, vertical = 10.dp))
}
}
is Entry.Said -> SelectionContainer { AgentMarkdown(entry.text, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) }
is Entry.Said -> {
val reply = remember(entry.text) { choices(entry.text) }
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (reply.text.isNotBlank()) SelectionContainer { AgentMarkdown(reply.text, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) }
if (reply.options.isNotEmpty()) AgentChoices(reply.options, answerable, onSent)
}
}
is Entry.Notice -> Text(entry.text, color = colors.error, modifier = Modifier.padding(horizontal = 4.dp))
is Entry.Thought -> AgentThought(entry.text, live = false)
is Entry.Used -> if (entry.tool == "TodoWrite") AgentTodos(entry.input) else AgentToolCall(entry, running)
is Entry.Used -> if (entry.tool == "TodoWrite") AgentTodos(entry.input) else AgentToolCall(entry, running, children)
is Entry.Result -> Unit
is Entry.Finished -> when {
last && AgentHost.answerless(AgentHost.entries) -> AgentNoReply()
last && entry.planned -> Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
AgentTurnEnd(entry, changes)
AgentPlanActions(onRevise)
AgentTurnEnd(entry, changes, turn)
AgentPlanActions(onRevise, onSent)
}
else -> AgentTurnEnd(entry, changes)
else -> AgentTurnEnd(entry, changes, turn)
}
}
}
/** The options a reply ends with; picking one sends it, while the reply is still the latest. */
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun AgentChoices(options: List<String>, answerable: Boolean, onSent: () -> Unit) {
val context = LocalContext.current
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(horizontal = 4.dp)) {
for (option in options) SecondaryButton(option, enabled = answerable, compact = true, modifier = Modifier.testTag("agent-choice")) {
AgentHost.send(context, option)
onSent()
}
}
}
/** A plan turn changed nothing; Go carries the plan out with plan mode off, Revise asks for another. */
@Composable
private fun AgentPlanActions(onRevise: () -> Unit) {
private fun AgentPlanActions(onRevise: () -> Unit, onSent: () -> Unit) {
val context = LocalContext.current
val pal = LocalPalette.current
val go = stringResource(R.string.agent_plan_go_message)
@@ -91,6 +120,7 @@ private fun AgentPlanActions(onRevise: () -> Unit) {
PrimaryButton(stringResource(R.string.agent_plan_go), compact = true, modifier = Modifier.testTag("agent-plan-go")) {
AgentHost.choosePlan(context, false)
AgentHost.send(context, go)
onSent()
}
SecondaryButton(stringResource(R.string.agent_plan_revise), compact = true, modifier = Modifier.testTag("agent-plan-revise")) {
AgentHost.choosePlan(context, true)
@@ -106,13 +136,18 @@ internal data class Changes(val files: Int, val added: Int, val removed: Int)
/** The edits of the turn that ends at [end], or null when it changed no file. */
internal fun turnChanges(entries: List<Entry>, end: Int): Changes? {
val start = entries.subList(0, end).indexOfLast { it is Entry.Asked }
// Plan mode saves its plan as a file of its own, which is not a change to anything.
val edits = entries.subList(start + 1, end).filterIsInstance<Entry.Used>().filter { !it.failed }.mapNotNull { diffOf(it) }
.filter { !it.path.contains("/.claude/plans/") }
val edits = turnEdits(entries.subList(start + 1, end))
if (edits.isEmpty()) return null
return Changes(edits.map { it.path }.distinct().size, edits.sumOf { it.added }, edits.sumOf { it.removed })
}
/** The edits in [turn] that took, in order. Plan mode saves its plan as a file of its own, which is not a change to anything. */
internal fun turnEdits(turn: List<Entry>): List<Diff> =
turn.filterIsInstance<Entry.Used>().filter { !it.failed }.mapNotNull { diffOf(it) }.filter { !it.path.contains("/.claude/plans/") }
/** What the agent said in [turn], to copy as one text. */
internal fun turnReply(turn: List<Entry>): String = turn.filterIsInstance<Entry.Said>().joinToString("\n\n") { it.text }
internal class Diff(val path: String, val lines: List<String>) {
val added = lines.count { it.startsWith("+") }
val removed = lines.count { it.startsWith("-") }
@@ -129,9 +164,11 @@ internal fun diffOf(entry: Entry.Used): Diff? {
}
@Composable
private fun AgentTurnEnd(entry: Entry.Finished, changes: Changes?) {
private fun AgentTurnEnd(entry: Entry.Finished, changes: Changes?, turn: List<Entry>) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var open by rememberSaveable { mutableStateOf(false) }
val reply = turnReply(turn)
val text = when {
entry.stopped -> stringResource(R.string.agent_stopped)
entry.error != null -> stringResource(R.string.agent_failed, entry.error)
@@ -143,18 +180,38 @@ private fun AgentTurnEnd(entry: Entry.Finished, changes: Changes?) {
}.joinToString(" · ")
}
}
if (text.isNullOrEmpty() && changes == null) return
if (text.isNullOrEmpty() && changes == null && reply.isEmpty()) return
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(horizontal = 4.dp)) {
if (changes != null) Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 9.dp, vertical = 4.dp).testTag("agent-changes"),
modifier = Modifier.clip(Shape12).background(if (open) pal.primary.copy(alpha = 0.2f) else pal.surfaceVariant).clickable { open = !open }
.padding(horizontal = 9.dp, vertical = 4.dp).testTag("agent-changes"),
) {
Text(pluralStringResource(R.plurals.agent_files_changed, changes.files, changes.files), fontSize = 12.sp, color = pal.onSurfaceVariant)
Text("+${changes.added}", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.good)
Text("−${changes.removed}", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.error)
Icon(if (open) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
if (!text.isNullOrEmpty()) Text(text, fontSize = 12.sp, color = if (entry.error != null && !entry.stopped) colors.error else pal.onSurfaceVariant)
if (!text.isNullOrEmpty()) Text(text, fontSize = 12.sp, color = if (entry.error != null && !entry.stopped) colors.error else pal.onSurfaceVariant,
modifier = Modifier.weight(1f, fill = false))
if (reply.isNotEmpty()) CopyButton(reply, stringResource(R.string.agent_copy_reply))
}
if (open && changes != null) Column(Modifier.padding(start = 4.dp, end = 4.dp, top = 8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
for (diff in turnEdits(turn)) {
Text(diff.path, fontSize = 11.5.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
DiffBox(diff)
}
}
}
@Composable
private fun CopyButton(text: String, label: String) {
val clipboard = LocalClipboardManager.current
val pal = LocalPalette.current
Icon(
Icons.Outlined.ContentCopy, label, tint = pal.onSurfaceVariant,
modifier = Modifier.size(28.dp).clip(Shape12).clickable { clipboard.setText(AnnotatedString(text)) }.padding(6.dp).testTag("agent-copy"),
)
}
@Composable
@@ -216,7 +273,7 @@ private fun AgentTodos(list: String) {
/** A tool call: one line with its status, opening to the full input and output, or to the diff of an edit. */
@Composable
private fun AgentToolCall(entry: Entry.Used, running: Boolean) {
private fun AgentToolCall(entry: Entry.Used, running: Boolean, children: List<Entry.Used> = emptyList()) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var open by rememberSaveable(entry.id.ifEmpty { entry.detail }) { mutableStateOf(false) }
@@ -245,6 +302,17 @@ private fun AgentToolCall(entry: Entry.Used, running: Boolean) {
}
Icon(if (open) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(18.dp))
}
if (children.isNotEmpty()) {
val latest = children.last()
Text(
pluralStringResource(R.plurals.agent_subagent_steps, children.size, children.size) + " · " + latest.tool + " " + latest.detail,
fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(start = 34.dp, end = 10.dp, bottom = 8.dp),
)
}
if (open && children.isNotEmpty()) Column(Modifier.padding(start = 10.dp, end = 4.dp, bottom = 6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
for (child in children) AgentToolCall(child, running && child.output == null)
}
if (open && diff != null) Column(Modifier.padding(start = 10.dp, end = 10.dp, bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
if (diff.path.contains('/')) Text(diff.path, fontSize = 11.5.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
DiffBox(diff)
@@ -289,7 +357,11 @@ private fun DiffBox(diff: Diff) {
private fun CodeBox(label: String, text: String, color: Color) {
val pal = LocalPalette.current
Column {
Text(label, fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.sp, color = pal.onSurfaceVariant, modifier = Modifier.padding(bottom = 3.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
Text(label, fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.sp, color = pal.onSurfaceVariant,
modifier = Modifier.weight(1f).padding(bottom = 3.dp))
CopyButton(text, stringResource(R.string.agent_copy))
}
SelectionContainer {
Text(
text, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = color, lineHeight = 17.sp,
@@ -9,6 +9,8 @@ import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.shrinkHorizontally
import androidx.compose.animation.expandHorizontally
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.Canvas
@@ -41,6 +43,10 @@ import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Send
import androidx.compose.material.icons.outlined.Extension
import androidx.compose.material.icons.outlined.PhotoCamera
import androidx.compose.material.icons.outlined.MicOff
import androidx.compose.material.icons.outlined.Mic
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.ArrowDownward
import androidx.compose.material.icons.outlined.AttachFile
@@ -64,12 +70,12 @@ import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.Stable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
@@ -91,6 +97,7 @@ import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
@@ -114,33 +121,54 @@ import com.droiddeck.launcher.agent.AgentHost.Entry
import com.droiddeck.launcher.agent.AgentSetup
import kotlinx.coroutines.launch
internal enum class AgentPanel { NONE, MODEL, USAGE, HISTORY, PROCESSES }
internal enum class AgentPanel { NONE, MODEL, USAGE, HISTORY, PROCESSES, TOOLS }
/** Slash commands the app handles itself; others go to the CLI, which has its own. */
private val LOCAL_COMMANDS = listOf("/new", "/model", "/plan", "/history", "/processes", "/stop")
private val CLI_COMMANDS = listOf("/compact", "/cost", "/review", "/init")
private const val COMPOSER_SLIDE_MS = 350L
/**
* The chat with the composer at the bottom. The composer is the full editor only while it is
* being typed in; reading shrinks it to one line, and scrolling back through older messages
* hides it behind a small pill. [startTyping] opens an empty conversation ready to type.
* The chat with the model, usage and menu on top and the editor at the bottom. Scrolling back
* through older messages hides the editor behind a small pill and stops following new output.
* [inputModifier] goes on the first control, where a controller lands without raising the keyboard.
*/
@Suppress("UNUSED_PARAMETER")
@Composable
internal fun AgentPage(
modifier: Modifier, inputModifier: Modifier = Modifier, visible: Boolean = true, startTyping: Boolean = true, hidesPet: Boolean = true,
) = AgentPageContent(modifier, inputModifier, visible, startTyping, hidesPet, showControlsWithoutKeyboard = false)
menuSlot: AgentMenuSlot? = null,
) = AgentPageContent(modifier, inputModifier, visible, hidesPet, menuSlot)
// Lab overlays run against the installed APK, so these entry points keep their JVM signatures.
@Suppress("UNUSED_PARAMETER")
@Composable
internal fun AgentPageWithControls(
modifier: Modifier, inputModifier: Modifier = Modifier, visible: Boolean = true, startTyping: Boolean = true,
showControlsWithoutKeyboard: Boolean,
) = AgentPageContent(modifier, inputModifier, visible, startTyping, hidesPet = true, showControlsWithoutKeyboard = showControlsWithoutKeyboard)
) = AgentPageContent(modifier, inputModifier, visible, hidesPet = true, drawer = true)
/** Whether the session drawer's chat keeps the model, usage and menu in the editor's row, giving the conversation that row's height. */
internal object AgentDrawerLayout {
private const val KEY = "drawer_inline_controls"
var inline by mutableStateOf(true)
private set
private var loaded = false
fun load(context: android.content.Context) {
if (loaded) return
loaded = true
inline = AgentHost.prefs(context).getBoolean(KEY, true)
}
fun set(context: android.content.Context, on: Boolean) {
inline = on
AgentHost.prefs(context).edit().putBoolean(KEY, on).apply()
}
}
@Composable
private fun AgentPageContent(
modifier: Modifier, inputModifier: Modifier, visible: Boolean, startTyping: Boolean, hidesPet: Boolean,
showControlsWithoutKeyboard: Boolean,
modifier: Modifier, inputModifier: Modifier, visible: Boolean, hidesPet: Boolean, menuSlot: AgentMenuSlot? = null, drawer: Boolean = false,
) {
val context = LocalContext.current
val view = LocalView.current
@@ -155,9 +183,19 @@ private fun AgentPageContent(
}
}
remember { AgentHost.refresh(context) }
remember { AgentDrawerLayout.load(context) }
val inline = drawer && AgentDrawerLayout.inline
LaunchedEffect(AgentHost.unseen, visible) { if (visible) AgentHost.seen() }
DisposableEffect(visible, hidesPet) {
val counts = visible && hidesPet
// A stopped activity keeps its composition; the page is only on screen while its host is started.
val lifecycle = androidx.compose.ui.platform.LocalLifecycleOwner.current.lifecycle
var started by remember(lifecycle) { mutableStateOf(lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.STARTED)) }
DisposableEffect(lifecycle) {
val observer = androidx.lifecycle.LifecycleEventObserver { _, _ -> started = lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.STARTED) }
lifecycle.addObserver(observer)
onDispose { lifecycle.removeObserver(observer) }
}
DisposableEffect(visible, hidesPet, started) {
val counts = visible && hidesPet && started
if (counts) AgentPet.agentOnScreen++
onDispose { if (counts) AgentPet.agentOnScreen-- }
}
@@ -169,16 +207,32 @@ private fun AgentPageContent(
return
}
var panel by rememberSaveable { mutableStateOf(AgentPanel.NONE) }
val composer = remember { ComposerState(startTyping && AgentHost.entries.isEmpty()) }
val composer = remember { ComposerState() }
val focusManager = LocalFocusManager.current
val togglePanel: (AgentPanel) -> Unit = { panel = if (panel == it) AgentPanel.NONE else it }
var menuOpen by rememberSaveable { mutableStateOf(false) }
val menu: @Composable () -> Unit = {
AgentMenu(menuOpen, { menuOpen = it }, onPanel = { panel = it }, onSetup = { setup = true })
}
val topBar: @Composable () -> Unit = { AgentTopBar(panel, togglePanel, inputModifier, menu) }
val inlineControls: (@Composable () -> Unit)? = if (inline) ({
ModelChip(panel, togglePanel, inputModifier, compact = true)
ContextRing("agent-usage", onClick = { togglePanel(AgentPanel.USAGE) })
menu()
}) else null
// A host with a title bar shows the top bar there.
val inSlot = menuSlot != null && panel != AgentPanel.HISTORY && panel != AgentPanel.PROCESSES && panel != AgentPanel.TOOLS
if (menuSlot != null) DisposableEffect(menuSlot, inSlot) {
menuSlot.content = if (inSlot) topBar else null
onDispose { menuSlot.content = null }
}
// The keyboard leaves too little height for a panel and the editor together, so typing closes the panel.
val keyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0
LaunchedEffect(keyboardOpen) { if (keyboardOpen && (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE)) panel = AgentPanel.NONE }
Column(
modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e ->
val k = e.nativeKeyEvent
if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y || composer.typing) return@onPreviewKeyEvent false
if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y || composer.focused) return@onPreviewKeyEvent false
if (k.action == KeyEvent.ACTION_UP) composer.open()
true
},
@@ -192,11 +246,22 @@ private fun AgentPageContent(
AgentPanelBar(stringResource(R.string.agent_processes)) { panel = AgentPanel.NONE }
AgentProcessList(Modifier.weight(1f))
}
AgentPanel.TOOLS -> {
AgentPanelBar(stringResource(R.string.agent_tools)) { panel = AgentPanel.NONE }
AgentToolsPanel(Modifier.weight(1f))
}
else -> {
if (menuSlot == null && !inline) Box(Modifier.padding(bottom = 6.dp)) { topBar() }
when (panel) {
AgentPanel.MODEL -> Box(Modifier.padding(bottom = 8.dp)) { AgentModelPicker() }
AgentPanel.USAGE -> Box(Modifier.padding(bottom = 8.dp)) { AgentUsage() }
else -> Unit
}
val list = rememberLazyListState()
val scope = rememberCoroutineScope()
// Only dragging back through older messages hides the composer; showing it again shrinks the list, which must not hide it once more.
// Only dragging back through older messages stops following the latest; reaching the bottom again resumes it.
var readingBack by remember { mutableStateOf(false) }
LaunchedEffect(AgentHost.chat) { readingBack = false }
LaunchedEffect(list) { snapshotFlow { list.canScrollForward }.collect { if (!it) readingBack = false } }
val dragBack = remember {
object : NestedScrollConnection {
@@ -210,27 +275,27 @@ private fun AgentPageContent(
readingBack = false
scope.launch { list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2) }
}
val hidden = !composer.typing && readingBack && AgentHost.entries.isNotEmpty()
var wasHidden by remember { mutableStateOf(false) }
LaunchedEffect(hidden) {
if (hidden) wasHidden = true
else if (wasHidden) {
wasHidden = false
// The composer takes its height back as it slides in; the latest message stays above it.
kotlinx.coroutines.delay(COMPOSER_SLIDE_MS)
list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2)
}
}
Box(Modifier.weight(1f).fillMaxWidth().clipToBounds().nestedScroll(dragBack)) {
val hidden = !composer.focused && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty()
var listHeight by remember { mutableIntStateOf(0) }
Box(
Modifier.weight(1f).fillMaxWidth().clipToBounds().nestedScroll(dragBack).onGloballyPositioned {
// The editor sliding in or the keyboard rising shrinks the list from below; a list following the latest keeps it in view, even mid-drag.
// Scrolling remeasures the list, which Compose refuses during a measure pass, so this runs once positioning is done.
val height = it.size.height
val shrunk = listHeight - height
listHeight = height
if (shrunk > 0 && !readingBack) list.dispatchRawDelta(shrunk.toFloat())
},
) {
AgentConversation(
Modifier.fillMaxSize().pointerInput(Unit) {
awaitEachGesture {
awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
if (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE) panel = AgentPanel.NONE
if (composer.typing) focusManager.clearFocus()
if (composer.focused) focusManager.clearFocus()
}
},
list, onRevise = { composer.open() },
list, following = !readingBack, onRevise = { composer.open() }, onSent = toLatest,
)
androidx.compose.animation.AnimatedVisibility(
hidden, enter = fadeIn(), exit = fadeOut(), modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 8.dp),
@@ -239,27 +304,24 @@ private fun AgentPageContent(
}
}
androidx.compose.animation.AnimatedVisibility(!hidden, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
AgentComposer(composer, draft, inputModifier, panel, togglePanel, showControlsWithoutKeyboard) { setup = true }
AgentComposer(composer, draft, visible, inlineControls, onPanel = { panel = it }, onSent = toLatest)
}
}
}
}
}
/** Whether the composer is the full editor; [open] also puts the cursor in it. */
/** Whether the editor has the cursor; [open] puts it there. */
@Stable
private class ComposerState(typing: Boolean) {
var typing by mutableStateOf(typing)
private class ComposerState {
var focused by mutableStateOf(false)
var focusRequests by mutableIntStateOf(0)
private set
private var consumedFocusRequests by mutableIntStateOf(0)
/** Opened and waiting for the text field to take focus; focus passes through nothing on the way. */
var opening = false
fun open() {
typing = true
opening = true
focusRequests++
if (focused) consumeFocusRequest()
}
fun hasUnconsumedFocusRequest() = focusRequests > consumedFocusRequests
@@ -269,6 +331,80 @@ private class ComposerState(typing: Boolean) {
}
}
/** Where a host with its own title bar shows the conversation's menu. */
@Stable
internal class AgentMenuSlot {
var content by mutableStateOf<(@Composable () -> Unit)?>(null)
}
/** The model and how full the context is, then the [menu]. */
@Composable
private fun AgentTopBar(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstControl: Modifier, menu: @Composable () -> Unit) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
ModelChip(panel, onPanel, firstControl, Modifier.weight(1f, fill = false))
ContextRing("agent-usage", onClick = { onPanel(AgentPanel.USAGE) })
}
menu()
}
}
/** The harness, model, effort and plan mode, opening the model picker; [compact] names only the model. */
@Composable
private fun ModelChip(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstControl: Modifier, modifier: Modifier = Modifier, compact: Boolean = false) {
val context = LocalContext.current
val pal = LocalPalette.current
val model = AgentHost.models(context).firstOrNull { it.id == AgentHost.model }?.label ?: AgentHost.model ?: stringResource(R.string.agent_model_default)
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier.then(if (compact) Modifier.widthIn(max = 120.dp) else Modifier).height(36.dp).clip(Shape12).then(firstControl)
.clickable { onPanel(AgentPanel.MODEL) }.padding(horizontal = 8.dp).testTag("agent-model"),
) {
val parts = if (compact) listOf(model)
else listOfNotNull(AgentHost.harness.name, model, AgentHost.effort, stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans })
Text(parts.joinToString(" · "), fontSize = 13.sp, color = if (panel == AgentPanel.MODEL) pal.primary else pal.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
Icon(Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
}
/** History, processes, a new conversation, the pet and setup, folded behind one button. */
@Composable
private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentPanel) -> Unit, onSetup: () -> Unit) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val working = AgentHost.state == AgentHost.State.WORKING
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.clip(Shape16).background(colors.surface.copy(alpha = if (open) 0.97f else 0.88f))
.border(1.dp, pal.line, Shape16).padding(end = 2.dp),
) {
androidx.compose.animation.AnimatedVisibility(open, enter = expandHorizontally(expandFrom = Alignment.End) + fadeIn(),
exit = shrinkHorizontally(shrinkTowards = Alignment.End) + fadeOut()) {
Row(verticalAlignment = Alignment.CenterVertically) {
HeaderAction(Icons.Outlined.History, stringResource(R.string.agent_history), size = 36.dp, tag = "agent-history") { onOpen(false); onPanel(AgentPanel.HISTORY) }
HeaderAction(Icons.Outlined.Memory, stringResource(R.string.agent_processes), size = 36.dp, tag = "agent-processes") { onOpen(false); onPanel(AgentPanel.PROCESSES) }
if (AgentHost.harness == com.droiddeck.launcher.agent.ClaudeCode) HeaderAction(
Icons.Outlined.Extension, stringResource(R.string.agent_tools), size = 36.dp, tag = "agent-tools",
) { onOpen(false); onPanel(AgentPanel.TOOLS) }
HeaderAction(Icons.Outlined.Add, stringResource(R.string.agent_new), enabled = !working && AgentHost.entries.isNotEmpty(), size = 36.dp, tag = "agent-new") {
onOpen(false)
AgentHost.forget(context)
}
HeaderAction(Icons.Outlined.Pets, stringResource(R.string.setup_agent_pet), selected = AgentPet.enabled, size = 36.dp, tag = "agent-pet-toggle") {
AgentPet.set(context, !AgentPet.enabled)
}
HeaderAction(Icons.Outlined.Settings, stringResource(R.string.agent_setup_title), enabled = !working, size = 36.dp, tag = "agent-settings") {
onOpen(false)
onSetup()
}
}
}
HeaderAction(Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), selected = open, size = 36.dp, tag = "agent-menu") { onOpen(!open) }
}
}
@Composable
private fun AgentPanelBar(title: String, onClose: () -> Unit) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp)) {
@@ -298,18 +434,20 @@ internal fun HeaderAction(
}
@Composable
private fun AgentConversation(modifier: Modifier, list: LazyListState, onRevise: () -> Unit) {
private fun AgentConversation(modifier: Modifier, list: LazyListState, following: Boolean, onRevise: () -> Unit, onSent: () -> Unit) {
val pal = LocalPalette.current
val working = AgentHost.state == AgentHost.State.WORKING
val atBottom by remember { derivedStateOf { !list.canScrollForward } }
val items = AgentHost.entries.size + (if (working) 1 else 0)
// A subagent's calls are shown inside the call that started it.
val shown = AgentHost.entries.indices.filter { (AgentHost.entries[it] as? Entry.Used)?.parent.isNullOrEmpty() }
val items = shown.size + (if (working) 1 else 0)
val follow by rememberUpdatedState(following)
LaunchedEffect(items) {
if (items == 0) return@LaunchedEffect
if (items == 0 || !follow) return@LaunchedEffect
list.animateScrollToItem(items - 1)
list.scrollToItem(items - 1, Int.MAX_VALUE / 2)
}
LaunchedEffect(AgentHost.live.length / 80, AgentHost.liveThinking.length / 80) {
if (atBottom && items > 0) list.scrollToItem(items - 1, Int.MAX_VALUE / 2)
if (follow && items > 0) list.scrollToItem(items - 1, Int.MAX_VALUE / 2)
}
if (AgentHost.entries.isEmpty() && !working) {
Column(modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
@@ -321,11 +459,15 @@ private fun AgentConversation(modifier: Modifier, list: LazyListState, onRevise:
}
val start = AgentHost.entries.indexOfLast { it is Entry.Asked }
LazyColumn(modifier.fillMaxWidth(), state = list, verticalArrangement = Arrangement.spacedBy(10.dp)) {
items(AgentHost.entries.size) { i ->
items(shown.size) { n ->
val i = shown[n]
val entry = AgentHost.entries[i]
AgentEntry(
entry, running = working && i > start && entry is Entry.Used && entry.output == null, last = !working && i == AgentHost.entries.lastIndex,
changes = if (entry is Entry.Finished) turnChanges(AgentHost.entries, i) else null, onRevise = onRevise,
children = if (entry is Entry.Used) AgentHost.entries.filter { it is Entry.Used && it.parent == entry.id && entry.id.isNotEmpty() }.map { it as Entry.Used } else emptyList(),
changes = if (entry is Entry.Finished) turnChanges(AgentHost.entries, i) else null,
turn = if (entry is Entry.Finished) AgentHost.entries.subList(AgentHost.entries.subList(0, i).indexOfLast { it is Entry.Asked } + 1, i) else emptyList(),
answerable = !working && i > start && AgentHost.queue.isEmpty(), onRevise = onRevise, onSent = onSent,
)
}
if (working) item { AgentLive() }
@@ -425,7 +567,8 @@ private fun labStage(lab: com.droiddeck.launcher.agent.LabProgress) = when (lab.
else -> stringResource(R.string.agent_lab_stage_starting)
}
private fun hasActivity() = AgentHost.lab != null || AgentHost.queue.isNotEmpty() || currentTodo() != null
private fun hasActivity() = AgentHost.lab != null || AgentHost.queue.isNotEmpty() || currentTodo() != null ||
com.droiddeck.launcher.agent.AgentSetup.problems.isNotEmpty()
/** The todo item in progress and how many are done, while the agent works through a list. */
private fun currentTodo(): String? {
@@ -452,6 +595,11 @@ private fun AgentActivity(labOpen: Boolean, onLab: () -> Unit) {
Text(todo, fontSize = 12.5.sp, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 220.dp))
}
}
val problems = com.droiddeck.launcher.agent.AgentSetup.problems
if (problems.isNotEmpty()) AgentChip(warn = true, tag = "agent-tools-missing") {
Text(stringResource(R.string.agent_tools_missing, problems.joinToString(", ")), fontSize = 12.5.sp, color = AttentionAmber,
maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 260.dp))
}
for (queued in AgentHost.queue) AgentChip(warn = true) {
Text(stringResource(R.string.agent_queued, queued.text), fontSize = 12.5.sp, color = AttentionAmber, maxLines = 1,
overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 180.dp))
@@ -511,15 +659,13 @@ internal fun liveUsed(limit: AgentHost.Limit) = if (limit.resetsAt > 0 && limit.
@Composable
private fun AgentComposer(
composer: ComposerState, draftState: MutableState<String>, inputModifier: Modifier, panel: AgentPanel, onPanel: (AgentPanel) -> Unit,
showControlsWithoutKeyboard: Boolean, onSetup: () -> Unit,
composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?,
onPanel: (AgentPanel) -> Unit, onSent: () -> Unit,
) {
val context = LocalContext.current
var draft by draftState
var labOpen by rememberSaveable { mutableStateOf(false) }
if (AgentHost.lab == null) labOpen = false
var controlsOpen by rememberSaveable { mutableStateOf(false) }
var hadFocus by remember { mutableStateOf(false) }
val send = send@{
val text = draft.trim()
when (text.substringBefore(' ')) {
@@ -533,92 +679,33 @@ private fun AgentComposer(
if (text.isEmpty() && AgentAttachments.pending.isEmpty()) return@send
AgentHost.send(context, text, AgentAttachments.pending.toList())
AgentAttachments.pending.clear()
onSent()
}
}
draft = ""
}
val keyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0
// Leaving the composer for the conversation, by touch or D-pad, is reading.
Column(
Modifier.fillMaxWidth().padding(bottom = if (keyboardOpen) 4.dp else 8.dp).onFocusChanged {
if (it.hasFocus) hadFocus = true
else if (hadFocus) {
hadFocus = false
if (composer.typing && !composer.opening) composer.typing = false
}
},
) {
Column(Modifier.fillMaxWidth().padding(bottom = if (keyboardOpen) 4.dp else 8.dp)) {
if (labOpen) AgentLabCard()
when (panel) {
AgentPanel.MODEL -> Box(Modifier.padding(top = 8.dp)) { AgentModelPicker() }
AgentPanel.USAGE -> Box(Modifier.padding(top = 8.dp)) { AgentUsage() }
else -> Unit
}
if (composer.typing) {
if (hasActivity()) Row(
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
) { AgentActivity(labOpen) { labOpen = !labOpen } }
AgentEditor(composer, draftState, inputModifier, panel, onPanel, onSetup, controlsOpen, { controlsOpen = it },
highlightControls = showControlsWithoutKeyboard, send = send)
} else AgentReadingBar(composer, draft, inputModifier, labOpen, onLab = { labOpen = !labOpen }) {
if (showControlsWithoutKeyboard) {
controlsOpen = false
composer.typing = true
composer.opening = true
} else {
controlsOpen = true
composer.open()
}
}
}
}
/** The composer while reading: one line holding what is going on, opened by a press or by Y. */
@Composable
private fun AgentReadingBar(
composer: ComposerState, draft: String, inputModifier: Modifier, labOpen: Boolean, onLab: () -> Unit, onControls: () -> Unit,
) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val working = AgentHost.state == AgentHost.State.WORKING
var focused by remember { mutableStateOf(false) }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(44.dp).clip(Shape16).background(colors.surface)
.border(if (focused) 2.dp else 1.dp, if (focused) pal.primary else pal.line, Shape16)
.then(inputModifier).onFocusChanged { focused = it.isFocused }.clickable { composer.open() }.testTag("agent-composer-bar")
.padding(start = 14.dp, end = 4.dp),
) {
Text(
draft.ifBlank { stringResource(if (working) R.string.agent_hint_working else R.string.agent_message) }, fontSize = 15.sp,
color = if (draft.isBlank()) pal.onSurfaceVariant else colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = !hasActivity()).widthIn(min = 72.dp),
)
if (hasActivity()) Row(
horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f).padding(start = 8.dp).horizontalScroll(rememberScrollState()),
) { AgentActivity(labOpen, onLab) }
HeaderAction(Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), size = 36.dp, tag = "agent-controls", onClick = onControls)
if (working) Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(start = 4.dp).size(36.dp).clip(CircleShape).background(pal.error.copy(alpha = 0.22f))
.clickable { AgentHost.stop(context) }.testTag("agent-stop"),
) { Icon(Icons.Outlined.Stop, stringResource(R.string.agent_stop), tint = colors.error, modifier = Modifier.size(20.dp)) }
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
) { AgentActivity(labOpen) { labOpen = !labOpen } }
AgentEditor(composer, draftState, visible, controls, send)
}
}
/** The full editor: model and usage on top, the text with attach, stop and send under them. */
/** The text with attach, stop and send beside it, and [controls] while the text is not being typed in. */
@Composable
private fun AgentEditor(
composer: ComposerState, draftState: MutableState<String>, inputModifier: Modifier, panel: AgentPanel, onPanel: (AgentPanel) -> Unit,
onSetup: () -> Unit, menu: Boolean, onMenu: (Boolean) -> Unit, highlightControls: Boolean = false, send: () -> Unit,
) {
private fun AgentEditor(composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, send: () -> Unit) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var draft by draftState
val voice = remember { AgentVoice(context.applicationContext, { draftState.value }) { draftState.value = it } }
val voiceAvailable = remember { AgentVoice.available(context) }
DisposableEffect(voice) { onDispose { voice.stop() } }
LaunchedEffect(visible) { if (!visible) voice.stop() }
val working = AgentHost.state == AgentHost.State.WORKING
if (draft.startsWith("/") && !draft.contains(' ')) {
val matches = (LOCAL_COMMANDS + CLI_COMMANDS).filter { it.startsWith(draft) && it != draft }
@@ -643,42 +730,11 @@ private fun AgentEditor(
LaunchedEffect(composer.focusRequests) { if (composer.hasUnconsumedFocusRequest()) runCatching { field.requestFocus() } }
Column(
Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape16).background(colors.surface)
.border(if (focused || highlightControls) 2.dp else 1.dp, if (focused || highlightControls) pal.primary else pal.line, Shape16).padding(6.dp),
.border(if (focused) 2.dp else 1.dp, if (focused) pal.primary else pal.line, Shape16).padding(6.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().height(36.dp)) {
val model = AgentHost.models(context).firstOrNull { it.id == AgentHost.model }?.label ?: AgentHost.model ?: stringResource(R.string.agent_model_default)
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f, fill = false).height(30.dp).clip(Shape12).clickable { onPanel(AgentPanel.MODEL) }
.padding(horizontal = 8.dp).testTag("agent-model"),
) {
val parts = listOfNotNull(AgentHost.harness.name, model, AgentHost.effort, stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans })
Text(parts.joinToString(" · "), fontSize = 13.sp, color = if (panel == AgentPanel.MODEL) pal.primary else pal.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
Icon(Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
ContextRing("agent-usage", onClick = { onPanel(AgentPanel.USAGE) })
}
if (menu) {
HeaderAction(Icons.Outlined.History, stringResource(R.string.agent_history), size = 32.dp, tag = "agent-history") { onMenu(false); onPanel(AgentPanel.HISTORY) }
HeaderAction(Icons.Outlined.Memory, stringResource(R.string.agent_processes), size = 32.dp, tag = "agent-processes") { onMenu(false); onPanel(AgentPanel.PROCESSES) }
HeaderAction(Icons.Outlined.Add, stringResource(R.string.agent_new), enabled = !working && AgentHost.entries.isNotEmpty(), size = 32.dp, tag = "agent-new") {
onMenu(false)
AgentHost.forget(context)
}
HeaderAction(Icons.Outlined.Pets, stringResource(R.string.setup_agent_pet), selected = AgentPet.enabled, size = 32.dp, tag = "agent-pet-toggle") {
AgentPet.set(context, !AgentPet.enabled)
}
HeaderAction(Icons.Outlined.Settings, stringResource(R.string.agent_setup_title), enabled = !working, size = 32.dp, tag = "agent-settings") {
onMenu(false)
onSetup()
}
}
HeaderAction(if (menu) Icons.Outlined.Close else Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), size = 32.dp, tag = "agent-menu") { onMenu(!menu) }
}
Row(verticalAlignment = Alignment.Bottom) {
if (LocalActivityResultRegistryOwner.current != null) AttachButton()
if (AgentAttachments.gameFrame != null) GameFrameButton()
Box(Modifier.weight(1f).padding(start = 8.dp, top = 10.dp, bottom = 10.dp)) {
if (draft.isEmpty()) Text(
stringResource(if (working) R.string.agent_hint_working else R.string.agent_hint), fontSize = 16.sp,
@@ -688,27 +744,82 @@ private fun AgentEditor(
draft, { draft = it },
Modifier.fillMaxWidth().focusRequester(field).onFocusChanged {
focused = it.isFocused
if (it.isFocused) {
composer.consumeFocusRequest()
composer.opening = false
}
}.testTag("agent-input").then(inputModifier),
composer.focused = it.isFocused
if (it.isFocused) composer.consumeFocusRequest()
}.testTag("agent-input"),
textStyle = TextStyle(fontSize = 16.sp, color = colors.onSurface),
cursorBrush = SolidColor(pal.primary),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
keyboardActions = KeyboardActions(onSend = { send() }),
keyboardActions = KeyboardActions(onSend = {
voice.stop()
send()
}),
minLines = 1,
maxLines = 8,
)
}
if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() }
if (working) RoundButton(Icons.Outlined.Stop, stringResource(R.string.agent_stop), pal.error.copy(alpha = 0.22f), colors.error, "agent-stop") {
AgentHost.stop(context)
}
val canSend = draft.isNotBlank() || AgentAttachments.pending.isNotEmpty()
RoundButton(
// An empty message has nothing to send, so the button there dictates one instead.
if ((!canSend || voice.listening) && voiceAvailable) VoiceButton(voice) { voice.start(draft) }
else RoundButton(
Icons.AutoMirrored.Outlined.Send, stringResource(if (working) R.string.agent_queue else R.string.agent_send),
if (canSend) pal.primary else pal.surfaceVariant, if (canSend) pal.onPrimary else pal.onSurfaceVariant, "agent-send", enabled = canSend,
) { send() }
) {
voice.stop()
send()
}
}
}
}
@Composable
private fun VoiceButton(voice: AgentVoice, onStart: () -> Unit) {
val context = LocalContext.current
val pal = LocalPalette.current
val ask = if (LocalActivityResultRegistryOwner.current != null) rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) onStart() else android.widget.Toast.makeText(context, R.string.agent_voice_denied, android.widget.Toast.LENGTH_SHORT).show()
} else null
RoundButton(
if (voice.listening) Icons.Outlined.MicOff else Icons.Outlined.Mic, stringResource(if (voice.listening) R.string.agent_voice_stop else R.string.agent_voice),
if (voice.listening) pal.primary else pal.surfaceVariant, if (voice.listening) pal.onPrimary else pal.onBackground, "agent-voice",
) {
when {
voice.listening -> voice.finish()
context.checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == android.content.pm.PackageManager.PERMISSION_GRANTED -> onStart()
ask != null -> ask.launch(android.Manifest.permission.RECORD_AUDIO)
else -> android.widget.Toast.makeText(context, R.string.agent_voice_denied, android.widget.Toast.LENGTH_SHORT).show()
}
}
}
/** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */
@Composable
private fun GameFrameButton() {
val context = LocalContext.current
val pal = LocalPalette.current
RoundButton(Icons.Outlined.PhotoCamera, stringResource(R.string.agent_attach_game), pal.surfaceVariant, pal.onBackground, "agent-game-frame") {
val grab = AgentAttachments.gameFrame ?: return@RoundButton
val chat = AgentHost.chat
grab frame@{ frame ->
if (frame == null) {
android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show()
return@frame
}
Thread({
val path = AgentAttachments.saveFrame(context, chat, frame)
frame.recycle()
android.os.Handler(android.os.Looper.getMainLooper()).post {
when {
path == null -> android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show()
AgentHost.chat == chat -> AgentAttachments.pending.add(path)
else -> AgentAttachments.discard(context, listOf(path))
}
}
}, "agent-game-frame").start()
}
}
}
@@ -41,6 +41,18 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material3.Icon
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.text.TextStyle
import androidx.compose.runtime.rememberCoroutineScope
import kotlinx.coroutines.launch
import com.droiddeck.launcher.agent.AgentTools
import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentChats
import com.droiddeck.launcher.agent.AgentHarness
@@ -100,47 +112,88 @@ internal fun AgentHistory(modifier: Modifier, onOpened: () -> Unit) {
}
return
}
var query by rememberSaveable { mutableStateOf("") }
val found by produceState<List<AgentChats.Chat>?>(null, chats, query) {
if (query.isNotBlank()) delay(250)
value = withContext(Dispatchers.IO) { AgentChats.search(context, chats, query) }
}
val working = AgentHost.state == AgentHost.State.WORKING
LazyColumn(modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
items(chats, key = { it.id }) { chat ->
var armed by remember(chat.id) { mutableStateOf(false) }
val current = chat.id == AgentHost.chat
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().heightIn(min = 62.dp)
.clickable(enabled = !working || current) {
AgentHost.open(context, chat.id)
onOpened()
}
.background(if (current) pal.primary.copy(alpha = 0.12f) else colors.surface)
.padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-chat"),
) {
Column(Modifier.weight(1f)) {
Text(chat.title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
if (armed) stringResource(R.string.agent_history_delete_warning)
else AgentHarness.byId(chat.harness).name + " · " + when {
System.currentTimeMillis() - chat.updated < 60_000 -> stringResource(R.string.agent_just_now)
else -> DateUtils.getRelativeTimeSpanString(chat.updated, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS).toString()
},
fontSize = 12.5.sp, color = if (armed) AttentionAmber else pal.onSurfaceVariant,
)
}
SecondaryButton(
stringResource(if (armed) R.string.agent_storage_confirm else R.string.agent_history_delete), compact = true,
enabled = !(current && working),
) {
if (armed) {
AgentHost.delete(context, chat.id)
version++
} else armed = true
}
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
Column(modifier.fillMaxWidth()) {
AgentHistorySearch(query) { query = it }
val shown = found ?: chats
if (shown.isEmpty()) Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
Text(stringResource(R.string.agent_history_no_match), fontSize = 15.sp, color = pal.onSurfaceVariant)
} else LazyColumn(Modifier.weight(1f).fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
items(shown, key = { it.id }) { chat -> AgentHistoryRow(chat, working, onOpened) { version++ } }
}
}
}
@Composable
private fun AgentHistorySearch(query: String, onQuery: (String) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp).height(44.dp).clip(Shape14).background(colors.surface)
.border(1.dp, pal.line, Shape14).padding(horizontal = 12.dp),
) {
Icon(Icons.Outlined.Search, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(18.dp))
Box(Modifier.weight(1f).padding(start = 8.dp)) {
if (query.isEmpty()) Text(stringResource(R.string.agent_history_search), fontSize = 15.sp, color = pal.onSurfaceVariant, maxLines = 1)
BasicTextField(
query, onQuery, singleLine = true, textStyle = TextStyle(fontSize = 15.sp, color = colors.onSurface),
cursorBrush = SolidColor(pal.primary), modifier = Modifier.fillMaxWidth().testTag("agent-history-search"),
)
}
if (query.isNotEmpty()) Icon(Icons.Outlined.Close, stringResource(R.string.agent_close), tint = pal.onSurfaceVariant,
modifier = Modifier.size(28.dp).clip(CircleShape).clickable { onQuery("") }.padding(5.dp))
}
}
@Composable
private fun AgentHistoryRow(chat: AgentChats.Chat, working: Boolean, onOpened: () -> Unit, onDeleted: () -> Unit) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column {
var armed by remember(chat.id) { mutableStateOf(false) }
val current = chat.id == AgentHost.chat
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().heightIn(min = 62.dp)
.clickable(enabled = !working || current) {
AgentHost.open(context, chat.id)
onOpened()
}
.background(if (current) pal.primary.copy(alpha = 0.12f) else colors.surface)
.padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-chat"),
) {
Column(Modifier.weight(1f)) {
Text(chat.title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
if (armed) stringResource(R.string.agent_history_delete_warning)
else AgentHarness.byId(chat.harness).name + " · " + when {
System.currentTimeMillis() - chat.updated < 60_000 -> stringResource(R.string.agent_just_now)
else -> DateUtils.getRelativeTimeSpanString(chat.updated, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS).toString()
},
fontSize = 12.5.sp, color = if (armed) AttentionAmber else pal.onSurfaceVariant,
)
}
SecondaryButton(
stringResource(if (armed) R.string.agent_storage_confirm else R.string.agent_history_delete), compact = true,
enabled = !(current && working),
) {
if (armed) {
AgentHost.delete(context, chat.id)
onDeleted()
} else armed = true
}
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
}
/** Processes in the Linux userland, the agent's own first, each with a way to end it. */
@Composable
internal fun AgentProcessList(modifier: Modifier) {
@@ -260,3 +313,117 @@ private fun resetTime(context: android.content.Context, epochSeconds: Long): Str
else DateUtils.FORMAT_SHOW_WEEKDAY or DateUtils.FORMAT_ABBREV_WEEKDAY or DateUtils.FORMAT_SHOW_TIME
return DateUtils.formatDateTime(context, ms, flags)
}
/** Claude Code's MCP servers, with a way to add and remove them, and the skills in its skills folder. */
@Composable
internal fun AgentToolsPanel(modifier: Modifier) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val scope = rememberCoroutineScope()
var version by remember { mutableIntStateOf(0) }
var loading by remember { mutableStateOf(true) }
val servers by produceState<List<AgentTools.Server>?>(null, version) {
loading = true
value = withContext(Dispatchers.IO) { AgentTools.servers(context) }
loading = false
}
val skills by produceState(emptyList<AgentTools.Skill>(), version) { value = withContext(Dispatchers.IO) { AgentTools.skills(context) } }
var name by rememberSaveable { mutableStateOf("") }
var target by rememberSaveable { mutableStateOf("") }
var busy by remember { mutableStateOf(false) }
var message by remember { mutableStateOf<String?>(null) }
fun act(added: Boolean = false, action: suspend () -> AgentTools.Result) {
busy = true
message = null
scope.launch {
val result = withContext(Dispatchers.IO) { action() }
busy = false
if (!result.ok) message = result.output.ifBlank { context.getString(R.string.agent_tools_failed) }
else if (added) {
name = ""
target = ""
}
version++
}
}
LazyColumn(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
item { ToolsHeading(stringResource(R.string.agent_tools_servers)) }
val list = servers
when {
loading && list == null -> item { Text(stringResource(R.string.agent_tools_loading), fontSize = 13.sp, color = pal.onSurfaceVariant) }
list == null -> item { Text(stringResource(R.string.agent_tools_failed), fontSize = 13.sp, color = AttentionAmber) }
list.isEmpty() -> item { Text(stringResource(R.string.agent_tools_no_servers), fontSize = 13.sp, color = pal.onSurfaceVariant) }
else -> items(list, key = { "mcp:" + it.name }) { server ->
var armed by remember(server.name) { mutableStateOf(false) }
ToolsRow(server.name, server.target + " · " + server.status) {
if (!server.account) SecondaryButton(
stringResource(if (armed) R.string.agent_storage_confirm else R.string.agent_tools_remove), compact = true, enabled = !busy,
) { if (armed) act { AgentTools.remove(context, server.name) } else armed = true }
}
}
}
item {
Column(
Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).padding(12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
ToolsField(name, { name = it }, stringResource(R.string.agent_tools_name), "agent-tools-name")
ToolsField(target, { target = it }, stringResource(R.string.agent_tools_target), "agent-tools-target")
Row(verticalAlignment = Alignment.CenterVertically) {
Text(stringResource(R.string.agent_tools_add_hint), fontSize = 12.sp, color = pal.onSurfaceVariant, modifier = Modifier.weight(1f))
PrimaryButton(stringResource(R.string.agent_tools_add), enabled = !busy && name.isNotBlank() && target.isNotBlank(), compact = true) {
act(added = true) { AgentTools.add(context, name, target) }
}
}
message?.let { Text(it, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = AttentionAmber) }
}
}
item { ToolsHeading(stringResource(R.string.agent_tools_skills)) }
if (skills.isEmpty()) item { Text(stringResource(R.string.agent_tools_no_skills), fontSize = 13.sp, color = pal.onSurfaceVariant) }
items(skills, key = { "skill:" + it.name }) { skill ->
var armed by remember(skill.name) { mutableStateOf(false) }
ToolsRow(skill.name, skill.description) {
SecondaryButton(stringResource(if (armed) R.string.agent_storage_confirm else R.string.agent_history_delete), compact = true, enabled = !busy) {
if (armed) act {
AgentTools.Result(AgentTools.deleteSkill(context, skill.name), "")
} else armed = true
}
}
}
}
}
@Composable
private fun ToolsHeading(text: String) {
Text(text, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = LocalPalette.current.onSurfaceVariant, modifier = Modifier.padding(top = 6.dp))
}
@Composable
private fun ToolsRow(title: String, detail: String, action: @Composable () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).padding(horizontal = 14.dp, vertical = 10.dp),
) {
Column(Modifier.weight(1f)) {
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (detail.isNotBlank()) Text(detail, fontSize = 12.5.sp, color = pal.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
action()
}
}
@Composable
private fun ToolsField(value: String, onValue: (String) -> Unit, hint: String, tag: String) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Box(Modifier.fillMaxWidth().clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 12.dp, vertical = 10.dp)) {
if (value.isEmpty()) Text(hint, fontSize = 14.sp, color = pal.onSurfaceVariant, maxLines = 1)
BasicTextField(
value, onValue, singleLine = true, textStyle = TextStyle(fontSize = 14.sp, fontFamily = FontFamily.Monospace, color = colors.onSurface),
cursorBrush = SolidColor(pal.primary), modifier = Modifier.fillMaxWidth().testTag(tag),
)
}
}
@@ -22,7 +22,6 @@ 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
@@ -34,7 +33,6 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
@@ -62,9 +60,7 @@ import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
@@ -110,7 +106,11 @@ internal class PetMotion(private val context: Context) {
private val margin = 6 * density
private val inset = 24 * density
private var settle: ValueAnimator? = null
private val spring = FlingSpring { sx, sy -> x = sx; y = sy }
// A fling's overshoot may carry the pet past the edge it settles on, but never so far that it leaves the screen.
private val spring = FlingSpring { sx, sy ->
x = sx.coerceIn(-size / 2, (width - size / 2).coerceAtLeast(-size / 2))
y = sy.coerceIn(0f, (height - size).coerceAtLeast(0f))
}
val dockX get() = width - size - margin
@@ -333,11 +333,24 @@ internal class PetWindows(private val context: Context) {
gravity = Gravity.TOP or Gravity.START
if (full) softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
noMoveAnimation(this)
}
if (onSize != null) compose.addOnLayoutChangeListener { v, _, _, _, _, _, _, _, _ -> onSize(v.width, v.height) }
return Window(frame, params, touchable)
}
/**
* The system otherwise eases a moved overlay from where it last placed it, so the pet trails behind
* the finger, lags the chat as it opens, or flashes at an old spot. setCanPlayMoveAnimation sets the
* same flag but makes some ROMs refuse the window, so the flag is set directly.
*/
private fun noMoveAnimation(params: WindowManager.LayoutParams) {
runCatching {
val field = WindowManager.LayoutParams::class.java.getField("privateFlags")
field.setInt(params, field.getInt(params) or PRIVATE_FLAG_NO_MOVE_ANIMATION)
}
}
/** A hidden overlay window still owns its frame, which the system can stretch over the screen, so it also stops taking touches. */
private fun setVisible(window: Window, shown: Boolean) {
window.view.visibility = if (shown) View.VISIBLE else View.GONE
@@ -467,6 +480,7 @@ internal class PetWindows(private val context: Context) {
companion object {
private const val OFFSCREEN = 10_000
private const val PRIVATE_FLAG_NO_MOVE_ANIMATION = 0x40
fun allowed(context: Context) = Settings.canDrawOverlays(context)
}
}
@@ -501,6 +515,7 @@ internal fun PetChat(open: Boolean, motion: PetMotion, onClose: () -> Unit, onCl
} else {
Rect(margin, motion.dockY + motion.size + gap, w - margin, h - margin)
}
val menuSlot = remember { AgentMenuSlot() }
val grow = remember { Animatable(0f) }
val fade = remember { Animatable(0f) }
LaunchedEffect(open) {
@@ -538,12 +553,10 @@ internal fun PetChat(open: Boolean, motion: PetMotion, onClose: () -> Unit, onCl
.padding(start = 12.dp, end = 12.dp, top = 6.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(bottom = 2.dp)) {
Text(stringResource(R.string.agent_pet_name), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
modifier = Modifier.padding(start = 4.dp))
Spacer(Modifier.weight(1f))
Box(Modifier.weight(1f)) { menuSlot.content?.invoke() }
HeaderAction(Icons.Outlined.Close, stringResource(R.string.agent_close), size = 34.dp, tag = "agent-pet-close", onClick = onClose)
}
AgentPage(Modifier.weight(1f).fillMaxWidth(), visible = open, startTyping = AgentHost.entries.isEmpty(), hidesPet = false)
AgentPage(Modifier.weight(1f).fillMaxWidth(), visible = open, startTyping = AgentHost.entries.isEmpty(), hidesPet = false, menuSlot = menuSlot)
}
}
}
Loaded 100 of 441 files, more files were not shown because too many files have changed in this diff. Show more