android: put game review in the bottom bar

This commit is contained in:
vrubelroman 2026-11-28 14:31:28 +03:00
parent fd2fbd9b2a
commit a0051859db
16 changed files with 778 additions and 83 deletions

View file

@ -0,0 +1,19 @@
package io.github.vrubelroman.chesspenguin.ui
internal enum class ReviewAction { Start, Report, Wait }
/// The same availability the menu entry had, now used by the visible bottom-bar button.
internal fun reviewEnabled(
hasMoves: Boolean,
gameOn: Boolean,
sessionGame: Boolean,
loaded: Boolean,
hasData: Boolean,
running: Boolean,
): Boolean = hasMoves && !gameOn && (sessionGame || loaded) && (hasData || !running)
internal fun reviewAction(hasData: Boolean, running: Boolean): ReviewAction = when {
hasData -> ReviewAction.Report
running -> ReviewAction.Wait
else -> ReviewAction.Start
}

View file

@ -5,17 +5,17 @@ import android.content.res.Configuration
import android.content.Intent
import android.view.HapticFeedbackConstants
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.indication
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
@ -33,6 +33,7 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
import androidx.compose.material.icons.outlined.Memory
@ -44,11 +45,10 @@ import androidx.compose.material.icons.rounded.SmartToy
import androidx.compose.material.icons.rounded.VerticalAlignTop
import androidx.compose.material.icons.rounded.ChevronRight
import androidx.compose.material.icons.rounded.Download
import androidx.compose.material.icons.rounded.FirstPage
import androidx.compose.material.icons.rounded.LastPage
import androidx.compose.material.icons.rounded.Memory
import androidx.compose.material.icons.rounded.MoreVert
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.QueryStats
import androidx.compose.material.icons.rounded.SwapVert
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
@ -70,7 +70,6 @@ import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.ripple
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
@ -85,6 +84,7 @@ import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
@ -94,10 +94,14 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.CustomAccessibilityAction
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.customActions
import androidx.compose.ui.semantics.disabled
import androidx.compose.ui.semantics.onClick
import androidx.compose.ui.semantics.onLongClick
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
@ -119,7 +123,6 @@ import io.github.vrubelroman.chesspenguin.data.enginePosition
import io.github.vrubelroman.chesspenguin.theme.LocalChessColors
import io.github.vrubelroman.chesspenguin.theme.Tabular
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@ -430,6 +433,24 @@ fun GameScreen(
val reviewMarks = remember(rs) { rs?.moves?.associate { it.node.toInt() to it.judgement } ?: emptyMap() }
val currentMark = if (reviewShown) rs.moves.firstOrNull { it.node.toInt() == current } else null
// The one visible entry to the report: start it, or bring its panel back and open it.
fun openReview() {
reviewHidden = false
val e = edit
if ((newGame || playGame) && e != null && rs == null) {
scope.launch {
review.openSession("${held.key}/${System.nanoTime()}", e)
reviewStart = true
}
return
}
when (reviewAction(rs?.hasData == true, rs?.running == true)) {
ReviewAction.Report -> reviewReport = true
ReviewAction.Wait -> {}
ReviewAction.Start -> reviewStart = true
}
}
fun buzz(edge: Boolean) {
if (prefs.vibration) view.performHapticFeedback(if (edge) HapticFeedbackConstants.CONFIRM else HapticFeedbackConstants.CLOCK_TICK)
}
@ -783,6 +804,13 @@ fun GameScreen(
fun forward() {
if (preview != null) stepPreview(1) else node?.children?.firstOrNull()?.let { go(it.toInt()) }
}
fun start() {
preview?.let {
preview = it.copy(step = 0)
return
}
go(0)
}
fun end() {
preview?.let {
preview = it.copy(step = it.line.steps.size - 1)
@ -856,24 +884,62 @@ fun GameScreen(
}
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
Surface(color = MaterialTheme.colorScheme.surfaceContainer) {
Row(
Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp),
verticalAlignment = Alignment.CenterVertically,
) {
EngineButton(
on = engineOn,
needsDownload = !engineReady && !files.builtIn,
loading = netState as? NetState.Loading,
modifier = Modifier.weight(1.2f),
onClick = ::toggleEngine,
)
BarButton(Icons.Rounded.SwapVert, stringResource(R.string.flip), true, Modifier.weight(1f)) { flipped = !flipped }
BarButton(Icons.Rounded.FirstPage, stringResource(R.string.to_start), canBack, Modifier.weight(1f)) {
if (preview != null) preview = null else go(0)
BoxWithConstraints(Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp)) {
val compact = maxWidth < 320.dp
val narrow = maxWidth < 360.dp
val engineSlot = if (compact) 52f else if (narrow) 56f else 60f
val reviewSlot = if (compact) 52f else if (narrow) 88f else 96f
val moveSlot = if (compact || narrow) 64f else 78f
Row(Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) {
EngineButton(
on = engineOn,
needsDownload = !engineReady && !files.builtIn,
loading = netState as? NetState.Loading,
modifier = Modifier.weight(engineSlot),
onClick = ::toggleEngine,
)
BarButton(Icons.Rounded.SwapVert, stringResource(R.string.flip), true, Modifier.weight(48f)) { flipped = !flipped }
BarButton(
icon = Icons.Rounded.PlayArrow,
label = stringResource(R.string.move_back),
description = stringResource(R.string.move_back),
enabled = canBack,
modifier = Modifier.weight(moveSlot),
iconSize = 32,
mirrored = true,
onLongClickLabel = stringResource(R.string.to_start),
onLongClick = ::start,
onClick = ::back,
)
BarButton(
icon = Icons.Rounded.PlayArrow,
label = stringResource(R.string.move_forward),
description = stringResource(R.string.move_forward),
enabled = canForward,
modifier = Modifier.weight(moveSlot),
iconSize = 32,
onLongClickLabel = stringResource(R.string.to_end),
onLongClick = ::end,
onClick = ::forward,
)
ReviewButton(
report = rs?.hasData == true,
enabled = reviewEnabled(
hasMoves = hasMoves,
gameOn = gameOn,
sessionGame = newGame || playGame,
loaded = rs != null,
hasData = rs?.hasData == true,
running = rs?.running == true,
) && !preparingReview,
preparing = preparingReview,
progress = if (rs?.running == true) rs.done.toInt() to rs.total.toInt() else null,
showLabel = !compact,
modifier = Modifier.weight(reviewSlot),
onClick = ::openReview,
)
}
BarButton(Icons.Rounded.PlayArrow, stringResource(R.string.move_back), canBack, Modifier.weight(1.5f), 32, repeat = true, mirrored = true) { back() }
BarButton(Icons.Rounded.PlayArrow, stringResource(R.string.move_forward), canForward, Modifier.weight(1.5f), 32, repeat = true) { forward() }
BarButton(Icons.Rounded.LastPage, stringResource(R.string.to_end), canForward, Modifier.weight(1f)) { end() }
}
}
}
@ -907,6 +973,7 @@ fun GameScreen(
if (f != null && t != null) {
add(BoardArrow(f, t, EngineArrow.copy(alpha = if (i == 0) 0.63f else 0.35f), if (i == 0) 1f else 0.7f))
}
}
}
}
@ -1176,28 +1243,6 @@ fun GameScreen(
undo()
})
}
DropdownMenuItem(
text = { Text(stringResource(if (rs?.hasData == true) R.string.review_report_menu else R.string.review_menu)) },
// During the first analysis the panel already shows its progress (§21.1).
enabled = hasMoves && !gameOn && ((newGame || playGame) || (rs != null && (rs.hasData || !rs.running))),
onClick = {
menu = false
reviewHidden = false
val e = edit
if ((newGame || playGame) && e != null && rs == null) {
scope.launch {
review.openSession("${held.key}/${System.nanoTime()}", e)
reviewStart = true
}
return@DropdownMenuItem
}
when {
rs?.hasData == true -> reviewReport = true
rs?.running == true -> {}
else -> reviewStart = true
}
},
)
DropdownMenuItem(text = { Text(stringResource(R.string.game_info)) }, enabled = g != null, onClick = {
menu = false
info = true
@ -1617,6 +1662,92 @@ private fun EngineButton(on: Boolean, needsDownload: Boolean, loading: NetState.
}
}
/// The visible entry to whole-game analysis. The invitation uses the report's «!!»
/// teal; a finished report drops the fill. Progress and stopping stay in `ReviewPanel`.
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun ReviewButton(
report: Boolean,
enabled: Boolean,
modifier: Modifier,
preparing: Boolean = false,
progress: Pair<Int, Int>? = null,
showLabel: Boolean = true,
onClick: () -> Unit,
) {
val label = when {
progress != null && !report -> "${progress.first}/${progress.second}"
report -> stringResource(R.string.review_report)
else -> stringResource(R.string.play_analyse_short)
}
val description = stringResource(if (report) R.string.review_report_menu else R.string.review_menu)
val spokenState = when {
preparing -> stringResource(R.string.preparing_engine)
progress != null -> stringResource(R.string.review_progress, progress.first, progress.second)
else -> null
}
val action by rememberUpdatedState(onClick)
val dark = LocalChessColors.current.dark
val accent = nagColor(3, dark) ?: LocalContentColor.current
val disabled = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
val filled = enabled && !report && !preparing && progress == null
val iconColor = when {
!enabled -> disabled
filled && dark -> Color(0xFF1B1B1B)
filled -> Color.White
else -> accent
}
Column(
modifier
.fillMaxHeight()
.clearAndSetSemantics {
contentDescription = description
role = Role.Button
if (enabled) onClick(description) { action(); true } else disabled()
spokenState?.let { stateDescription = it }
}
.combinedClickable(
enabled = enabled,
onClickLabel = description,
role = Role.Button,
hapticFeedbackEnabled = false,
onClick = action,
),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Box(
Modifier.size(36.dp).clip(RoundedCornerShape(10.dp)).background(if (filled) accent else Color.Transparent),
contentAlignment = Alignment.Center,
) {
Icon(Icons.Rounded.QueryStats, null, tint = iconColor)
when {
progress != null -> CircularProgressIndicator(
progress = { progress.first.toFloat() / progress.second.coerceAtLeast(1) },
modifier = Modifier.size(34.dp),
color = if (enabled) accent else disabled,
strokeWidth = 2.dp,
)
preparing -> CircularProgressIndicator(
modifier = Modifier.size(34.dp),
color = if (enabled) accent else disabled,
strokeWidth = 2.dp,
)
}
}
if (showLabel) {
Text(
label,
style = MaterialTheme.typography.labelSmall.merge(Tabular),
color = if (enabled) MaterialTheme.colorScheme.onSurface else disabled,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
Box(Modifier.padding(top = 2.dp).width(24.dp).height(2.dp))
}
}
/// The row of continuations at a fork (§7.5): the line's own move first and filled.
@Composable
private fun Forks(moves: List<MoveNode>, san: (String) -> AnnotatedString, onMove: (Int) -> Unit) {
@ -1636,57 +1767,50 @@ private fun Forks(moves: List<MoveNode>, san: (String) -> AnnotatedString, onMov
}
}
/// A button of the bottom bar. With `repeat`, holding it steps again after 400 ms and
/// then every 120 ms (§7.4).
/// A button of the bottom bar. A tap is one action; an optional long press is a separate
/// action, never an auto-repeat. Long-press is also an accessibility custom action.
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun BarButton(
internal fun BarButton(
icon: ImageVector,
label: String,
enabled: Boolean,
modifier: Modifier,
iconSize: Int = 24,
repeat: Boolean = false,
mirrored: Boolean = false,
description: String = label,
onLongClickLabel: String? = null,
onLongClick: (() -> Unit)? = null,
onClick: () -> Unit,
) {
val action by rememberUpdatedState(onClick)
val on by rememberUpdatedState(enabled)
val interaction = remember { MutableInteractionSource() }
val color = if (enabled) LocalContentColor.current else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
val action by rememberUpdatedState(onClick)
val longAction by rememberUpdatedState(onLongClick)
Box(
modifier
.fillMaxHeight()
.semantics {
contentDescription = label
.clearAndSetSemantics {
contentDescription = description
role = Role.Button
if (!enabled) disabled()
onClick { action(); true }
}
.indication(interaction, ripple(bounded = false, radius = 32.dp))
.pointerInput(repeat) {
detectTapGestures(onPress = { at ->
if (!on) return@detectTapGestures
val press = PressInteraction.Press(at)
interaction.emit(press)
action()
coroutineScope {
val job = if (repeat) {
launch {
delay(400)
while (on) {
action()
delay(120)
}
}
} else {
null
}
tryAwaitRelease()
job?.cancel()
if (enabled) {
onClick(label) { action(); true }
if (onLongClickLabel != null && longAction != null) {
onLongClick(onLongClickLabel) { longAction?.invoke(); true }
customActions = listOf(CustomAccessibilityAction(onLongClickLabel) { longAction?.invoke(); true })
}
interaction.emit(PressInteraction.Release(press))
})
},
} else {
disabled()
}
}
.combinedClickable(
enabled = enabled,
onClickLabel = label,
role = Role.Button,
onLongClickLabel = onLongClickLabel,
onLongClick = onLongClick,
hapticFeedbackEnabled = false,
onClick = onClick,
),
contentAlignment = Alignment.Center,
) {
Icon(icon, null, tint = color, modifier = Modifier.size(iconSize.dp).then(if (mirrored) Modifier.scale(-1f, 1f) else Modifier))

View file

@ -36,6 +36,8 @@
<string name="to_start">Zum Anfang</string>
<string name="move_back">Zug zurück</string>
<string name="move_forward">Zug vor</string>
<string name="move_back_hint">Vorheriger Zug. Gedrückt halten: zum Anfang</string>
<string name="move_forward_hint">Nächster Zug. Gedrückt halten: zum Ende der Variante</string>
<string name="to_end">Zum Ende der Variante</string>
<string name="next_moves">Weiter:</string>
<string name="board_description">Brett, Stellung nach %1$s</string>

View file

@ -37,6 +37,8 @@
<string name="to_start">Al inicio</string>
<string name="move_back">Jugada atrás</string>
<string name="move_forward">Jugada adelante</string>
<string name="move_back_hint">Jugada anterior. Mantén pulsado para ir al inicio</string>
<string name="move_forward_hint">Jugada siguiente. Mantén pulsado para ir al final de la línea</string>
<string name="to_end">Al final de la línea</string>
<string name="next_moves">Siguiente:</string>
<string name="board_description">Tablero, posición tras %1$s</string>

View file

@ -37,6 +37,8 @@
<string name="to_start">Au début</string>
<string name="move_back">Coup précédent</string>
<string name="move_forward">Coup suivant</string>
<string name="move_back_hint">Coup précédent. Maintenez pour aller au début</string>
<string name="move_forward_hint">Coup suivant. Maintenez pour aller à la fin de la ligne</string>
<string name="to_end">À la fin de la ligne</string>
<string name="next_moves">Suite :</string>
<string name="board_description">Échiquier, position après %1$s</string>

View file

@ -37,6 +37,8 @@
<string name="to_start">All\'inizio</string>
<string name="move_back">Mossa indietro</string>
<string name="move_forward">Mossa avanti</string>
<string name="move_back_hint">Mossa precedente. Tieni premuto per andare all\'inizio</string>
<string name="move_forward_hint">Mossa successiva. Tieni premuto per andare alla fine della linea</string>
<string name="to_end">Alla fine della linea</string>
<string name="next_moves">Seguito:</string>
<string name="board_description">Scacchiera, posizione dopo %1$s</string>

View file

@ -36,6 +36,8 @@
<string name="to_start">Басына</string>
<string name="move_back">Бір жүріс артқа</string>
<string name="move_forward">Бір жүріс алға</string>
<string name="move_back_hint">Алдыңғы жүріс. Басына өту үшін басып тұрыңыз</string>
<string name="move_forward_hint">Келесі жүріс. Варианттың соңына өту үшін басып тұрыңыз</string>
<string name="to_end">Варианттың соңына</string>
<string name="next_moves">Келесі:</string>
<string name="board_description">Тақта, %1$s кейінгі позиция</string>

View file

@ -37,6 +37,8 @@
<string name="to_start">Ao início</string>
<string name="move_back">Voltar um lance</string>
<string name="move_forward">Avançar um lance</string>
<string name="move_back_hint">Lance anterior. Mantenha premido para ir ao início</string>
<string name="move_forward_hint">Lance seguinte. Mantenha premido para ir ao fim da linha</string>
<string name="to_end">Ao fim da linha</string>
<string name="next_moves">Próximo:</string>
<string name="board_description">Tabuleiro, posição após %1$s</string>

View file

@ -38,6 +38,8 @@
<string name="to_start">В начало</string>
<string name="move_back">Ход назад</string>
<string name="move_forward">Ход вперёд</string>
<string name="move_back_hint">Предыдущий ход. Удерживайте для перехода в начало</string>
<string name="move_forward_hint">Следующий ход. Удерживайте для перехода в конец линии</string>
<string name="to_end">В конец линии</string>
<string name="next_moves">Дальше:</string>
<string name="board_description">Доска, позиция после %1$s</string>

View file

@ -37,6 +37,8 @@
<string name="to_start">Boshiga</string>
<string name="move_back">Bir yurish orqaga</string>
<string name="move_forward">Bir yurish oldinga</string>
<string name="move_back_hint">Oldingi yurish. Boshiga oʻtish uchun bosib turing</string>
<string name="move_forward_hint">Keyingi yurish. Liniya oxiriga oʻtish uchun bosib turing</string>
<string name="to_end">Liniya oxiriga</string>
<string name="next_moves">Keyin:</string>
<string name="board_description">Taxta, %1$sdan keyingi pozitsiya</string>

View file

@ -37,6 +37,8 @@
<string name="to_start">To the start</string>
<string name="move_back">Move back</string>
<string name="move_forward">Move forward</string>
<string name="move_back_hint">Previous move. Hold for the first position</string>
<string name="move_forward_hint">Next move. Hold for the end of the line</string>
<string name="to_end">To the end of the line</string>
<string name="next_moves">Next:</string>
<string name="board_description">Board, position after %1$s</string>

View file

@ -0,0 +1,54 @@
package io.github.vrubelroman.chesspenguin.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class GameBarStateTest {
@Test
fun `loaded game can start or open its report`() {
assertTrue(enabled())
assertTrue(enabled(hasData = true, running = true))
}
@Test
fun `review is unavailable during computer play and without moves`() {
assertFalse(enabled(gameOn = true, sessionGame = true))
assertFalse(enabled(hasMoves = false))
}
@Test
fun `database game waits for its review state`() {
assertFalse(enabled(loaded = false))
assertTrue(enabled(sessionGame = true, loaded = false))
}
@Test
fun `first running database analysis disables duplicate start`() {
assertFalse(enabled(running = true))
}
@Test
fun `session game cannot duplicate its first run`() {
assertFalse(enabled(sessionGame = true, loaded = true, running = true))
assertEquals(ReviewAction.Wait, reviewAction(hasData = false, running = true))
}
@Test
fun `report wins over running while an empty run waits`() {
assertEquals(ReviewAction.Start, reviewAction(hasData = false, running = false))
assertEquals(ReviewAction.Wait, reviewAction(hasData = false, running = true))
assertEquals(ReviewAction.Report, reviewAction(hasData = true, running = false))
assertEquals(ReviewAction.Report, reviewAction(hasData = true, running = true))
}
private fun enabled(
hasMoves: Boolean = true,
gameOn: Boolean = false,
sessionGame: Boolean = false,
loaded: Boolean = true,
hasData: Boolean = false,
running: Boolean = false,
) = reviewEnabled(hasMoves, gameOn, sessionGame, loaded, hasData, running)
}