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

@@ -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) }
}
}
}