Merge main and retain unified input behavior

This commit is contained in:
Delete228 committed 2026-11-07 00:01:20 +03:00
commit f44826ae3a
75 files changed
+2441 -160

No files matched your search

@@ -5,8 +5,11 @@ import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.ComponentUpdater
import com.droiddeck.launcher.session.ComponentUpdates
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.ProtonDefault
import com.droiddeck.launcher.session.SessionPrefs
internal class ComponentsMenu(private val activity: android.app.Activity, private val ui: Handler) {
var compSnapshot by mutableStateOf<ComponentsManager.Snapshot?>(null)
@@ -20,6 +23,10 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
get() = downloads
private set(value) { downloads = value }
val compDownloadRevision: Long get() = downloadRevision
var compModes by mutableStateOf<Map<String, String>>(emptyMap())
var compAuto by mutableStateOf<Map<String, List<ComponentUpdater.Status>>>(emptyMap())
var compAutoHeld by mutableStateOf<Set<String>>(emptySet())
var compAutoChecking by mutableStateOf(false)
private var shownDefault: String? = null
fun refreshComponents(snapshotFirst: Boolean = false) {
@@ -29,7 +36,14 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
val snap = runCatching { ComponentsManager.snapshot(activity) }.onFailure { Log.w(TAG, "components", it) }.getOrNull()
val cat = runCatching { ComponentsManager.catalog(activity, false) }.getOrNull()
val chosen = snap?.let { s -> runCatching { ProtonDefault.selectedId(activity, s.protons.map { it.proton }) }.getOrNull() }
runCatching { ComponentUpdater.settle(activity) }
val modes = ComponentsManager.COMPONENTS.associateWith { SessionPrefs.componentMode(activity, it) }
val auto = ComponentsManager.COMPONENTS.associateWith { runCatching { ComponentUpdater.status(activity, it) }.getOrDefault(emptyList()) }
val held = if (runCatching { ComponentsManager.hardwareDxvk(activity) }.getOrDefault(false)) setOf("dxvk") else emptySet()
ui.post {
compModes = modes
compAuto = auto
compAutoHeld = held
compSnapshot = snap ?: ComponentsManager.Snapshot(emptyList(), emptyList())
if (cat != null && cat.fetchedAt > 0) { compCatalog = cat.items; compCatalogAt = cat.fetchedAt }
if (chosen != null && chosen != shownDefault) {
@@ -42,6 +56,35 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
}, "components").start()
}
fun chooseComponentMode(comp: String, mode: String) {
SessionPrefs.setComponentMode(activity, comp, mode)
compModes = compModes + (comp to mode)
if (mode != ComponentUpdates.AUTO) return
checkComponentUpdates(force = true)
}
private var checkAgain: Boolean? = null
fun checkComponentUpdates(force: Boolean) {
if (compAutoChecking) {
checkAgain = force || checkAgain == true
return
}
compAutoChecking = true
Thread({
val notes = runCatching { ComponentUpdater.ensure(activity, force) }.onFailure { Log.w(TAG, "component updates", it) }.getOrDefault(emptyList())
ui.post {
compAutoChecking = false
checkAgain?.let { again ->
checkAgain = null
checkComponentUpdates(again)
}
if (notes.isNotEmpty()) android.widget.Toast.makeText(activity, notes.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show()
refreshComponents()
}
}, "component-updates").start()
}
fun chooseProton(id: String) {
val proton = compSnapshot?.protons?.firstOrNull { it.proton.id == id }?.proton ?: return
compProton = id
@@ -40,6 +40,8 @@ import com.droiddeck.launcher.ui.PackageRow
import com.droiddeck.launcher.ui.exposeTestTags
import com.droiddeck.launcher.session.OfflineMode
import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.session.ComponentUpdater
import com.droiddeck.launcher.session.ComponentUpdates
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.ui.ComponentsPage
import com.droiddeck.launcher.session.GameSaves
@@ -92,7 +94,11 @@ class FrontEndActivity : ComponentActivity() {
private val components = ComponentsMenu(this, ui)
private val decky = DeckyMenu(this, ui)
private val updates = UpdatesMenu(this, ui)
private val protons = ProtonMenu(this, ui) { !busy && flood == null && compatLaunch == null && pkgStage == null && components.compBusy == null }
private val protons = ProtonMenu(
this, ui,
idle = { !busy && flood == null && compatLaunch == null && pkgStage == null && components.compBusy == null },
onInstalled = { if (!OfflineMode.enabled(this)) components.checkComponentUpdates(force = false) },
)
private var installed by mutableStateOf<String?>(null)
private var flood by mutableStateOf<PendingFlood?>(null)
@@ -199,6 +205,7 @@ class FrontEndActivity : ComponentActivity() {
private var gameStoresSpeedTier by mutableStateOf("fast")
private var navRequest by mutableStateOf<String?>(null)
private val gameLaunchRequest = java.util.concurrent.atomic.AtomicLong()
private var preparingGames by mutableStateOf(emptySet<String>())
private var storesShowMature by mutableStateOf(false)
private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first())
private var storesView by mutableStateOf(SessionPrefs.DEFAULT_STORES_VIEW)
@@ -1135,6 +1142,7 @@ class FrontEndActivity : ComponentActivity() {
installed = installed, ready = ready, available = available?.version, removalPending = removalPending, runtimeActionsBlocked = runtimeChangesBlocked(),
vkBridge = vkBridge, venus = venus, venusHostVulkan = venusHostVulkan, vkBridgeSafe = vkBridgeSafe, bridgeProtonDxvk = bridgeProtonDxvk, adreno = adrenoGpu,
shortcutPicker = shortcutPicker,
preparingGames = preparingGames,
shortcutLibraryScanning = shortcutLibraryScanning,
gameSyncFolder = gameSyncFolder,
busy = busy, stage = stage, percent = percent,
@@ -1213,14 +1221,26 @@ class FrontEndActivity : ComponentActivity() {
},
onSteamGame = { g ->
if (shortcutPicker) chooseGameShortcut(g)
else {
val request = gameLaunchRequest.incrementAndGet()
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g) {
if (request != gameLaunchRequest.get() || isFinishing || isDestroyed) return@beforeLaunch
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) {
if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g)
else if (g.launchKey !in preparingGames) {
preparingGames = preparingGames + g.launchKey
prepareAndLaunch(g, g.launchKey)
}
},
onStoreGame = { store, id ->
val key = "${store.id}:$id"
if (key !in preparingGames) {
preparingGames = preparingGames + key
val app = applicationContext
Thread({
val g = runCatching { com.droiddeck.launcher.stores.StoreLaunch.installedGame(app, store, id) }.getOrNull()
runOnUiThread {
if (g != null && !isFinishing && !isDestroyed) prepareAndLaunch(g, key)
else {
preparingGames = preparingGames - key
if (g == null && !isFinishing && !isDestroyed) android.widget.Toast.makeText(this, R.string.stores_launch_not_registered, android.widget.Toast.LENGTH_LONG).show()
}
}
}
}, "store-play").start()
}
},
onEpicLauncher = { openEpicLauncher() },
@@ -1862,6 +1882,13 @@ class FrontEndActivity : ComponentActivity() {
if (applied.isNotEmpty()) ui.post {
android.widget.Toast.makeText(this, getString(R.string.main_applied, applied.joinToString(", ")), android.widget.Toast.LENGTH_LONG).show()
}
if (!OfflineMode.enabled(this)) {
val updated = runCatching { ComponentUpdater.ensure(this, force = false) }
.onFailure { android.util.Log.w("ComponentUpdater", "automatic component updates", it) }.getOrDefault(emptyList())
if (updated.isNotEmpty()) ui.post {
android.widget.Toast.makeText(this, updated.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show()
}
}
ui.post {
componentsQueueBusy = false
if (showComponents) components.refreshComponents()
@@ -1924,6 +1951,18 @@ class FrontEndActivity : ComponentActivity() {
if (Build.VERSION.SDK_INT >= 33) state.getParcelable(key, Intent::class.java)
else @Suppress("DEPRECATION") state.getParcelable(key)
private fun prepareAndLaunch(g: Library.SteamGame, key: String) {
val request = gameLaunchRequest.incrementAndGet()
val done = { preparingGames = preparingGames - key }
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)
}
}
}
override fun onDestroy() {
gameLaunchRequest.incrementAndGet()
cancelCompatLaunch()
@@ -2129,7 +2168,15 @@ class FrontEndActivity : ComponentActivity() {
onDeletePackage = { file -> components.componentAction(getString(R.string.comp_busy_deleting)) { ComponentsManager.deletePackage(this, file) } },
onDeleteOriginal = { version -> components.compProton?.let { pid -> components.componentAction(getString(R.string.comp_busy_deleting)) { ComponentsManager.deleteOriginal(this, pid, components.compComp, version) } } },
onDownload = { components.downloadComponent(it) },
onRefresh = { components.refreshComponentCatalog() },
onRefresh = {
components.refreshComponentCatalog()
if (components.compModes.values.any { it == ComponentUpdates.AUTO }) components.checkComponentUpdates(force = true)
},
compModes = components.compModes,
compAuto = components.compAuto,
compAutoHeld = components.compAutoHeld,
compAutoChecking = components.compAutoChecking,
onCompMode = { comp, mode -> components.chooseComponentMode(comp, mode) },
onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, getString(R.string.comp_pick_wcp))) },
onBack = { if (!com.droiddeck.launcher.ui.Hops.back { showComponents = false }) showComponents = false },
games = steamGames,
@@ -2959,6 +3006,7 @@ class FrontEndActivity : ComponentActivity() {
private fun removeRuntime() {
if (runtimeChangesBlocked()) return
val removal = LinuxRuntimeInstaller.beginUninstall(this) ?: return
com.droiddeck.launcher.runtime.RuntimeAutoUpdate.seed(this)
ready = false
com.droiddeck.launcher.runtime.RuntimeInstallService.keepRemovalAlive(this)
followRuntimeOperation { removal.run(it) }
@@ -2985,6 +3033,7 @@ class FrontEndActivity : ComponentActivity() {
android.widget.Toast.makeText(this, it, android.widget.Toast.LENGTH_LONG).show()
}
refresh()
if (ok == true && LinuxRuntime.isInstalled(this)) protons.checkUpdates()
}
}, "runtime-operation").start()
}
@@ -2992,9 +3041,12 @@ class FrontEndActivity : ComponentActivity() {
private fun autoUpdateRuntime() {
val release = available?.takeIf { catalogFresh } ?: return
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED) || runtimeChangesBlocked() || removalPending) return
if (release.version == installed || installed == null) return
if (installed != null) com.droiddeck.launcher.runtime.RuntimeAutoUpdate.seed(this)
if (release.version == installed) return
if (installed == null && (OfflineMode.enabled(this) || !com.droiddeck.launcher.core.DeviceSupport.canDraw(this) ||
!com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.unfavourable(this))) return
if (com.droiddeck.launcher.runtime.RuntimeAutoUpdate.claim(this, installed, release.version)) {
Log.i(TAG, "runtime: updating $installed to ${release.version} by itself")
Log.i(TAG, "runtime: installing ${release.version} over ${installed ?: "nothing"} by itself")
install(release)
}
}
@@ -18,6 +18,7 @@ import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
internal class ProtonMenu(
private val activity: android.app.Activity,
private val ui: Handler,
private val onInstalled: () -> Unit = {},
private val idle: () -> Boolean = { true },
) {
private object Operation {
@@ -61,6 +62,7 @@ internal class ProtonMenu(
if (automatic) Log.w("ProtonMenu", "auto-update ${tool.id}: $problem")
else android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
}
if (problem == null) onInstalled()
if (automatic) ensureAutoUpdates()
}
}, "install-proton-$id").start()
@@ -4,6 +4,7 @@ import androidx.compose.foundation.background
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import android.hardware.input.InputManager
import android.hardware.display.DisplayManager
import android.content.Intent
@@ -275,6 +276,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var directHoldBehavior by mutableStateOf(com.droiddeck.launcher.input.TouchGestureConfig.MOUSE_BEHAVIOR_CLICK)
private var relativeMouseMode by mutableIntStateOf(0)
@Volatile private var appliedRelativeMouseMode: Int? = null
private val appTextFocus get() = wowChat.request != null
private val wowChat by lazy { com.droiddeck.launcher.ui.WowChat(this, ::sendWowChat, ::cancelWowChat, ::readGameField) }
private var wowChatBottom: SecondScreenPresentation? = null
private var wowChatOnTop by mutableStateOf(false)
private var recognizedGesture by mutableStateOf<TouchscreenGestures.Gesture?>(null)
private var gesturePointerX = 0f
private var gesturePointerY = 0f
@@ -847,7 +852,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(it))
}
sessionOverlay = createSessionOverlay()
root.addView(sessionOverlay)
root.addView(object : FrameLayout(this) {
override fun onResolvePointerIcon(event: MotionEvent, pointerIndex: Int): android.view.PointerIcon? =
if (platformPointerShown == true) super.onResolvePointerIcon(event, pointerIndex) else null
}.apply { addView(sessionOverlay) })
setContentView(root)
glassesScope.launch { Glasses.state.collect {
glasses = it
@@ -932,6 +940,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
androidx.compose.runtime.LaunchedEffect(AgentGuest.steamKeyboard) { updateOnScreenControls() }
androidx.compose.runtime.LaunchedEffect(AgentGuest.desktopTextField) { onDesktopTextField(AgentGuest.desktopTextField) }
androidx.compose.runtime.LaunchedEffect(AgentGuest.gameTextField, AgentGuest.gameProgram) { onGameTextField(AgentGuest.gameTextField) }
androidx.compose.runtime.LaunchedEffect(wowChat.request) { placeWowChat() }
androidx.compose.runtime.LaunchedEffect(pipUi, pcKeyboardOpen) { updateDesktopKeyboardButton() }
val keyboardRequestsSeen = androidx.compose.runtime.remember { intArrayOf(AgentGuest.keyboardRequests) }
androidx.compose.runtime.LaunchedEffect(AgentGuest.keyboardRequests) {
@@ -1023,10 +1033,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
runCatching { com.droiddeck.launcher.session.TelemetryOutput.applyAutomatic(this@SessionActivity, nextGame) }
}
}
LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, inputSettingsOpen, pipUi, SessionState.suspended, resumed) {
LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, inputSettingsOpen, pipUi, SessionState.suspended, resumed, appTextFocus) {
updateOnScreenControls()
padBridge?.setInputEnabled(resumed && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && !SessionState.suspended)
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || inputSettingsOpen || pipUi || SessionState.suspended) {
padBridge?.setInputEnabled(resumed && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && !appTextFocus && !SessionState.suspended)
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || inputSettingsOpen || pipUi || appTextFocus || SessionState.suspended) {
backQamInput.cancel()
com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this@SessionActivity)
cancelTouchGestures()
@@ -1068,6 +1078,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
}
if (wowChat.asking) com.droiddeck.launcher.ui.WowChatChoiceDialog(wowChat)
if (wowChatOnTop && wowChat.request != null) androidx.compose.foundation.layout.Box(
Modifier.fillMaxSize().imePadding(), contentAlignment = androidx.compose.ui.Alignment.BottomCenter,
) { com.droiddeck.launcher.ui.WowChatPanel(wowChat) }
if (gestureSettingsOpen) com.droiddeck.launcher.ui.TouchGestureDialog(
game = gestureGame,
onDismiss = { gestureSettingsOpen = false },
@@ -1267,6 +1281,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
},
onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; keyboard?.toggle() },
onHardwareKeyboard = ::togglePcKeyboard,
wowChatShown = com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram),
wowChat = wowChat.remembered,
onWowChat = wowChat::choose,
controller = controllerSettings,
onRumble = { on -> updateControllerPrefs { ControllerPrefs.setRumble(this@SessionActivity, on) } },
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
@@ -2205,9 +2222,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun windowOutputSize(width: Int, height: Int): Pair<Int, Int>? {
if (width <= 0 || height <= 0) return null
if (isInPictureInPictureMode) return com.droiddeck.launcher.session.PipPolicy.outputSize(
width, height, SessionState.outputSize.first, SessionState.outputSize.second)
if (width <= 0 || height <= 0 || isInPictureInPictureMode) return null
if (bottomGame != null) return when {
SessionState.followScreen ->
com.droiddeck.launcher.session.SessionDisplay.followSize(width, height, false, SessionState.followScale)
@@ -2579,7 +2594,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionState.mode == SessionService.MODE_STEAM && SessionState.running &&
SessionState.firstFrameSeen && !SessionState.suspended && !ended &&
!pipUi && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
!gestureSettingsOpen && !inputSettingsOpen && window.decorView.hasWindowFocus()
!gestureSettingsOpen && !inputSettingsOpen && !appTextFocus && window.decorView.hasWindowFocus()
if (steamVolume) {
val audio = getSystemService(android.media.AudioManager::class.java)
if (com.droiddeck.launcher.input.SteamVolumeKeys.dispatch(event, !audio.isVolumeFixed) { direction ->
@@ -2589,6 +2604,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return super.dispatchKeyEvent(event)
}
}
if (appTextFocus) return super.dispatchKeyEvent(event)
if (!pipUi) {
if (physicalInputBindings?.onKey(event, resumed && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
!inputSettingsOpen && !gestureSettingsOpen && !SessionState.suspended && !loading.visible) == true) return true
@@ -2617,10 +2633,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Log.i(TAG, String.format(java.util.Locale.ROOT, "back key device=%d (%s) source=0x%x flags=0x%x",
event.deviceId, event.device?.name, event.source, event.flags))
}
val mouseToGuest = !pipUi && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen &&
val mouseToGuest = !pipUi && !appTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen &&
!SessionState.suspended && !(::loading.isInitialized && (loading.visible || loading.ended))
if (mouseBackInput.onKeyEvent(event, mouseToGuest)) return true
val backToQam = !pipUi && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
val backToQam = !pipUi && !appTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
!inputSettingsOpen && !gestureSettingsOpen &&
SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen &&
!SessionState.suspended && padBridge?.canHoldQam() == true
@@ -3547,20 +3563,105 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
panel.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, height - gameHeight, Gravity.BOTTOM)
}
private fun openBottomKeyboard() {
if (!started) return
private fun bottomKeyboardPresentation(): SecondScreenPresentation? {
if (!started) return null
if (secondScreenPresentation?.showsKeyboard != true && dockDrawer()) {
val target = com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId) ?: return
val target = com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId) ?: return null
if (drawerOpen || drawerPinned) drawerOpen = false
typingReturnMode = secondScreenMode
selectedSecondScreenDisplay = target.displayId
selectSecondScreenMode(SecondScreenMode.CUSTOM_CONTROLS)
}
val presentation = secondScreenPresentation ?: return
if (!presentation.showsKeyboard) return
val display = presentation.display?.displayId ?: return
return secondScreenPresentation?.takeIf { it.showsKeyboard && it.display != null }
}
private fun openBottomKeyboard() {
val presentation = bottomKeyboardPresentation() ?: return
presentation.requestKeyboard(forField = true)
com.droiddeck.launcher.ui.SessionTyping.focusDisplay(this, display)
com.droiddeck.launcher.ui.SessionTyping.focusDisplay(this, presentation.display.displayId)
}
private fun onGameTextField(focused: Boolean) {
if (!focused || !com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram)) wowChat.chatClosed()
else if (resumed && !pipUi && !pcKeyboardOpen &&
resources.configuration.hardKeyboardHidden != android.content.res.Configuration.HARDKEYBOARDHIDDEN_NO) {
keyboard?.takeIf { it.shown }?.hide()
wowChat.chatOpened()
}
}
private fun placeWowChat() {
val open = wowChat.request != null
val shown = wowChatBottom
wowChatOnTop = false
if (open && shown == null) {
val presentation = bottomKeyboardPresentation()
if (presentation == null) {
wowChatOnTop = true
return
}
wowChatBottom = presentation
presentation.showChat(onLost = {
if (wowChatBottom === presentation) {
wowChatBottom = null
wowChatOnTop = wowChat.request != null
}
}) {
androidx.compose.runtime.CompositionLocalProvider(
androidx.activity.compose.LocalActivityResultRegistryOwner provides this,
androidx.activity.compose.LocalOnBackPressedDispatcherOwner provides this,
) { DroidDeckTheme { com.droiddeck.launcher.ui.WowChatPanel(wowChat) } }
}
com.droiddeck.launcher.ui.SessionTyping.focusDisplay(this, presentation.display.displayId)
} else if (!open && shown != null) {
wowChatBottom = null
shown.hideChat()
if (secondScreenPresentation === shown) bottomKeyboardClosed()
}
}
private fun sendWowChat(text: String, replace: Boolean) {
val host = keyboard ?: return
if (replace) {
selectGameField()
if (text.isEmpty()) host.tap(KeyEvent.KEYCODE_DEL)
} else {
endGameField()
}
host.type(text)
host.tap(KeyEvent.KEYCODE_ENTER)
uiHandler.postDelayed({
if (AgentGuest.gameTextField && com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram)) endGameField()
}, FIELD_SETTLE_MS)
}
private fun endGameField() {
WaylandCompositor.nativeSendKey(KEY_END, 1)
WaylandCompositor.nativeSendKey(KEY_END, 0)
}
private fun selectGameField(vararg then: Int) {
heldKeys.set(256, KEY_LEFTCTRL, true)
try {
for (key in intArrayOf(KEY_A) + then) {
heldKeys.set(256, key, true)
heldKeys.set(256, key, false)
}
} finally { heldKeys.release(256) }
}
private fun readGameField(done: (String?) -> Unit) {
val opened = wowChat.request
val stillOpen = { wowChat.request === opened && AgentGuest.gameTextField }
sessionClipboard.captureGuest(FIELD_READ_MS, onTimeout = { if (stillOpen()) endGameField() }) { text ->
if (text != null && stillOpen()) endGameField()
done(text)
}
selectGameField(KEY_C)
}
private fun cancelWowChat() {
keyboard?.tap(KeyEvent.KEYCODE_ESCAPE)
}
private fun bottomKeyboardClosed() {
@@ -3985,7 +4086,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun appUiOwnsPointer(): Boolean =
drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || pipUi || glassesOutputActive || bottomOutputActive || touchEditorOpen
drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || pipUi || glassesOutputActive || bottomOutputActive || touchEditorOpen || wowChatOnTop
private fun applyPlatformPointer(shown: Boolean) {
if (!::sessionRoot.isInitialized || !::surfaceView.isInitialized) return
@@ -4297,6 +4398,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun showPipUi(show: Boolean) {
pipUi = show
if (show) {
if (::hud.isInitialized) hud.setHidden(true)
drawerOpen = false
pcKeyboardOpen = false
achievementsOpen = false
@@ -5209,6 +5311,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private const val AXIS_UNITS_PER_PIXEL = 3f
private const val KEY_LEFTCTRL = 29
private const val KEY_RIGHTCTRL = 97
private const val KEY_A = 30
private const val KEY_C = 46
private const val KEY_END = 107
private const val FIELD_READ_MS = 600L
private const val FIELD_SETTLE_MS = 200L
private const val BTN_SIDE = 0x113
private const val BTN_EXTRA = 0x114
private const val DESKTOP_GRAB_TAP_MS = 500L
@@ -26,6 +26,10 @@ object AgentGuest {
private set
var keyboardRequests by mutableIntStateOf(0)
private set
var gameTextField by mutableStateOf(false)
private set
var gameProgram by mutableStateOf<String?>(null)
private set
var keyboardDismissals by mutableIntStateOf(0)
private set
@Volatile private var keyboardRoute = false
@@ -43,7 +47,7 @@ object AgentGuest {
observer?.stopWatching()
observer = null
lastFocusKey = null
main.post { steamKeyboard = false; desktopTextField = false }
main.post { steamKeyboard = false; desktopTextField = false; gameTextField = false; gameProgram = null }
val dir = dir(context)
dir.deleteRecursively()
dir.mkdirs()
@@ -59,6 +63,7 @@ object AgentGuest {
"focus.json" -> readJson(File(dir, path))?.let(::recordFocus)
"keyboard.json" -> readJson(File(dir, path))?.let { recordKeyboard(this, it) }
"ime.json" -> readJson(File(dir, path))?.let { recordTextField(this, it) }
"wine-ime.json" -> readJson(File(dir, path))?.let { recordGameTextField(this, it) }
"keyboard-request.json" -> readJson(File(dir, path))?.let { recordKeyboardRequest(this) }
"keyboard-dismiss.json" -> readJson(File(dir, path))?.let { recordKeyboardDismiss(this) }
}
@@ -71,7 +76,7 @@ object AgentGuest {
synchronized(lock) {
observer?.stopWatching()
observer = null
main.post { steamKeyboard = false; desktopTextField = false }
main.post { steamKeyboard = false; desktopTextField = false; gameTextField = false; gameProgram = null }
}
}
@@ -129,6 +134,16 @@ object AgentGuest {
SessionEvents.record("ime.changed", mapOf("textField" to focused, "seq" to snapshot.optInt("seq")))
}
private fun recordGameTextField(source: FileObserver, snapshot: JSONObject) {
val focused = snapshot.optBoolean("textField")
val program = snapshot.optString("program").takeIf { it.isNotEmpty() }
synchronized(lock) {
if (source !== observer) return
main.post { gameProgram = program; gameTextField = focused }
}
SessionEvents.record("game.ime.changed", mapOf("textField" to focused, "program" to program, "seq" to snapshot.optInt("seq")))
}
private fun recordFocus(snapshot: JSONObject) {
val fields = linkedMapOf<String, Any?>(
"focusedApp" to snapshot.opt("focusedApp"),
@@ -475,15 +475,15 @@ object AutoComponents {
return true
}
fun beforeLaunch(context: Context, game: Library.SteamGame, onReady: () -> Unit) {
fun beforeLaunch(context: Context, game: Library.SteamGame, onBlocked: () -> Unit = {}, onReady: () -> Unit) {
val app = context.applicationContext
Thread({
val ready = runCatching { prepareLaunch(app, game) }.getOrElse {
Log.w(TAG, "${game.name}: launch repair discovery failed: ${it.javaClass.simpleName}: ${it.message}")
false
}
Handler(Looper.getMainLooper()).post(if (ready) onReady else onBlocked)
queueGame(app, game, asked = false)
if (ready) Handler(Looper.getMainLooper()).post(onReady)
}, "auto-components-launch").apply { isDaemon = true; start() }
}
@@ -23,6 +23,7 @@ object Library {
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo)
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
val launchKey: String get() = if (storeId != null) "$source:$storeId" else gameIdString
val profileKey: String get() = when {
source == com.droiddeck.launcher.stores.Store.BATTLENET.id -> com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString()
library == ADDED -> java.lang.Integer.toUnsignedString(appId)
@@ -89,21 +89,31 @@ class KeyboardHost(
clearFocus()
}
fun type(text: CharSequence?) {
if (text.isNullOrEmpty()) return
val events = map.getEvents(text.toString().toCharArray())
if (events != null) {
for (event in events) sendKeyEvent(event)
} else {
for (ch in text) {
val t = System.currentTimeMillis()
val down = KeyEvent(t, t, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_UNKNOWN, 0, 0,
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, 0)
sendKeyEvent(CharKeyEvent(down, ch))
sendKeyEvent(CharKeyEvent(KeyEvent.changeAction(down, KeyEvent.ACTION_UP), ch))
}
}
}
fun tap(keyCode: Int) {
val t = System.currentTimeMillis()
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_DOWN, keyCode, 0))
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_UP, keyCode, 0))
}
private inner class KeyConnection : BaseInputConnection(this, false) {
override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
if (text.isNullOrEmpty()) return true
val events = map.getEvents(text.toString().toCharArray())
if (events != null) {
for (event in events) sendKeyEvent(event)
} else {
for (ch in text) {
val t = System.currentTimeMillis()
val down = KeyEvent(t, t, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_UNKNOWN, 0, 0,
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, 0)
sendKeyEvent(CharKeyEvent(down, ch))
sendKeyEvent(CharKeyEvent(KeyEvent.changeAction(down, KeyEvent.ACTION_UP), ch))
}
}
type(text)
return true
}
@@ -123,12 +133,6 @@ class KeyboardHost(
return true
}
private fun tap(keyCode: Int) {
val t = System.currentTimeMillis()
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_DOWN, keyCode, 0))
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_UP, keyCode, 0))
}
override fun getTextBeforeCursor(n: Int, flags: Int): CharSequence = ""
override fun getTextAfterCursor(n: Int, flags: Int): CharSequence = ""
override fun getSelectedText(flags: Int): CharSequence? = null
@@ -19,11 +19,20 @@ class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
private var published = false
private var shared: String? = null
private var echo: String? = null
private var capture: ((String?) -> Unit)? = null
private var captureBefore: String? = null
private var captureLate: (() -> Unit)? = null
private val androidListener = ClipboardManager.OnPrimaryClipChangedListener { refresh(changed = true) }
private val guestListener = object : WaylandCompositor.ClipboardListener {
override fun onGuestClipboardText(text: String) {
handler.post {
if (active && hasFocus() && WaylandCompositor.isClipboardListener(this)) {
val taken = capture?.takeIf { text != captureBefore }
if (taken != null && WaylandCompositor.isClipboardListener(this)) {
capture = null
handler.removeCallbacks(captureTimeout)
WaylandCompositor.setClipboardText(shared)
taken(text)
} else if (active && hasFocus() && WaylandCompositor.isClipboardListener(this)) {
val current = clipboard.primaryClip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text
shared = text
published = true
@@ -36,6 +45,21 @@ class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
}
}
private val captureTimeout = Runnable {
val taken = capture ?: return@Runnable
capture = null
captureLate?.invoke()
taken(null)
}
fun captureGuest(timeoutMs: Long, onTimeout: () -> Unit = {}, onText: (String?) -> Unit) {
capture?.let { handler.removeCallbacks(captureTimeout); it(null) }
capture = onText
captureLate = onTimeout
captureBefore = shared
handler.postDelayed(captureTimeout, timeoutMs)
}
fun start() {
if (active) return
active = true
@@ -47,6 +71,8 @@ class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
fun stop() {
if (!active) return
active = false
handler.removeCallbacks(captureTimeout)
capture?.let { capture = null; it(null) }
clipboard.removePrimaryClipChangedListener(androidListener)
WaylandCompositor.clearClipboardListener(guestListener)
handler.removeCallbacksAndMessages(null)
@@ -8,8 +8,10 @@ object RuntimeAutoUpdate {
const val MAX_ATTEMPTS = 3
const val RETRY_MS = 10 * 60_000L
fun due(installed: String?, release: String?, attempts: Int, lastAt: Long = 0L, now: Long = lastAt + RETRY_MS): Boolean =
installed != null && !release.isNullOrEmpty() && release != installed && attempts < MAX_ATTEMPTS &&
private const val SEEDED = "seeded"
fun due(installed: String?, release: String?, attempts: Int, lastAt: Long = 0L, now: Long = lastAt + RETRY_MS, first: Boolean = false): Boolean =
(installed != null || first) && !release.isNullOrEmpty() && release != installed && attempts < MAX_ATTEMPTS &&
(attempts == 0 || now - lastAt !in 0 until RETRY_MS)
fun key(appVersion: Int, release: String) = "$appVersion:$release"
@@ -20,11 +22,17 @@ object RuntimeAutoUpdate {
val key = key(BuildConfig.VERSION_CODE, release)
synchronized(this) {
val attempts = prefs.getInt(key, 0)
if (!due(installed, release, attempts, prefs.getLong("$key@at", 0L), now)) return false
val first = installed == null && !prefs.getBoolean(SEEDED, false)
if (!due(installed, release, attempts, prefs.getLong("$key@at", 0L), now, first)) return false
val edit = prefs.edit()
prefs.all.keys.filterNot { it.startsWith("${BuildConfig.VERSION_CODE}:") }.forEach { edit.remove(it) }
prefs.all.keys.filterNot { it.startsWith("${BuildConfig.VERSION_CODE}:") || it == SEEDED }.forEach { edit.remove(it) }
edit.putInt(key, attempts + 1).putLong("$key@at", now).apply()
return true
}
}
fun seed(context: Context) {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
if (!prefs.getBoolean(SEEDED, false)) prefs.edit().putBoolean(SEEDED, true).apply()
}
}
@@ -0,0 +1,312 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.util.AtomicFile
import android.util.Log
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AutoComponents
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
object ComponentUpdater {
private const val TAG = "ComponentUpdater"
private const val CHECK_EVERY_MS = 3_600_000L
private const val BOOTED_KEPT = 200
private val lock = Any()
private val io = Any()
data class Status(val line: String, val current: String, val previous: String, val protons: List<String>, val note: String)
private fun file(context: Context) = File(File(context.filesDir, "components").apply { mkdirs() }, "updates.json")
private fun load(context: Context): JSONObject = synchronized(io) {
runCatching { JSONObject(String(AtomicFile(file(context)).readFully(), Charsets.UTF_8)) }.getOrDefault(JSONObject())
}
private fun save(context: Context, state: JSONObject) {
synchronized(io) {
val atomic = AtomicFile(file(context))
val output = runCatching { atomic.startWrite() }.onFailure { Log.w(TAG, "could not save", it) }.getOrNull() ?: return
try {
output.write(state.toString(1).toByteArray(Charsets.UTF_8))
atomic.finishWrite(output)
} catch (error: Exception) {
atomic.failWrite(output)
Log.w(TAG, "could not save", error)
}
}
}
private fun Map<String, Map<String, ComponentsManager.Choice>>.fileOf(p: ComponentsManager.Proton, comp: String): String? =
this[p.id]?.get(comp)?.takeIf { it.protonVersion == p.version }?.file
private class Target(val comp: String, val p: ComponentsManager.Proton, val line: ComponentUpdates.Line, val ls: JSONObject) {
val key: String get() = line.key
}
private fun JSONObject.obj(key: String): JSONObject = optJSONObject(key) ?: JSONObject().also { put(key, it) }
private fun JSONArray?.strings(): Set<String> = this?.let { a -> (0 until a.length()).map { a.optString(it) }.toSet() } ?: emptySet()
private fun JSONObject.strings(key: String): Set<String> = optJSONArray(key).strings()
private fun JSONObject?.ints(): Map<String, Int> = this?.keys()?.asSequence()?.associateWith { optInt(it) } ?: emptyMap()
private fun JSONObject?.texts(): Map<String, String> = this?.keys()?.asSequence()?.associateWith { optString(it) } ?: emptyMap()
fun settle(context: Context) {
val owned = load(context).optJSONObject("lines")?.let { lines -> lines.keys().asSequence().flatMap { lines.optJSONObject(it).strings("owned") }.toSet() } ?: emptySet()
val choices = ComponentsManager.activeChoices(context).values.flatMap { it.entries }
for (comp in ComponentsManager.COMPONENTS) {
if (SessionPrefs.componentModeChosen(context, comp)) continue
val manual = choices.any { (c, choice) -> c == comp && !choice.auto && choice.file !in owned && !choice.file.startsWith("original ") }
SessionPrefs.setComponentMode(context, comp, if (manual) ComponentUpdates.MANUAL else ComponentUpdates.AUTO)
}
}
private fun managed(context: Context, comp: String): Boolean =
SessionPrefs.componentMode(context, comp) == ComponentUpdates.AUTO && !(comp == "dxvk" && ComponentsManager.hardwareDxvk(context))
private fun logLines(context: Context): Sequence<String> {
val dir = ComponentsManager.steamLogs(context)
return sequenceOf("console_log.previous.txt", "console_log.txt").map { File(dir, it) }.filter { it.isFile }
.flatMap { f -> runCatching { f.readLines() }.getOrDefault(emptyList()).asSequence() }
}
private val STAMP = Regex("""^\[(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)]""")
private fun latestStamp(context: Context): String =
logLines(context).mapNotNull { STAMP.find(it)?.groupValues?.get(1) }.maxOrNull() ?: "0"
private fun lineOf(context: Context, state: JSONObject, p: ComponentsManager.Proton, comp: String): ComponentUpdates.Line? {
if (!ComponentsManager.supports(p, comp)) return null
if (comp == "fex") return ComponentUpdates.line("fex", false)
val key = "${p.id}|${p.version}"
val flavors = state.obj("flavors").obj(key)
val arm64ec = if (flavors.has(comp)) flavors.optBoolean(comp) else ComponentsManager.arm64ec(context, p, comp)?.also { flavors.put(comp, it) }
return arm64ec?.let { ComponentUpdates.line(comp, it) }
}
fun ensure(context: Context, force: Boolean): List<String> = synchronized(lock) {
if (SessionState.running) return emptyList()
settle(context)
val state = load(context)
val notes = ArrayList<String>()
val protons = runCatching { ComponentsManager.protons(context) }.getOrDefault(emptyList())
judge(context, state, protons, notes)
val due = force || System.currentTimeMillis() - state.optLong("checkedAt") >= CHECK_EVERY_MS
val wanted = ComponentsManager.COMPONENTS.filter { managed(context, it) }
if (wanted.isEmpty() || protons.isEmpty()) {
save(context, state)
return notes
}
try {
dropRemoved(state, protons)
val checked = due && check(context, state, protons, wanted, force, notes)
apply(context, state, protons, wanted, notes)
prune(context, state)
if (checked) state.put("checkedAt", System.currentTimeMillis())
} finally {
save(context, state)
}
notes
}
private fun check(
context: Context, state: JSONObject, protons: List<ComponentsManager.Proton>, wanted: List<String>, force: Boolean, notes: MutableList<String>,
): Boolean {
if (!AutoComponents.isOnline(context)) {
state.put("note", context.getString(R.string.comp_auto_waits_network))
return false
}
val catalog = runCatching { ComponentsManager.catalog(context, true).items }
.onFailure { Log.w(TAG, "catalog", it) }.getOrDefault(emptyList())
if (catalog.none { it.release == ComponentsManager.DD_NIGHTLY }) {
state.put("note", context.getString(R.string.comp_auto_check_failed))
return false
}
val holdBack = !force && AutoComponents.constrained(context)
val lines = state.obj("lines")
var complete = true
state.remove("note")
for (comp in wanted) for (p in protons) {
val line = lineOf(context, state, p, comp) ?: continue
val ls = lines.obj(line.key)
if (rollingBack(ls)) {
complete = false
continue
}
val target = ComponentUpdates.pick(catalog, line, ls.strings("bad"))
if (target == null || ls.optString("current") == target.file) continue
val stored = ComponentsManager.isStored(context, target.file)
if (!stored) {
if (holdBack) {
state.put("note", context.getString(R.string.comp_auto_waits_unmetered))
complete = false
continue
}
val got = runCatching { ComponentsManager.download(context, target) {} }
if (got.isFailure) {
Log.w(TAG, "download ${target.file}", got.exceptionOrNull())
state.put("note", context.getString(R.string.comp_auto_check_failed))
complete = false
continue
}
}
val stocks = protons.filter { lineOf(context, state, it, comp)?.key == line.key }.map { ComponentsManager.arm64x(context, it, comp) }
if (ComponentUpdates.needsArm64x(line, stocks) && !ComponentsManager.packageArm64x(context, target.file, comp)) {
Log.w(TAG, "${target.file} is not ARM64X like ${p.name}'s own ${line.key}; skipped")
ls.put("bad", JSONArray(ls.strings("bad") + target.file))
if (!stored) runCatching { ComponentsManager.deletePackage(context, target.file) }
continue
}
ls.put("previous", ls.optString("current").ifEmpty { ComponentUpdates.ORIGINAL })
.put("current", target.file).put("since", latestStamp(context)).put("failed", JSONObject())
if (!stored) ls.put("owned", JSONArray(ls.strings("owned") + target.file))
ls.remove("note")
notes += context.getString(R.string.comp_auto_updated, ComponentsManager.LABEL[comp], target.file.removeSuffix(".wcp"))
}
return complete
}
private fun apply(context: Context, state: JSONObject, protons: List<ComponentsManager.Proton>, wanted: List<String>, notes: MutableList<String>) {
val lines = state.obj("lines")
val targets = wanted.flatMap { comp ->
protons.mapNotNull { p -> lineOf(context, state, p, comp)?.let { line -> lines.optJSONObject(line.key)?.let { Target(comp, p, line, it) } } }
}
val choices = ComponentsManager.activeChoices(context)
for (t in targets) {
val from = t.ls.optJSONObject("restore")?.optString(t.p.id).orEmpty()
val current = t.ls.optString("current")
if (from.isNotEmpty()) {
if (choices.fileOf(t.p, t.comp) == from) runCatching { ComponentsManager.restore(context, t.p.id, t.comp, ComponentsManager.safeName(t.p.version)) }
.onFailure { Log.w(TAG, "restore ${t.p.name} ${t.key}", it) }
} else if (current.isNotEmpty() && choices.fileOf(t.p, t.comp) != current) {
if (ComponentUpdates.needsArm64x(t.line, listOf(ComponentsManager.arm64x(context, t.p, t.comp))) &&
!ComponentsManager.packageArm64x(context, current, t.comp)) continue
runCatching { ComponentsManager.swap(context, t.p.id, current) }.onFailure { Log.w(TAG, "${t.p.name} ${t.key}", it) }
}
}
val after = ComponentsManager.activeChoices(context)
val unfinished = HashSet<String>()
for (t in targets) {
val restore = t.ls.optJSONObject("restore")
val from = restore?.optString(t.p.id).orEmpty()
val current = t.ls.optString("current")
if (from.isNotEmpty()) {
if (after.fileOf(t.p, t.comp) == from) unfinished += t.key else restore?.remove(t.p.id)
} else if (current.isNotEmpty() && after.fileOf(t.p, t.comp) != current) {
unfinished += t.key
}
}
for (key in lines.keys().asSequence().toList()) {
val ls = lines.optJSONObject(key) ?: continue
val pending = ls.optString("pendingNote")
if (pending.isEmpty() || key in unfinished || (ls.optJSONObject("restore")?.length() ?: 0) > 0) continue
ls.remove("pendingNote")
ls.put("note", pending)
notes += pending
}
}
internal fun dropRemoved(state: JSONObject, protons: List<ComponentsManager.Proton>) {
val installed = protons.mapTo(HashSet()) { it.id }
val lines = state.optJSONObject("lines") ?: return
for (key in lines.keys().asSequence().toList()) {
val restore = lines.optJSONObject(key)?.optJSONObject("restore") ?: continue
for (id in restore.keys().asSequence().toList()) if (id !in installed) restore.remove(id)
}
}
internal fun rollingBack(ls: JSONObject): Boolean =
(ls.optJSONObject("restore")?.length() ?: 0) > 0 || ls.optString("pendingNote").isNotEmpty()
private fun judge(context: Context, state: JSONObject, protons: List<ComponentsManager.Proton>, notes: MutableList<String>) {
val mark = state.optString("logMark")
val runs = ComponentUpdates.launches(logLines(context), mark)
if (runs.isEmpty()) return
state.put("logMark", runs.maxOf { it.start })
val byTool = protons.associateBy { it.dir.name }
val lines = state.obj("lines")
for (comp in ComponentsManager.COMPONENTS) {
val onLine = HashMap<String, MutableList<ComponentUpdates.Launch>>()
for (run in runs) {
val p = byTool[run.tool] ?: continue
if (ComponentsManager.gameComponents(context, run.app).containsKey(comp)) continue
val line = lineOf(context, state, p, comp) ?: continue
onLine.getOrPut(line.key) { ArrayList() } += run
}
for ((key, list) in onLine) {
val ls = lines.obj(key)
val verdict = ComponentUpdates.judge(ComponentUpdates.Trial(
ls.optString("current"), ls.optString("previous"), ls.optString("since"),
ls.optJSONObject("booted").texts(), ls.optJSONObject("failed").ints(),
), list)
ls.put("booted", JSONObject(verdict.booted.entries.toList().takeLast(BOOTED_KEPT).associate { it.key to it.value } as Map<*, *>))
ls.put("failed", JSONObject(verdict.failed as Map<*, *>))
if (verdict.rollBack && managed(context, comp)) rollBack(context, state, protons, comp, key, notes)
}
}
}
private fun rollBack(context: Context, state: JSONObject, protons: List<ComponentsManager.Proton>, comp: String, key: String, notes: MutableList<String>) {
val ls = state.obj("lines").obj(key)
val bad = ls.optString("current")
val back = ls.optString("previous")
val choices = ComponentsManager.activeChoices(context)
val targets = protons.filter { lineOf(context, state, it, comp)?.key == key && choices.fileOf(it, comp) == bad }
for (p in targets) {
runCatching {
if (back == ComponentUpdates.ORIGINAL) ComponentsManager.restore(context, p.id, comp, ComponentsManager.safeName(p.version))
else ComponentsManager.swap(context, p.id, back)
}.onFailure { Log.w(TAG, "roll back ${p.name} $key", it) }
}
val after = ComponentsManager.activeChoices(context)
val unfinished = targets.filter { after.fileOf(it, comp) == bad }
ls.put("bad", JSONArray(ls.strings("bad") + bad)).put("current", back).put("previous", ComponentUpdates.ORIGINAL)
.put("since", latestStamp(context)).put("failed", JSONObject())
if (back == ComponentUpdates.ORIGINAL) ls.obj("restore").let { restore -> unfinished.forEach { restore.put(it.id, bad) } }
val label = ComponentsManager.LABEL[comp]
val shown = back.ifEmpty { context.getString(R.string.comp_tag_original) }.removeSuffix(".wcp")
val note = context.getString(R.string.comp_auto_rolled_back, label, bad.removeSuffix(".wcp"), shown)
Log.w(TAG, note)
if (unfinished.isNotEmpty()) {
ls.put("pendingNote", note)
return
}
ls.remove("pendingNote")
ls.put("note", note)
notes += note
prune(context, state)
}
private fun prune(context: Context, state: JSONObject) {
val lines = state.obj("lines")
val selected = ComponentsManager.selectedPackages(context)
val keep = lines.keys().asSequence().flatMap { k ->
val ls = lines.optJSONObject(k) ?: return@flatMap emptySequence()
ComponentUpdates.keep(ls.optString("current"), ls.optString("previous"), selected).asSequence()
}.toSet()
for (k in lines.keys().asSequence().toList()) {
val ls = lines.optJSONObject(k) ?: continue
val owned = ls.strings("owned")
val gone = owned.filter { it !in keep && runCatching { ComponentsManager.deletePackage(context, it) }.isSuccess }
ls.put("owned", JSONArray(owned - gone.toSet()))
}
}
fun status(context: Context, comp: String): List<Status> {
val state = load(context)
val lines = state.optJSONObject("lines") ?: JSONObject()
val protons = runCatching { ComponentsManager.protons(context) }.getOrDefault(emptyList())
val byLine = protons.groupBy { lineOf(context, state, it, comp)?.key }
return ComponentUpdates.LINES.filter { it.comp == comp }.mapNotNull { line ->
val on = byLine[line.key].orEmpty()
val ls = lines.optJSONObject(line.key)
if (on.isEmpty() && ls == null) return@mapNotNull null
val note = ls?.optString("note").orEmpty().ifEmpty { state.optString("note") }
Status(line.key, ls?.optString("current").orEmpty(), ls?.optString("previous").orEmpty(), on.map { it.name }, note)
}
}
}
@@ -0,0 +1,127 @@
package com.droiddeck.launcher.session
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.text.SimpleDateFormat
import java.util.Locale
object ComponentUpdates {
const val AUTO = "auto"
const val MANUAL = "manual"
const val ORIGINAL = ""
const val BOOT_SECONDS = 30L
const val BOOTED_SECONDS = 60L
const val FAILED_BOOTS_BEFORE_ROLLBACK = 2
data class Line(val key: String, val comp: String, val prefix: String)
val LINES = listOf(
Line("dxvk", "dxvk", "DD-dxvk-"),
Line("dxvk-arm64ec", "dxvk", "DD-dxvk-arm64ec-"),
Line("vkd3d", "vkd3d", "DD-vkd3d-proton-"),
Line("vkd3d-arm64ec", "vkd3d", "DD-vkd3d-proton-arm64ec-"),
Line("fex", "fex", "DD-FEXCore-"),
)
fun line(comp: String, arm64ec: Boolean): Line = LINES.first {
it.comp == comp && (comp == "fex" || it.key.endsWith("-arm64ec") == arm64ec)
}
fun pick(items: List<ComponentsManager.CatalogItem>, line: Line, bad: Set<String>): ComponentsManager.CatalogItem? {
val newestBad = bad.filter { belongs(it, line) }.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a, b) }
return items.filter { it.release == ComponentsManager.DD_NIGHTLY && it.comp == line.comp && belongs(it.file, line) }
.filter { newestBad == null || ProtonExtras.compareVersions(it.file, newestBad) > 0 }
.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a.file, b.file) }
}
fun belongs(file: String, line: Line): Boolean =
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true
fun arm64ec(pe: ByteArray): Boolean? = runCatching {
val b = ByteBuffer.wrap(pe).order(ByteOrder.LITTLE_ENDIAN)
val header = b.getInt(0x3c)
if (b.getInt(header) != 0x4550) return null
val sections = b.getShort(header + 6).toInt() and 0xffff
val optionalSize = b.getShort(header + 20).toInt() and 0xffff
val optional = header + 24
if ((b.getShort(optional).toInt() and 0xffff) != 0x20b) return false
val loadConfigRva = b.getInt(optional + 112 + 10 * 8)
if (loadConfigRva == 0) return false
val table = optional + optionalSize
var offset = -1
for (i in 0 until sections) {
val s = table + i * 40
val size = b.getInt(s + 8)
val va = b.getInt(s + 12)
if (loadConfigRva >= va && loadConfigRva < va + maxOf(size, 1)) offset = b.getInt(s + 20) + loadConfigRva - va
}
if (offset < 0) return null
b.getInt(offset) >= 0xC8 + 8 && b.getLong(offset + 0xC8) != 0L
}.getOrNull()
fun arm64x(pe: ByteArray): Boolean = runCatching {
val b = ByteBuffer.wrap(pe).order(ByteOrder.LITTLE_ENDIAN)
val header = b.getInt(0x3c)
b.getInt(header) == 0x4550 && (b.getShort(header + 4).toInt() and 0xffff) == 0xaa64 && arm64ec(pe) == true
}.getOrDefault(false)
fun needsArm64x(line: Line, stocks: List<Boolean?>): Boolean =
line.key.endsWith("-arm64ec") && stocks.any { it != false }
data class Launch(val app: String, val tool: String, val start: String, val seconds: Long)
private val PROCESS = Regex("""^\[(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)] Game process (added|removed)\s*: AppID (\d+)(?: "(.*))?""")
private val TOOL = Regex("""compatibilitytools\.d/([^/'"]+)['"]?/|steamapps/common/([^/'"]+)['"]?/proton""")
fun launches(log: Sequence<String>, after: String): List<Launch> {
val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US)
val open = HashMap<String, Pair<String, String>>()
val out = ArrayList<Launch>()
for (line in log) {
val m = PROCESS.find(line) ?: continue
val (time, what, app) = m.destructured
if (time <= after) continue
if (what == "added") {
val tool = TOOL.find(m.groupValues[4])?.let { t -> t.groupValues[1].ifEmpty { t.groupValues[2] } } ?: continue
open[app] = time to tool
} else {
val (start, tool) = open.remove(app) ?: continue
val seconds = runCatching { (format.parse(time)!!.time - format.parse(start)!!.time) / 1000 }.getOrNull() ?: continue
out += Launch(app, tool, start, seconds)
}
}
return out
}
data class Trial(
val current: String,
val previous: String,
val since: String,
val booted: Map<String, String>,
val failed: Map<String, Int>,
)
data class Verdict(val booted: Map<String, String>, val failed: Map<String, Int>, val rollBack: Boolean)
fun judge(trial: Trial, runs: List<Launch>): Verdict {
val booted = trial.booted.toMutableMap()
val failed = trial.failed.toMutableMap()
var rollBack = false
for (run in runs) {
val build = if (trial.since.isNotEmpty() && run.start > trial.since) trial.current else trial.previous
if (run.seconds >= BOOTED_SECONDS) {
booted[run.app] = build
if (build == trial.current) failed.remove(run.app)
} else if (run.seconds < BOOT_SECONDS && build == trial.current && trial.current != trial.previous &&
booted[run.app] == trial.previous) {
val n = (failed[run.app] ?: 0) + 1
failed[run.app] = n
if (n >= FAILED_BOOTS_BEFORE_ROLLBACK) rollBack = true
}
}
return Verdict(booted, failed, rollBack)
}
fun keep(current: String, previous: String, selected: Set<String>): Set<String> =
(setOf(current, previous) + selected) - ORIGINAL
}
@@ -84,6 +84,7 @@ object ComponentsManager {
private fun root(context: Context) = LinuxRuntime.rootDir(context)
private fun steam(context: Context) = File(root(context), "root/.local/share/Steam")
fun steamLogs(context: Context) = File(steam(context), "logs")
private fun host(context: Context, guest: String) = File(root(context), guest.removePrefix("/"))
private fun dataDir(context: Context) = File(context.filesDir, "components").apply { mkdirs() }
private fun packagesDir(context: Context) = File(dataDir(context), "packages").apply { mkdirs() }
@@ -1031,6 +1032,78 @@ object ComponentsManager {
ForcedPackage(setOf(GpuInfo.Family.A6XX), "dxvk", "dxvk-2.7.1-linux.wcp", "Dxvk-Linux"),
)
private val ARM64EC_PROBE = mapOf("dxvk" to "d3d11.dll", "vkd3d" to "d3d12.dll")
fun arm64ec(context: Context, p: Proton, comp: String): Boolean? = stockProbe(context, p, comp)?.let(ComponentUpdates::arm64ec)
fun arm64x(context: Context, p: Proton, comp: String): Boolean? = stockProbe(context, p, comp)?.let(ComponentUpdates::arm64x)
fun packageArm64x(context: Context, file: String, comp: String): Boolean {
val rel = "${COMP_DIR[comp] ?: return false}/aarch64-windows/${ARM64EC_PROBE.getValue(comp)}"
val f = File(packagesDir(context), safeName(file)).takeIf { it.isFile } ?: return false
return runCatching { readWcpEntry(f, rel) }.getOrNull()?.let(ComponentUpdates::arm64x) == true
}
private fun readWcpEntry(f: File, rel: String): ByteArray? = readWcp(f) { tar ->
var found: ByteArray? = null
while (found == null) {
val e = tar.nextTarEntry ?: break
if (!e.isDirectory && normalize(e.name) == rel) found = tar.readBytes()
}
found
}
private fun stockProbe(context: Context, p: Proton, comp: String): ByteArray? {
val rel = "${COMP_DIR[comp] ?: return null}/aarch64-windows/${ARM64EC_PROBE.getValue(comp)}"
val original = synchronized(lock) {
val swapped = loadState(context).optJSONObject("active")?.optJSONObject(p.id)?.optJSONObject(comp)
?.let { liveSelection("active", it, p) } == true
if (!swapped) return File(p.dir, rel).takeIf { it.isFile }?.let { runCatching { it.readBytes() }.getOrNull() }
originalFile(context, p, comp).takeIf { it.isFile } ?: return null
}
return runCatching { readWcpEntry(original, rel) }.getOrNull()
}
fun supports(p: Proton, comp: String): Boolean =
if (comp == "fex") File(p.dir, FEX_FILES.first()).isFile else File(p.dir, "${COMP_DIR.getValue(comp)}/aarch64-windows").isDirectory
fun hardwareDxvk(context: Context): Boolean =
runtimeManaged(context, "dxvk") || FORCED_PACKAGES.any { it.comp == "dxvk" && it.matches(GpuInfo.detect()) } ||
(com.droiddeck.launcher.core.DeviceSupport.vkBridge(context) && !SessionPrefs.bridgeProtonDxvk(context) &&
bridgeDxvk(AppVulkan.detect(context)) != null)
data class Choice(val file: String, val auto: Boolean, val protonVersion: String)
fun activeChoices(context: Context): Map<String, Map<String, Choice>> = synchronized(lock) {
val active = loadState(context).optJSONObject("active") ?: return emptyMap()
active.keys().asSequence().toList().associateWith { pid ->
val comps = active.optJSONObject(pid) ?: JSONObject()
comps.keys().asSequence().toList().mapNotNull { c ->
comps.optJSONObject(c)?.let { c to Choice(it.optString("file"), it.optBoolean("auto"), it.optString("protonVersion")) }
}.toMap()
}
}
fun selectedPackages(context: Context): Set<String> = synchronized(lock) {
val state = loadState(context)
buildSet {
for (key in listOf("active", "queued")) {
val byProton = state.optJSONObject(key) ?: continue
for (pid in byProton.keys()) {
val comps = byProton.optJSONObject(pid) ?: continue
for (c in comps.keys()) comps.optJSONObject(c)?.optString("file")?.takeIf(String::isNotEmpty)?.let(::add)
}
}
val profiles = state.optJSONObject("profiles")
profiles?.keys()?.forEach { scope ->
val profile = profiles.optJSONObject(scope) ?: return@forEach
for (c in COMPONENTS) profile.optString(c).takeIf(String::isNotEmpty)?.let(::add)
}
}
}
fun isStored(context: Context, file: String): Boolean = File(packagesDir(context), safeName(file)).isFile
internal fun forcedPackageWanted(activeFile: String?, protonVersionMatches: Boolean): Boolean =
activeFile.isNullOrEmpty() || !protonVersionMatches
@@ -11,12 +11,4 @@ object PipPolicy {
height.toDouble() / width > 2.39 -> 100 to 239
else -> width to height
}
fun outputSize(width: Int, height: Int, outputWidth: Int, outputHeight: Int): Pair<Int, Int>? {
if (width <= 0 || height <= 0 || outputWidth <= 0 || outputHeight <= 0) return null
val scale = minOf(width.toFloat() / outputWidth, height.toFloat() / outputHeight)
val fittedWidth = ((outputWidth * scale).toInt() and 1.inv()).coerceAtLeast(2)
val fittedHeight = ((outputHeight * scale).toInt() and 1.inv()).coerceAtLeast(2)
return fittedWidth to fittedHeight
}
}
@@ -351,6 +351,8 @@ object SessionPrefs {
}
const val PC_KEYBOARD_SIZE_DEFAULT = 47
const val WOW_CHAT_VOICE = "voice"
const val WOW_CHAT_KEYBOARD = "keyboard"
val PC_KEYBOARD_SIZE_RANGE = 25..70
const val PC_KEYBOARD_OPACITY_DEFAULT = 100
val PC_KEYBOARD_OPACITY_RANGE = 30..100
@@ -362,6 +364,13 @@ object SessionPrefs {
prefs(context).edit().putInt("pcKeyboardSize", percent.coerceIn(PC_KEYBOARD_SIZE_RANGE)).apply()
}
fun wowChatInput(context: Context): String? =
prefs(context).getString("wowChatInput", null)?.takeIf { it == WOW_CHAT_VOICE || it == WOW_CHAT_KEYBOARD }
fun setWowChatInput(context: Context, mode: String?) {
prefs(context).edit().apply { if (mode == null) remove("wowChatInput") else putString("wowChatInput", mode) }.apply()
}
fun pcKeyboardOpacity(context: Context): Int =
prefs(context).getInt("pcKeyboardOpacity", PC_KEYBOARD_OPACITY_DEFAULT).takeIf { it in PC_KEYBOARD_OPACITY_RANGE } ?: PC_KEYBOARD_OPACITY_DEFAULT
@@ -499,6 +508,17 @@ object SessionPrefs {
prefs(context).edit().putString("gpuDriverMode", mode).apply()
}
fun componentMode(context: Context, comp: String): String =
prefs(context).getString("componentMode.$comp", ComponentUpdates.AUTO)
?.takeIf { it == ComponentUpdates.AUTO || it == ComponentUpdates.MANUAL } ?: ComponentUpdates.AUTO
fun componentModeChosen(context: Context, comp: String): Boolean = prefs(context).contains("componentMode.$comp")
fun setComponentMode(context: Context, comp: String, mode: String) {
require(mode == ComponentUpdates.AUTO || mode == ComponentUpdates.MANUAL)
prefs(context).edit().putString("componentMode.$comp", mode).commit()
}
fun settleGpuDriverMode(context: Context) {
val p = prefs(context)
if (p.contains("gpuDriverMode")) return
@@ -31,7 +31,7 @@ object SettingsReset {
)
internal val SESSION_PREFIXES = listOf(
"resolutionCap.", "displayResolution.", "customRes.", "hdr.", "fpsLimit.", "performanceMode.", "suspendPolicy.",
"resolutionCap.", "displayResolution.", "customRes.", "hdr.", "fpsLimit.", "performanceMode.", "suspendPolicy.", "componentMode.",
)
private val STEAM_TOUCH_KEYS = listOf("feedback", "autoFade", "gyro", "shake")
@@ -11,6 +11,7 @@ import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
@@ -110,7 +111,16 @@ internal class BottomScreenTextInput(private val fallback: TextInputService) : P
}
@Composable
internal fun TypingPanel(request: TypingRequest, onDone: () -> Unit) {
internal fun TypingPanel(
request: TypingRequest,
modifier: Modifier = Modifier.fillMaxSize(),
title: String = stringResource(R.string.dual_typing_title),
done: String = stringResource(R.string.dual_typing_done),
onCancel: (() -> Unit)? = null,
leading: (@Composable () -> Unit)? = null,
showKeyboard: Boolean = true,
onDone: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
var field by remember(request) { mutableStateOf(request.value) }
LaunchedEffect(request.value) {
@@ -120,19 +130,22 @@ internal fun TypingPanel(request: TypingRequest, onDone: () -> Unit) {
val keyboard = LocalSoftwareKeyboardController.current
LaunchedEffect(request) {
kotlinx.coroutines.delay(120)
if (!showKeyboard) return@LaunchedEffect
runCatching { focus.requestFocus() }
keyboard?.show()
}
val options = request.imeOptions
val secret = options.keyboardType == KeyboardType.Password || options.keyboardType == KeyboardType.NumberPassword
Column(
Modifier.fillMaxSize().background(colors.background).padding(horizontal = 20.dp, vertical = 14.dp),
modifier.background(colors.background).padding(horizontal = 20.dp, vertical = 14.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text(stringResource(R.string.dual_typing_title), fontSize = 15.sp, fontWeight = FontWeight.SemiBold,
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
leading?.invoke()
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold,
color = colors.onSurfaceVariant, modifier = Modifier.weight(1f))
Button(onClick = onDone, modifier = Modifier.testTag("dual-typing-done")) { Text(stringResource(R.string.dual_typing_done)) }
if (onCancel != null) OutlinedButton(onClick = onCancel, modifier = Modifier.testTag("dual-typing-cancel")) { Text(stringResource(R.string.common_cancel)) }
Button(onClick = onDone, modifier = Modifier.testTag("dual-typing-done")) { Text(done) }
}
OutlinedTextField(
value = field,
@@ -81,6 +81,8 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.ComponentUpdater
import com.droiddeck.launcher.session.ComponentUpdates
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.ComponentsManager.CatalogItem
import com.droiddeck.launcher.session.ComponentsManager.Snapshot
@@ -163,6 +165,11 @@ fun ComponentsPage(
protons: ProtonsState = ProtonsState(),
protonActions: ProtonsActions = ProtonsActions(),
protonOptions: @Composable () -> Unit = {},
compModes: Map<String, String> = emptyMap(),
compAuto: Map<String, List<ComponentUpdater.Status>> = emptyMap(),
compAutoHeld: Set<String> = emptySet(),
compAutoChecking: Boolean = false,
onCompMode: (String, String) -> Unit = { _, _ -> },
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
@@ -521,6 +528,8 @@ fun ComponentsPage(
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot).size)
}
}
val moded: (String) -> Boolean = { it in compModes && it !in compAutoHeld && !ComponentsManager.runtimeManaged(it, gpu.systemPowerVr) }
val automatic: (String) -> Boolean = { moded(it) && compModes[it] == ComponentUpdates.AUTO }
val installedRows: @Composable ColumnScope.(String, Boolean) -> Unit = { l, right ->
when (l) {
PROTON_TAB -> {
@@ -535,7 +544,7 @@ fun ComponentsPage(
(if (swaps > 0) stringResource(R.string.comp_swapped, v.proton.version, swaps) else stringResource(R.string.comp_all_original, v.proton.version))
.let { if (v.inUseByGame) stringResource(R.string.comp_game_running_suffix, it) else it },
v.proton.id == view?.proton?.id, removable = removable,
modifier = (if (i == 0) Modifier.focusRequester(firstRow) else Modifier).trackRow(key, rowsAt),
modifier = (if (i == 0 && !moded(l)) Modifier.focusRequester(firstRow) else Modifier).trackRow(key, rowsAt),
onSelect = { if (v.proton.id != view?.proton?.id) { onProton(v.proton.id); flyHome(key, PROTON_TAB) } },
onDelete = {
if (extra != null) ask(key, right, ctx.getString(R.string.proton_remove_title, v.proton.name), ctx.getString(R.string.proton_remove_body), ctx.getString(R.string.store_remove), true, v.proton.name) {
@@ -555,7 +564,7 @@ fun ComponentsPage(
val key = "row:$l:${item.file ?: item.protonVersion}"
ChoiceLine(
item.name, item.detail, item.selected, item.removable, tag = item.tag, enabled = !managedDxvk,
modifier = (if (i == 0 && !managedDxvk) Modifier.focusRequester(firstRow) else Modifier).trackRow(key, rowsAt),
modifier = (if (i == 0 && !managedDxvk && !moded(l)) Modifier.focusRequester(firstRow) else Modifier).trackRow(key, rowsAt),
onSelect = {
if (managedDxvk || item.selected || p == null) return@ChoiceLine
val waits = if (view.inUseByGame) ctx.getString(R.string.comp_waits_long) else ctx.getString(R.string.comp_applies_long)
@@ -680,15 +689,31 @@ fun ComponentsPage(
label = "layerRows",
) { k -> body(k) }
}
if (single) {
slide { k -> RowGroup(installedTitle(k)) { installedRows(k, false) } }
Spacer(Modifier.height(12.dp))
slide { k -> RowGroup(availableTitle(k)) { availableRows(k) } }
} else Row(horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.Top) {
Column(Modifier.weight(1f)) { slide { k -> RowGroup(installedTitle(k)) { installedRows(k, false) } } }
Column(Modifier.weight(1f)) { slide { k -> RowGroup(availableTitle(k)) { availableRows(k) } } }
if (moded(l)) slide { k ->
if (moded(k)) Column(verticalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.padding(bottom = 14.dp)) {
PanelHeading(stringResource(R.string.comp_mode_title))
ModeChoices(
listOf(
Triple(ComponentUpdates.AUTO, R.string.common_auto, R.string.comp_mode_auto_detail),
Triple(ComponentUpdates.MANUAL, R.string.drivers_manual, R.string.comp_mode_manual_detail),
),
if (automatic(k)) ComponentUpdates.AUTO else ComponentUpdates.MANUAL, single, firstRow,
onPick = { onCompMode(k, it) },
)
if (automatic(k)) AutoComponentBody(ComponentsManager.LABEL[k] ?: k, compAuto[k].orEmpty(), compAutoChecking)
}
}
if (!automatic(l)) {
if (single) {
slide { k -> RowGroup(installedTitle(k)) { installedRows(k, false) } }
Spacer(Modifier.height(12.dp))
slide { k -> RowGroup(availableTitle(k)) { availableRows(k) } }
} else Row(horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.Top) {
Column(Modifier.weight(1f)) { slide { k -> RowGroup(installedTitle(k)) { installedRows(k, false) } } }
Column(Modifier.weight(1f)) { slide { k -> RowGroup(availableTitle(k)) { availableRows(k) } } }
}
Box(Modifier.padding(top = 14.dp)) { slide { k -> actions(k) } }
}
Box(Modifier.padding(top = 14.dp)) { slide { k -> actions(k) } }
if (l == "fex") {
SettingsGroup(stringResource(R.string.fex_preset_title)) {
SettingsRow(stringResource(R.string.fex_preset_title), null) {
@@ -1078,6 +1103,25 @@ private fun RowGroup(title: String, content: @Composable ColumnScope.() -> Unit)
}
}
@Composable
private fun AutoComponentBody(label: String, lines: List<ComponentUpdater.Status>, checking: Boolean) {
val colors = MaterialTheme.colorScheme
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
PanelTitle(stringResource(R.string.comp_auto_title, label), stringResource(R.string.comp_auto_hint))
if (lines.isEmpty()) EmptyLine(stringResource(R.string.comp_auto_none))
for (line in lines) {
val previous = line.previous.removeSuffix(".wcp").ifEmpty { stringResource(R.string.comp_tag_original) }
val fallback = if (line.current.isEmpty()) null else stringResource(R.string.comp_auto_fallback, previous)
PanelRow(
line.current.removeSuffix(".wcp").ifEmpty { stringResource(if (checking) R.string.comp_auto_checking else R.string.comp_tag_original) },
listOfNotNull(line.protons.joinToString(", ").ifEmpty { null }, fallback).joinToString(" · "),
selected = true, onClick = null,
)
}
lines.map { it.note }.filter { it.isNotEmpty() }.distinct().forEach { Text(it, fontSize = 13.sp, color = colors.onSurfaceVariant) }
}
}
@Composable
private fun EmptyLine(text: String) {
Text(text, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp))
@@ -122,6 +122,7 @@ class FrontEndState(
val frameGen: FrameGen.Mode = FrameGen.Mode.OFF,
val lossless: Lossless.State = Lossless.State.NONE,
val shortcutPicker: Boolean = false,
val preparingGames: Set<String> = emptySet(),
val shortcutLibraryScanning: Boolean = false,
val gameSyncFolder: String? = null,
val pageKey: String? = null,
@@ -188,6 +189,7 @@ class FrontEndActions(
val onPlayDesktopUi: () -> Unit,
val onSteamUrl: (String) -> Unit = {},
val onSteamGame: (Library.SteamGame) -> Unit,
val onStoreGame: (com.droiddeck.launcher.stores.Store, String) -> Unit = { _, _ -> },
val onGameShortcut: (Library.SteamGame) -> Unit = {},
val onExportGameFile: (Library.SteamGame) -> Unit = {},
val onSyncGameFiles: () -> Unit = {},
@@ -56,6 +56,7 @@ import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.semantics.Role
@@ -150,6 +151,27 @@ internal fun Chip(t: String, ok: Boolean) {
@Composable
internal fun rememberHot(src: MutableInteractionSource): Boolean = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
@Composable
internal fun DialogToggleRow(label: String, checked: Boolean, onChange: (Boolean) -> Unit) {
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val flip = { onChange(!checked) }
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().clip(Shape12)
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
.border(if (hot) 2.dp else 1.dp, if (hot) pal.signal else pal.line, Shape12)
.hoverable(src)
.clickable(interactionSource = src, indication = null, role = Role.Switch, onClick = flip)
.controllerConfirm(onClick = flip)
.padding(start = 14.dp, end = 4.dp),
) {
Text(label, fontSize = 14.sp, color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.weight(1f))
ToggleSwitch(checked, label = label, modifier = Modifier.focusProperties { canFocus = false }) { onChange(it) }
}
}
@Composable
internal fun PrimaryButton(
text: String,
@@ -408,11 +408,13 @@ internal fun GameActions(
!cloud && (game != null || installed != null) -> {
val gone = storeKey?.let { StoresState.uninstalling[it] }
val xboxBusy = store == Store.XBOX && id != null && XboxContent.busy(id)
val preparing = (game?.launchKey ?: storeKey)?.let { it in s.preparingGames } == true
PrimaryButton(
stringResource(R.string.stores_play), enabled = !s.busy && gone == null && download == null && !xboxBusy && (store != Store.GOG || installed?.sidecar?.isInstalled != false),
stringResource(if (preparing) R.string.store_starting else R.string.stores_play),
enabled = !s.busy && !preparing && gone == null && download == null && !xboxBusy && (store != Store.GOG || installed?.sidecar?.isInstalled != false),
main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn,
) {
if (game != null) a.onSteamGame(game) else if (store != null && id != null) launchStoreGame(ctx, store, id, s, a)
if (game != null) a.onSteamGame(game) else if (store != null && id != null) launchStoreGame(store, id, s, a)
}
if (game != null) {
if (compactMenu) GameMoreMenu(game, a) else {
@@ -250,18 +250,8 @@ internal fun GpuDriversBody(
Triple(GPU_MODE_PAIR, R.string.gpu_mode_pair, R.string.gpu_mode_pair_detail),
Triple(GPU_MODE_MIX, R.string.gpu_mode_mix, R.string.gpu_mode_mix_detail),
)
val choice: @Composable (Int, Modifier) -> Unit = { i, mod ->
val (id, title, detail) = modes[i]
PanelRow(
stringResource(title), stringResource(detail), gpu.mode == id,
modifier = mod.then(if (gpu.mode == id) Modifier.focusRequester(first) else Modifier)
.then(if (i == 0) Modifier.onGloballyPositioned { placed[1] = it }.onFocusChanged { if (it.isFocused) revealCard() } else Modifier),
onClick = { if (gpu.mode != id) actions.onMode(id) },
)
}
if (single) Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { modes.indices.forEach { choice(it, Modifier) } }
else Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min)) {
modes.indices.forEach { choice(it, Modifier.weight(1f).fillMaxHeight()) }
ModeChoices(modes, gpu.mode, single, first, onPick = actions.onMode) { i ->
if (i == 0) Modifier.onGloballyPositioned { placed[1] = it }.onFocusChanged { if (it.isFocused) revealCard() } else Modifier
}
when (gpu.mode) {
GPU_MODE_AUTO -> AutoBody(gpu, actions)
@@ -439,12 +429,35 @@ internal const val SLOT_DISPLAY = "panel"
internal const val SLOT_RUNTIME = "rt"
@Composable
private fun PanelHeading(text: String) {
internal fun ModeChoices(
modes: List<Triple<String, Int, Int>>,
selected: String,
single: Boolean,
first: FocusRequester,
onPick: (String) -> Unit,
extra: (Int) -> Modifier = { Modifier },
) {
val choice: @Composable (Int, Modifier) -> Unit = { i, mod ->
val (id, title, detail) = modes[i]
PanelRow(
stringResource(title), stringResource(detail), selected == id,
modifier = mod.then(if (selected == id) Modifier.focusRequester(first) else Modifier).then(extra(i)),
onClick = { if (selected != id) onPick(id) },
)
}
if (single) Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { modes.indices.forEach { choice(it, Modifier) } }
else Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min)) {
modes.indices.forEach { choice(it, Modifier.weight(1f).fillMaxHeight()) }
}
}
@Composable
internal fun PanelHeading(text: String) {
Text(text.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
@Composable
private fun PanelTitle(title: String, hint: String) {
internal fun PanelTitle(title: String, hint: String) {
Column(verticalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier.padding(top = 4.dp)) {
Text(title, fontSize = 18.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
Text(hint, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
@@ -461,7 +474,7 @@ private fun Pill(text: String, fill: Color, ink: Color) {
}
@Composable
private fun PanelRow(
internal fun PanelRow(
title: String,
detail: String,
selected: Boolean,
@@ -353,6 +353,11 @@ class InputSurfaceView(
private var touching = false
private var clicking = false
private var lastUp = 0L
private var downAt = 0L
private var downX = 0f
private var downY = 0f
private var travel = 0f
private val tapSlop = ViewConfiguration.get(context).scaledTouchSlop.toFloat()
private var originX = 0f
private var originY = 0f
private var knobX = 0f
@@ -379,6 +384,10 @@ class InputSurfaceView(
val r = reach().coerceAtLeast(1f)
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
downAt = event.eventTime
downX = event.x
downY = event.y
travel = 0f
originX = if (floating) event.x else width / 2f
originY = if (floating) event.y else height / 2f
touching = true
@@ -389,7 +398,9 @@ class InputSurfaceView(
MotionEvent.ACTION_MOVE -> follow(event.getX(0), event.getY(0), r)
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
touching = false
lastUp = if (clicking || event.actionMasked == MotionEvent.ACTION_CANCEL) 0L else event.eventTime
val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL || event.flags and MotionEvent.FLAG_CANCELED != 0
travel = maxOf(travel, hypot(event.x - downX, event.y - downY))
lastUp = if (!clicking && !cancelled && event.eventTime - downAt <= STICK_TAP_MS && travel <= tapSlop) event.eventTime else 0L
setClick(false)
move(0f, 0f, 1f)
}
@@ -398,6 +409,7 @@ class InputSurfaceView(
}
private fun follow(x: Float, y: Float, r: Float, force: Boolean = false) {
travel = maxOf(travel, hypot(x - downX, y - downY))
var dx = x - originX
var dy = y - originY
val length = hypot(dx, dy)
@@ -486,6 +498,7 @@ class InputSurfaceView(
companion object {
private const val CLICK_MS = 300L
private const val STICK_TAP_MS = 200L
private const val CORNER = 20f
@@ -43,6 +43,8 @@ class SecondScreenPresentation(
private val frame = FrameLayout(context)
private var menuView: androidx.compose.ui.platform.ComposeView? = null
private var dashboardView: androidx.compose.ui.platform.ComposeView? = null
private var chatView: androidx.compose.ui.platform.ComposeView? = null
private var chatLost: (() -> Unit)? = null
var menuShown = false
private set
private val root = LinearLayout(context).apply {
@@ -75,7 +77,7 @@ class SecondScreenPresentation(
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
root.setOnApplyWindowInsetsListener { view, insets ->
if (insets.isVisible(WindowInsets.Type.ime())) imeSeen = true
else if (imeSeen) keyboardClosed()
else if (imeSeen && chatView == null) keyboardClosed()
view.onApplyWindowInsets(insets)
}
}
@@ -126,6 +128,37 @@ class SecondScreenPresentation(
if (created && isShowing && currentMode == SecondScreenMode.TERMINAL && terminalPanel?.ready != true) renderMode()
}
fun showChat(onLost: () -> Unit, content: @androidx.compose.runtime.Composable () -> Unit) {
if (!showsKeyboard || chatView != null) return
keyboardHost?.takeIf { it.shown }?.hide()
keyboardShown.value = false
keyboardPending = false
fieldKeyboard = false
chatLost = onLost
ownComposeViews()
val view = androidx.compose.ui.platform.ComposeView(context).apply {
isFocusable = true
isFocusableInTouchMode = true
setContent { content() }
}
chatView = view
root.addView(view, 1.coerceAtMost(root.childCount), LinearLayout.LayoutParams(-1, -2))
}
fun hideChat() {
chatLost = null
dropChat()
}
private fun dropChat() {
val view = chatView ?: return
chatView = null
chatLost?.let { lost -> chatLost = null; sessionActivity.runOnUiThread(lost) }
imeSeen = false
root.removeView(view)
view.disposeComposition()
}
val showsKeyboard: Boolean get() = isShowing && !menuShown && currentMode == SecondScreenMode.CUSTOM_CONTROLS
val showsControls: Boolean get() = isShowing && currentMode != SecondScreenMode.NONE
@@ -176,6 +209,7 @@ class SecondScreenPresentation(
showMenu(false)
closeDashboard()
closeTerminal()
dropChat()
keyboardHost?.hide()
keyboardHost = null
dismiss()
@@ -219,6 +253,7 @@ class SecondScreenPresentation(
}
private fun renderMode() {
dropChat()
fieldKeyboard = false
keyboardHost?.hide()
keyboardHost = null
@@ -264,6 +264,9 @@ class DrawerActions(
val onImportLossless: () -> Unit,
val onKeyboard: () -> Unit,
val onHardwareKeyboard: () -> Unit,
val wowChatShown: Boolean = false,
val wowChat: String? = null,
val onWowChat: (String?) -> Unit = {},
val onSteamMenu: (() -> Unit)?,
val onQam: (() -> Unit)?,
val onAchievements: (() -> Unit)? = null,
@@ -675,6 +678,15 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
host.open = null; a.onKeyboard()
}
}
if (a.wowChatShown) ChoiceRow(
host, "wow-chat", stringResource(R.string.wow_chat_title), null,
listOf(
null to stringResource(R.string.wow_chat_ask),
SessionPrefs.WOW_CHAT_VOICE to stringResource(R.string.wow_chat_voice),
SessionPrefs.WOW_CHAT_KEYBOARD to stringResource(R.string.pckb_android),
),
a.wowChat, chipModifier = focus.track(page, "wow-chat"), onPick = a.onWowChat,
)
val keyboardContext = LocalContext.current
remember { PcKeyboardPrefs.load(keyboardContext) }
SliderRow(
@@ -1,14 +1,8 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Usb
@@ -18,12 +12,7 @@ import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.res.stringResource
@@ -48,23 +37,7 @@ internal fun SlowUsbDialog(drive: UsbLink.SlowDrive, never: Boolean, onNever: (B
stringResource(message, drive.name, UsbLink.generation(drive.mbps), speed, UsbLink.megabytesPerSecond(drive.mbps)),
fontSize = 13.sp, lineHeight = 18.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
)
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val flip = { onNever(!never) }
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().clip(Shape12)
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
.border(if (hot) 2.dp else 1.dp, if (hot) pal.signal else pal.line, Shape12)
.hoverable(src)
.clickable(interactionSource = src, indication = null, role = Role.Switch, onClick = flip)
.controllerConfirm(onClick = flip)
.padding(start = 14.dp, end = 4.dp),
) {
Text(stringResource(R.string.slow_usb_never), fontSize = 14.sp, color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.weight(1f))
ToggleSwitch(never, label = stringResource(R.string.slow_usb_never), modifier = Modifier.focusProperties { canFocus = false }) { onNever(it) }
}
DialogToggleRow(stringResource(R.string.slow_usb_never), never, onNever)
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
PrimaryButton(stringResource(R.string.slow_usb_dismiss), modifier = Modifier.focusRequester(focus), onClick = close)
}
@@ -221,7 +221,7 @@ private fun FinishedRow(d: DownloadEntry, s: FrontEndState, a: FrontEndActions,
ArtStrip(d.cover, d.name) {
StripLabel(d.name, d.store.id, stringResource(if (d.state == DownloadState.INSTALLED) R.string.stores_installed_chip else R.string.stores_dl_cancelled), Color.White.copy(alpha = 0.72f))
if (d.state == DownloadState.INSTALLED) Box(Modifier.bloomIn(bloom, GATHER_HOLD_MS + 150)) {
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else if (d.key == com.droiddeck.launcher.stores.battlenet.BattleNetClient.DOWNLOAD_KEY) a.onBattleNet() else launchStoreGame(ctx, d.store, d.id, s, a) }
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else if (d.key == com.droiddeck.launcher.stores.battlenet.BattleNetClient.DOWNLOAD_KEY) a.onBattleNet() else launchStoreGame(d.store, d.id, s, a) }
}
}
}
@@ -374,7 +374,7 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
CancelAction { DownloadQueue.clear(ctx, d.key) }
}
DownloadState.INSTALLED -> Box(Modifier.bloomIn(true, 420)) {
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else if (d.key == com.droiddeck.launcher.stores.battlenet.BattleNetClient.DOWNLOAD_KEY) a.onBattleNet() else launchStoreGame(ctx, d.store, d.id, s, a) }
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else if (d.key == com.droiddeck.launcher.stores.battlenet.BattleNetClient.DOWNLOAD_KEY) a.onBattleNet() else launchStoreGame(d.store, d.id, s, a) }
}
DownloadState.CANCELLED -> {}
}
@@ -1430,18 +1430,7 @@ internal fun openUrl(ctx: android.content.Context, url: String) {
runCatching { ctx.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) }
}
internal fun launchStoreGame(ctx: android.content.Context, store: Store, id: String, s: FrontEndState, a: FrontEndActions) {
internal fun launchStoreGame(store: Store, id: String, s: FrontEndState, a: FrontEndActions) {
val game = s.steamGames.firstOrNull { it.source == store.id && it.storeId == id }
if (game != null) {
a.onSteamGame(game)
return
}
val app = ctx.applicationContext
Thread({
val installed = runCatching { com.droiddeck.launcher.stores.StoreLaunch.installedGame(app, store, id) }.getOrNull()
StoresState.post {
if (installed == null) android.widget.Toast.makeText(ctx, R.string.stores_launch_not_registered, android.widget.Toast.LENGTH_LONG).show()
else a.onSteamGame(installed)
}
}, "store-play").start()
if (game != null) a.onSteamGame(game) else a.onStoreGame(store, id)
}
@@ -0,0 +1,230 @@
package com.droiddeck.launcher.ui
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material3.FilledIconToggleButton
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.ImeOptions
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
class WowChat(
private val context: Context,
private val onSend: (String, Boolean) -> Unit,
private val onCancel: () -> Unit,
private val readField: ((String?) -> Unit) -> Unit = {},
) {
var request by mutableStateOf<TypingRequest?>(null)
private set
var asking by mutableStateOf(false)
private set
var listening by mutableStateOf(false)
private set
var voice by mutableStateOf(false)
private set
var remembered by mutableStateOf(SessionPrefs.wowChatInput(context))
private set
private var recognizer: SpeechRecognizer? = null
private var spokenBase = ""
private var fieldRead = false
val open: Boolean get() = request != null || asking
fun chatOpened() {
if (open) return
when (val mode = remembered) {
null -> asking = true
else -> start(mode)
}
}
fun chatClosed() {
asking = false
finish()
}
fun pick(mode: String, remember: Boolean) {
asking = false
if (remember) choose(mode)
start(mode)
}
fun choose(mode: String?) {
SessionPrefs.setWowChatInput(context, mode)
remembered = SessionPrefs.wowChatInput(context)
}
fun dismissChoice() {
asking = false
onCancel()
}
fun send() {
val text = request?.value?.text.orEmpty()
val replace = fieldRead
finish()
onSend(text, replace)
}
fun cancel() {
finish()
onCancel()
}
private fun start(mode: String) {
voice = mode == SessionPrefs.WOW_CHAT_VOICE && voiceAvailable(context)
if (mode == SessionPrefs.WOW_CHAT_VOICE && !voice) Toast.makeText(context, R.string.wow_chat_voice_unavailable, Toast.LENGTH_SHORT).show()
val opened = TypingRequest(TextFieldValue(""), ImeOptions(singleLine = true, imeAction = ImeAction.Send), {}, {})
fieldRead = false
request = opened
readField { text ->
if (request === opened && !text.isNullOrEmpty() && opened.value.text.isEmpty()) {
fieldRead = true
opened.value = TextFieldValue(text, TextRange(text.length))
if (recognizer != null) spokenBase = "${text.trimEnd()} "
}
}
}
private fun finish() {
stopListening()
request = null
voice = false
}
fun listen() {
val active = request ?: return
stopListening()
val speech = runCatching { SpeechRecognizer.createSpeechRecognizer(context) }.getOrNull() ?: return
recognizer = speech
spokenBase = active.value.text.trimEnd().let { if (it.isEmpty()) it else "$it " }
speech.setRecognitionListener(object : RecognitionListener {
override fun onReadyForSpeech(params: Bundle?) { listening = true }
override fun onBeginningOfSpeech() {}
override fun onRmsChanged(rmsdB: Float) {}
override fun onBufferReceived(buffer: ByteArray?) {}
override fun onEndOfSpeech() {}
override fun onError(error: Int) { if (recognizer === speech) stopListening() }
override fun onResults(results: Bundle?) {
if (recognizer !== speech) return
heard(results)
stopListening()
}
override fun onPartialResults(partialResults: Bundle?) { if (recognizer === speech) heard(partialResults) }
override fun onEvent(eventType: Int, params: Bundle?) {}
})
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context.packageName)
runCatching { speech.startListening(intent) }.onFailure { stopListening() }
}
private fun heard(results: Bundle?) {
val spoken = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull()?.takeIf { it.isNotBlank() } ?: return
val text = spokenBase + spoken
request?.value = TextFieldValue(text, TextRange(text.length))
}
fun stopListening() {
listening = false
val speech = recognizer ?: return
recognizer = null
runCatching { speech.cancel() }
runCatching { speech.destroy() }
}
companion object {
private val PROGRAM = Regex("wow[\\w-]*\\.exe", RegexOption.IGNORE_CASE)
fun isWow(program: String?): Boolean = program != null && PROGRAM.matches(program)
fun voiceAvailable(context: Context): Boolean = SpeechRecognizer.isRecognitionAvailable(context)
}
}
@Composable
internal fun WowChatPanel(chat: WowChat, modifier: Modifier = Modifier.fillMaxWidth()) {
val request = chat.request ?: return
val context = LocalContext.current
val mic = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) chat.listen() else Toast.makeText(context, R.string.wow_chat_mic_denied, Toast.LENGTH_SHORT).show()
}
val listen = {
if (context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) chat.listen()
else mic.launch(Manifest.permission.RECORD_AUDIO)
}
LaunchedEffect(request) { if (chat.voice) listen() }
DisposableEffect(request) { onDispose { chat.stopListening() } }
BackHandler(onBack = chat::cancel)
TypingPanel(
request, modifier,
title = stringResource(if (chat.listening) R.string.wow_chat_listening else R.string.wow_chat_title),
done = stringResource(R.string.wow_chat_send),
onCancel = chat::cancel,
showKeyboard = !chat.voice,
leading = if (WowChat.voiceAvailable(context)) ({
FilledIconToggleButton(
checked = chat.listening,
onCheckedChange = { on -> if (on) listen() else chat.stopListening() },
modifier = Modifier.testTag("wow-chat-mic"),
) { Icon(Icons.Filled.Mic, stringResource(R.string.wow_chat_voice)) }
}) else null,
onDone = chat::send,
)
}
@Composable
internal fun WowChatChoiceDialog(chat: WowChat) {
var remember by remember { mutableStateOf(true) }
var picked by remember { mutableStateOf<String?>(null) }
val shown = rememberShown {
val mode = picked
if (mode != null) chat.pick(mode, remember) else chat.dismissChoice()
}
val close = { shown.targetState = false }
val choose = { mode: String -> picked = mode; close() }
val focus = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { focus.requestFocus() } }
AppDialog(shown, close, "wowChat", wide = false, maxWidth = 520.dp) {
DialogTitleRow(stringResource(R.string.wow_chat_title), close)
DialogToggleRow(stringResource(R.string.wow_chat_remember), remember) { remember = it }
Row(horizontalArrangement = Arrangement.spacedBy(10.dp, androidx.compose.ui.Alignment.End), modifier = Modifier.fillMaxWidth()) {
SecondaryButton(stringResource(R.string.pckb_android), modifier = Modifier.testTag("wow-chat-keyboard")) { choose(SessionPrefs.WOW_CHAT_KEYBOARD) }
PrimaryButton(stringResource(R.string.wow_chat_voice), icon = Icons.Filled.Mic,
modifier = Modifier.focusRequester(focus).testTag("wow-chat-voice")) { choose(SessionPrefs.WOW_CHAT_VOICE) }
}
}
}