Android: game report — mistakes, blunders and accuracy, as on the desktop

The game analysis of the desktop (evaluations of the main line, judgements, accuracy,
cache and the engine job) moves into a shared crate, game-review, so both apps give the
same numbers. The desktop uses it unchanged in behaviour.

On Android, ⋮ → «Game analysis» runs Stockfish over the main line in its own process
(the live engine waits): an evaluation graph and a status row between the board and the
notation, marks in the notation, the better line of an error on the board, a report sheet
with both players side by side. Games with [%eval] and games analysed before show their
report at once. The analysis stops with the screen and goes on after it, also after the
phone is turned, and is cached as it goes.

Reviewed by an independent tester and designer (docs/design/android-ui.md §21, §22).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-23 14:10:58 +03:00
parent 7fcc75c7af
commit 1661e238d8
31 changed files with 3016 additions and 567 deletions

View file

@ -0,0 +1,128 @@
package io.github.vrubelroman.chesspenguin.data
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import uniffi.mobile_api.Database
import uniffi.mobile_api.GameReview
import uniffi.mobile_api.ReviewState
/// Nodes per position of the three qualities, as on the desktop (android-ui.md §21.2).
val REVIEW_NODES = listOf(250_000UL, 1_000_000UL, 3_000_000UL)
/// A first guess at the engine's speed per thread before it was measured on this phone.
const val GUESS_NPS_PER_THREAD = 250_000L
/// The analysis of the game on the screen (its report, android-ui.md §21): the cached
/// or PGN evaluations at once, the engine job when asked for. One game at a time; the
/// job has its own engine process (the Rust side runs it on a thread of its own).
class ReviewSession(private val cacheDir: String, private val scope: CoroutineScope) {
private val _state = MutableStateFlow<ReviewState?>(null)
/// The analysis of the game shown, `null` while it loads.
val state: StateFlow<ReviewState?> = _state.asStateFlow()
private val lock = Mutex()
private var review: GameReview? = null
private var game: Pair<String, UInt>? = null
private var poller: Job? = null
/// Bumped whenever another game comes: work for the old one is dropped.
@Volatile private var generation = 0
/// Shows the analysis of game `index` of database `db` (from the cache or its
/// `[%eval]` comments); the analysis of the game before is stopped and kept.
suspend fun open(db: String, database: Database, index: UInt) {
if (game == db to index) return
val gen = ++generation
_state.value = null
lock.withLock {
closeLocked()
val r = withContext(Dispatchers.IO) { runCatching { database.review(index, cacheDir) }.getOrNull() } ?: return
if (gen != generation) {
withContext(Dispatchers.IO) { r.close() }
return
}
review = r
game = db to index
_state.value = withContext(Dispatchers.IO) { r.state() }
}
}
/// Starts the engine on the positions without an evaluation, or on all when `full`.
/// `done` gets the final state when the job ends by itself.
fun start(path: String, evalFile: String, threads: Int, hashMb: Int, nodes: ULong, full: Boolean, done: (ReviewState) -> Unit) {
val gen = generation
scope.launch {
lock.withLock {
val r = review ?: return@withLock
if (gen != generation) return@withLock
val started = withContext(Dispatchers.IO) {
r.start(path, evalFile, threads.toUInt(), hashMb.toUInt(), nodes, full)
}
_state.value = withContext(Dispatchers.IO) { r.state() }
if (started) poll(r, gen, done)
}
}
}
/// Stops the engine; what it evaluated stays (and is cached).
fun cancel() {
poller?.cancel()
val gen = generation
scope.launch {
lock.withLock {
val r = review ?: return@withLock
withContext(Dispatchers.IO) { r.cancel() }
if (gen == generation) _state.value = withContext(Dispatchers.IO) { r.state() }
}
}
}
/// The screen went away: the job stops and the object is freed.
fun close() {
generation++
poller?.cancel()
scope.launch { lock.withLock { closeLocked() } }
}
private suspend fun closeLocked() {
poller?.cancel()
val r = review ?: return
review = null
game = null
withContext(Dispatchers.IO) {
r.cancel()
r.close()
}
}
/// While the job runs: its state a few times a second (the graph grows with it).
private fun poll(r: GameReview, gen: Int, done: (ReviewState) -> Unit) {
poller?.cancel()
poller = scope.launch(Dispatchers.IO) {
while (true) {
delay(POLL_MS)
val s = lock.withLock {
if (review !== r || gen != generation) null else r.state()
} ?: return@launch
_state.value = s
if (!s.running) {
done(s)
return@launch
}
}
}
}
private companion object {
const val POLL_MS = 300L
}
}

View file

@ -24,6 +24,11 @@ data class Prefs(
val engineSeconds: Int = 20,
val engineThreads: Int = defaultThreads(),
val engineHashMb: Int = 64,
/// The game report's quality, an index into REVIEW_NODES (§21.2).
val reviewQuality: Int = 1,
/// The engine's speed per thread measured by the last game analysis (0 = not yet),
/// for the time estimate.
val reviewNps: Long = 0,
)
/// Half the cores, at most 2: the engine leaves the phone's interface room (§9).
@ -58,6 +63,8 @@ class Settings(context: Context) {
engineSeconds = store.getInt("engineSeconds", d.engineSeconds),
engineThreads = store.getInt("engineThreads", d.engineThreads),
engineHashMb = store.getInt("engineHashMb", d.engineHashMb),
reviewQuality = store.getInt("reviewQuality", d.reviewQuality).coerceIn(0, REVIEW_NODES.size - 1),
reviewNps = store.getLong("reviewNps", d.reviewNps),
)
}
@ -76,6 +83,8 @@ class Settings(context: Context) {
.putInt("engineSeconds", p.engineSeconds)
.putInt("engineThreads", p.engineThreads)
.putInt("engineHashMb", p.engineHashMb)
.putInt("reviewQuality", p.reviewQuality)
.putLong("reviewNps", p.reviewNps)
.apply()
}
}

View file

@ -61,7 +61,8 @@ fun whiteShare(line: EngineLine?): Float {
}
/// The engine's row between the board and the notation (android-ui.md §8.2): the
/// evaluation, the depth, the best line; ▾ shows more lines.
/// evaluation, the depth, the best line; ▾ shows more lines. While the game is being
/// analysed (`waiting`, §21.6) the engine rests and the row says so.
@Composable
fun EngineStrip(
ending: String?,
@ -75,6 +76,7 @@ fun EngineStrip(
onDeeper: () -> Unit,
onRestart: () -> Unit,
notation: (String) -> AnnotatedString,
waiting: Boolean = false,
) {
val best = analysis?.lines?.firstOrNull()
val share by animateFloatAsState(whiteShare(best), tween(300), label = "eval")
@ -94,6 +96,16 @@ fun EngineStrip(
}
return@Column
}
if (waiting) {
Row(Modifier.fillMaxWidth().height(48.dp).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
Text(
stringResource(R.string.review_engine_paused),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
return@Column
}
if (status is EngineStatus.Failed) {
Row(Modifier.fillMaxWidth().height(48.dp).padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Text(
@ -211,9 +223,10 @@ fun shownEval(line: EngineLine): String {
return "$sign${a / 10}.${a % 10}"
}
/// The bar above the notation while an engine line is shown on the board (§8.3).
/// The bar above the notation while an engine line is shown on the board (§8.3); `best`
/// for the better line of a game report's error (§21.1).
@Composable
fun PreviewBar(step: Int, total: Int, onClose: () -> Unit) {
fun PreviewBar(step: Int, total: Int, onClose: () -> Unit, best: Boolean = false) {
Row(
Modifier
.fillMaxWidth()
@ -223,7 +236,7 @@ fun PreviewBar(step: Int, total: Int, onClose: () -> Unit) {
verticalAlignment = Alignment.CenterVertically,
) {
Text(
stringResource(R.string.engine_line_preview, step, total),
stringResource(if (best) R.string.review_best_preview else R.string.engine_line_preview, step, total),
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.weight(1f),

View file

@ -17,6 +17,11 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
@ -96,7 +101,10 @@ import androidx.lifecycle.compose.LocalLifecycleOwner
import io.github.vrubelroman.chesspenguin.R
import io.github.vrubelroman.chesspenguin.data.EngineSession
import io.github.vrubelroman.chesspenguin.data.NetState
import io.github.vrubelroman.chesspenguin.data.REVIEW_NODES
import io.github.vrubelroman.chesspenguin.data.ReviewSession
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
@ -105,10 +113,12 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import uniffi.mobile_api.EngineLine
import uniffi.mobile_api.GameData
import uniffi.mobile_api.MoveJudgement
import uniffi.mobile_api.MoveNode
/// An engine line shown on the board (§8.3): the game itself does not change.
private data class Preview(val line: EngineLine, val step: Int)
/// An engine line shown on the board (§8.3): the game itself does not change. `best`:
/// the better line of an error of the game report (§21.1).
private data class Preview(val line: EngineLine, val step: Int, val best: Boolean = false)
/// One game: the board on top, the notation under it, the move buttons at the bottom
/// under the thumb; ‹ › page the games of the list (android-ui.md §7).
@ -125,6 +135,8 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
var current by rememberSaveable(place) { mutableIntStateOf(0) }
var flipped by rememberSaveable { mutableStateOf(false) }
var preview by remember { mutableStateOf<Preview?>(null) }
// The game report (§21): its own engine job; the live engine rests while it runs.
val review = remember { ReviewSession(java.io.File(context.cacheDir, "analysis").path, app.scope) }
LaunchedEffect(db, place) {
preview = null
val database = app.library.database(db).getOrNull()
@ -142,6 +154,7 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
val loaded = withContext(Dispatchers.Default) { runCatching { database.game(index) } }
failed = loaded.isFailure
game = loaded.getOrNull()
if (game != null) review.open(db, database, index)
}
val pieces = remember { Pieces(context) }
val snackbar = remember { SnackbarHostState() }
@ -172,6 +185,19 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
var engineVisit by rememberSaveable { mutableStateOf<String?>(null) }
val engineWanted = engineVisit == app.visit
var expanded by rememberSaveable { mutableStateOf(false) }
val reviewState by review.state.collectAsState()
// "Hide" in the report: until the next game.
var reviewHidden by remember(place) { mutableStateOf(false) }
var reviewStart by remember { mutableStateOf(false) }
var reviewReport by remember { mutableStateOf(false) }
// A start that waits for the engine (downloaded or unpacked): full or not.
var wantReview by remember { mutableStateOf<Boolean?>(null) }
// The download sheet was opened to analyse the game (not for the engine button).
var sheetForReview by remember { mutableStateOf<Boolean?>(null) }
// Stopped because the app went to the background: goes on when it comes back.
// Kept when the phone is turned (the screen is made again): the analysis goes on.
var reviewResume by rememberSaveable(place) { mutableStateOf(false) }
val reviewCycle = remember(place) { HashMap<Pair<Boolean, MoveJudgement>, Int>() }
var menu by remember { mutableStateOf(false) }
var info by remember { mutableStateOf(false) }
@Suppress("DEPRECATION")
@ -224,10 +250,12 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
else -> null
}
LaunchedEffect(position, engineOn, visible, prefs.engineLines, prefs.engineSeconds) {
val reviewRunning = reviewState?.running == true
LaunchedEffect(position, engineOn, visible, prefs.engineLines, prefs.engineSeconds, reviewRunning) {
if (position == null || !visible) return@LaunchedEffect
when {
!engineOn -> session.shutdown()
// One engine at a time on a phone: the analysis of the game comes first (§21.6).
!engineOn || reviewRunning -> session.shutdown()
ending != null -> session.pause()
else -> session.show(position, prefs)
}
@ -242,6 +270,67 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
}
}
fun startReview(full: Boolean) {
if (files.state.value != NetState.Ready) {
if (files.builtIn) {
wantReview = full
files.prepare()
} else {
sheetForReview = full
sheet = true
}
return
}
wantReview = null
reviewHidden = false
val p = app.settings.prefs.value
review.start(files.executable, files.net.path, p.engineThreads, p.engineHashMb, REVIEW_NODES[p.reviewQuality], full) { s ->
if (s.npsPerThread > 0UL) app.settings.update { it.copy(reviewNps = s.npsPerThread.toLong()) }
}
}
// The engine became ready for an analysis that was asked for.
LaunchedEffect(netState) {
if (netState == NetState.Ready) wantReview?.let { full ->
sheet = false
startReview(full)
}
}
// An analysis stopped by the background or a turn of the phone goes on once this
// game's analysis is loaded again and the screen is visible.
val reviewLoaded = reviewState != null
LaunchedEffect(reviewLoaded, visible) {
if (reviewLoaded && visible && reviewResume) {
reviewResume = false
startReview(false)
}
}
DisposableEffect(lifecycle) {
val observer = LifecycleEventObserver { _, e ->
when (e) {
// Battery first (§21.6): the analysis stops with the screen and goes on after.
Lifecycle.Event.ON_STOP -> if (review.state.value?.running == true) {
reviewResume = true
review.cancel()
}
else -> {}
}
}
lifecycle.addObserver(observer)
onDispose {
lifecycle.removeObserver(observer)
review.close()
}
}
val rs = reviewState
val preparingReview = wantReview != null && files.builtIn && netState is NetState.Loading
// A game without moves has nothing to analyse.
val hasMoves = g?.nodes?.firstOrNull()?.children?.isNotEmpty() == true
val reviewShown = rs != null && hasMoves && !reviewHidden && (rs.hasData || rs.running || preparingReview)
val reviewPoints = remember(rs) { rs?.points?.withIndex()?.associate { it.value.node.toInt() to it.index } ?: emptyMap() }
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
fun buzz(edge: Boolean) {
if (prefs.vibration) view.performHapticFeedback(if (edge) HapticFeedbackConstants.CONFIRM else HapticFeedbackConstants.CLOCK_TICK)
}
@ -289,7 +378,10 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
wantEngine = true
files.prepare()
}
else -> sheet = true
else -> {
sheetForReview = null
sheet = true
}
}
}
BackHandler(preview != null) { preview = null }
@ -326,6 +418,7 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
}
}
val board: @Composable (Modifier) -> Unit = { boardModifier ->
val dark = LocalChessColors.current.dark
val p = preview
val step = p?.let { it.line.steps[it.step] }
val fen = step?.fen ?: node?.fen ?: START
@ -339,6 +432,12 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
p.line.steps.getOrNull(p.step + 1)?.let { add(BoardArrow(it.fromSquare, it.toSquare, EngineArrow)) }
} else {
node?.marks?.forEach { m -> m.to?.let { add(BoardArrow(m.from, it, markColor(m.color), 0.9f)) } }
// After an error of the report: how the opponent punishes it (§21.1).
if (!engineOn) currentMark?.let { m ->
val f = m.replyFrom
val t = m.replyTo
if (f != null && t != null) add(BoardArrow(f, t, judgementColor(m.judgement, dark).copy(alpha = 0.8f), 0.9f))
}
if (engineOn && prefs.bestArrow) {
analysis()?.lines?.take(2)?.forEachIndexed { i, l ->
val f = l.fromSquare
@ -392,6 +491,7 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
position?.let { session.show(it, prefs) }
},
notation = line,
waiting = reviewRunning,
)
}
} else if (wantEngine && files.builtIn && netState is NetState.Loading) {
@ -400,10 +500,34 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
Text(stringResource(R.string.preparing_engine), Modifier.padding(start = 12.dp), color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
if (p != null) PreviewBar(p.step + 1, p.line.steps.size, onClose = { preview = null })
if (reviewShown) {
val cursor = g?.let { pointIndex(reviewPoints, it, current) }
ReviewPanel(
state = rs,
cursor = cursor,
// TalkBack: "6…Nf6, evaluation +1.2" (the start position has no move).
cursorLabel = cursor?.takeIf { it > 0 }?.let { rs.points[it].node.toInt() }?.let { id ->
nodes?.getOrNull(id)?.let { n -> (if (n.white) "${n.moveNumber}." else "${n.moveNumber}…") + n.san }
},
// A phone on its side has little height: with the engine strip on, only the row (§21.3).
showGraph = !(landscape && engineOn),
mark = currentMark,
preparing = preparingReview,
notation = line,
onIndex = { i -> rs.points.getOrNull(i)?.let { go(it.node.toInt()) } },
onBest = { m -> m.best?.takeIf { it.steps.isNotEmpty() }?.let { preview = Preview(it, 0, best = true) } },
onReport = { reviewReport = true },
onStop = { review.cancel() },
onResume = { startReview(false) },
)
}
if (p != null) PreviewBar(p.step + 1, p.line.steps.size, onClose = { preview = null }, best = p.best)
Box(Modifier.weight(1f).fillMaxWidth()) {
when {
g != null -> Notation(g, items, where, current, notation, san, onMove = ::go, modifier = Modifier.fillMaxSize())
g != null -> Notation(
g, items, where, current, notation, san, onMove = ::go, modifier = Modifier.fillMaxSize(),
marks = if (reviewShown) reviewMarks else emptyMap(),
)
failed -> Text(
stringResource(R.string.game_failed),
color = MaterialTheme.colorScheme.error,
@ -452,6 +576,20 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
Box {
IconButton(onClick = { menu = true }) { Icon(Icons.Rounded.MoreVert, stringResource(R.string.menu)) }
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
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 && rs != null && (rs.hasData || !rs.running),
onClick = {
menu = false
reviewHidden = false
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
@ -497,7 +635,8 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
) { padding ->
val inner = Modifier.fillMaxSize().padding(top = padding.calculateTopPadding(), bottom = padding.calculateBottomPadding())
if (landscape) {
Row(inner) {
// The navigation buttons stand on a side of the screen: nothing goes under them.
Row(inner.windowInsetsPadding(WindowInsets.navigationBars.only(WindowInsetsSides.Horizontal))) {
board(Modifier.fillMaxHeight())
Column(Modifier.weight(1f).fillMaxHeight()) {
side(Modifier.weight(1f))
@ -537,16 +676,65 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
state = netState,
metered = remember(sheet) { !files.builtIn && files.metered() },
onDownload = {
wantEngine = true
// Asked for by the analysis of the game: it starts when the engine is ready,
// the engine button stays as it is.
val forReview = sheetForReview
if (forReview != null) wantReview = forReview else wantEngine = true
files.prepare()
},
onCancel = {
files.cancel()
wantEngine = false
wantReview = null
sheetForReview = null
sheet = false
scope.launch { snackbar.showSnackbar(cancelledText) }
},
onDismiss = { sheet = false },
onDismiss = {
sheet = false
sheetForReview = null
},
)
}
if (reviewStart) {
ReviewStartSheet(
state = rs,
quality = prefs.reviewQuality,
threads = prefs.engineThreads,
npsPerThread = prefs.reviewNps,
onQuality = { q -> app.settings.update { it.copy(reviewQuality = q) } },
onStart = { full ->
reviewStart = false
startReview(full)
},
onDismiss = { reviewStart = false },
)
}
if (reviewReport && rs != null) {
val whiteName = tag("White").takeIf { it.isNotBlank() && it != "?" } ?: stringResource(R.string.tag_white)
val blackName = tag("Black").takeIf { it.isNotBlank() && it != "?" } ?: stringResource(R.string.tag_black)
ReviewSheet(
state = rs,
white = whiteName,
black = blackName,
onError = { w, j ->
reviewReport = false
val hits = rs.moves.filter { it.white == w && it.judgement == j }
if (hits.isNotEmpty()) {
val k = ((reviewCycle[w to j] ?: -1) + 1) % hits.size
reviewCycle[w to j] = k
go(hits[k].node.toInt())
}
},
onAgain = {
reviewReport = false
reviewStart = true
},
onHide = {
reviewReport = false
reviewHidden = true
},
onDismiss = { reviewReport = false },
)
}
}

View file

@ -48,6 +48,7 @@ import io.github.vrubelroman.chesspenguin.theme.ChessColors
import io.github.vrubelroman.chesspenguin.theme.LocalChessColors
import io.github.vrubelroman.chesspenguin.theme.nagColor
import uniffi.mobile_api.GameData
import uniffi.mobile_api.MoveJudgement
import uniffi.mobile_api.MoveNode
/// A piece of the notation: the main line as a table of moves, comments and variations
@ -201,7 +202,8 @@ private fun variationText(
}
/// The notation under the board (android-ui.md §7.3): the current move highlighted
/// and kept in view; a tap on a move goes there.
/// and kept in view; a tap on a move goes there. `marks` are the engine's judgements of
/// main-line moves (the game report, §21.4).
@Composable
fun Notation(
game: GameData,
@ -212,6 +214,7 @@ fun Notation(
san: (String) -> AnnotatedString,
onMove: (Int) -> Unit,
modifier: Modifier = Modifier,
marks: Map<Int, MoveJudgement> = emptyMap(),
) {
val chess = LocalChessColors.current
LaunchedEffect(current) {
@ -237,7 +240,7 @@ fun Notation(
.background(MaterialTheme.colorScheme.surfaceContainerLow)
.padding(horizontal = 12.dp, vertical = 8.dp),
)
is Item.Moves -> MovesRow(game, item, current, chess, san, onMove)
is Item.Moves -> MovesRow(game, item, current, chess, san, onMove, marks)
is Item.Variation -> Box(
Modifier
.fillMaxWidth()
@ -276,6 +279,7 @@ private fun MovesRow(
chess: ChessColors,
san: (String) -> AnnotatedString,
onMove: (Int) -> Unit,
marks: Map<Int, MoveJudgement>,
) {
Row(Modifier.fillMaxWidth().height(48.dp), verticalAlignment = Alignment.CenterVertically) {
Text(
@ -285,8 +289,8 @@ private fun MovesRow(
modifier = Modifier.width(40.dp).padding(end = 8.dp),
textAlign = androidx.compose.ui.text.style.TextAlign.End,
)
MoveCell(game, row.white, true, current, chess, san, onMove, Modifier.weight(1f))
MoveCell(game, row.black, false, current, chess, san, onMove, Modifier.weight(1f))
MoveCell(game, row.white, true, current, chess, san, onMove, Modifier.weight(1f), row.white?.let { marks[it] })
MoveCell(game, row.black, false, current, chess, san, onMove, Modifier.weight(1f), row.black?.let { marks[it] })
}
}
@ -300,12 +304,19 @@ private fun MoveCell(
san: (String) -> AnnotatedString,
onMove: (Int) -> Unit,
modifier: Modifier,
mark: MoveJudgement?,
) {
val selected = id != null && id == current
// TalkBack reads "4, White, dxe5", and whether it is the current move.
// The engine's mark is left out where the author already put the same sign ("Nf6? ?"
// reads as a typo, §21.4).
val mark = mark?.takeIf { m -> id == null || game.nodes[id].nags.none { it.toInt() == judgementNag(m) } }
// TalkBack reads "4, White, dxe5", the engine's judgement, and whether it is the
// current move.
val markName = mark?.let { judgementName(it) }
val spoken = id?.let {
val n = game.nodes[it]
stringResource(if (white) R.string.move_white else R.string.move_black, n.moveNumber.toInt(), n.san + n.nagSymbols)
stringResource(if (white) R.string.move_white else R.string.move_black, n.moveNumber.toInt(), n.san + n.nagSymbols) +
(markName?.let { m -> ", $m" } ?: "")
}
val currentLabel = stringResource(R.string.current_move)
// The whole cell takes the tap; the fill only hugs the move.
@ -334,26 +345,29 @@ private fun MoveCell(
if (white) Text("…", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 17.sp, modifier = Modifier.padding(horizontal = 8.dp))
} else {
val n = game.nodes[id]
Row(
Modifier
.clip(RoundedCornerShape(6.dp))
.background(if (selected) chess.currentMove else Color.Transparent)
.padding(horizontal = 8.dp, vertical = 6.dp),
horizontalArrangement = Arrangement.spacedBy(1.dp),
) {
Text(san(n.san), fontSize = 17.sp, fontWeight = FontWeight.Medium, color = MaterialTheme.colorScheme.onSurface)
if (n.nagSymbols.isNotEmpty()) {
Text(
n.nagSymbols,
fontSize = 17.sp,
fontWeight = FontWeight.Medium,
color = if (selected) {
MaterialTheme.colorScheme.onSurface
} else {
n.nags.firstOrNull()?.let { nagColor(it.toInt(), chess.dark) } ?: MaterialTheme.colorScheme.onSurfaceVariant
},
)
Row(verticalAlignment = Alignment.CenterVertically) {
Row(
Modifier
.clip(RoundedCornerShape(6.dp))
.background(if (selected) chess.currentMove else Color.Transparent)
.padding(horizontal = 8.dp, vertical = 6.dp),
horizontalArrangement = Arrangement.spacedBy(1.dp),
) {
Text(san(n.san), fontSize = 17.sp, fontWeight = FontWeight.Medium, color = MaterialTheme.colorScheme.onSurface)
if (n.nagSymbols.isNotEmpty()) {
Text(
n.nagSymbols,
fontSize = 17.sp,
fontWeight = FontWeight.Medium,
color = if (selected) {
MaterialTheme.colorScheme.onSurface
} else {
n.nags.firstOrNull()?.let { nagColor(it.toInt(), chess.dark) } ?: MaterialTheme.colorScheme.onSurfaceVariant
},
)
}
}
if (mark != null) ReviewBadge(mark, Modifier.padding(start = 2.dp))
}
}
}

View file

@ -0,0 +1,654 @@
package io.github.vrubelroman.chesspenguin.ui
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ChevronRight
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.clipRect
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import io.github.vrubelroman.chesspenguin.R
import io.github.vrubelroman.chesspenguin.data.GUESS_NPS_PER_THREAD
import io.github.vrubelroman.chesspenguin.data.REVIEW_NODES
import io.github.vrubelroman.chesspenguin.theme.LocalChessColors
import io.github.vrubelroman.chesspenguin.theme.Tabular
import io.github.vrubelroman.chesspenguin.theme.nagColor
import uniffi.mobile_api.GameData
import uniffi.mobile_api.MoveJudgement
import uniffi.mobile_api.ReviewMove
import uniffi.mobile_api.ReviewState
import uniffi.mobile_api.SideReview
import kotlin.math.ceil
import kotlin.math.roundToInt
/// The NAG of the same sign: $6 ?!, $2 ?, $4 ??.
fun judgementNag(j: MoveJudgement): Int = when (j) {
MoveJudgement.INACCURACY -> 6
MoveJudgement.MISTAKE -> 2
MoveJudgement.BLUNDER -> 4
}
/// The colors of the NAGs ?!, ? and ?? (§21.4).
fun judgementColor(j: MoveJudgement, dark: Boolean): Color = nagColor(judgementNag(j), dark) ?: Color.Unspecified
fun judgementSymbol(j: MoveJudgement): String = when (j) {
MoveJudgement.INACCURACY -> "?!"
MoveJudgement.MISTAKE -> "?"
MoveJudgement.BLUNDER -> "??"
}
@Composable
fun judgementName(j: MoveJudgement): String = stringResource(
when (j) {
MoveJudgement.INACCURACY -> R.string.review_inaccuracy
MoveJudgement.MISTAKE -> R.string.review_mistake
MoveJudgement.BLUNDER -> R.string.review_blunder
},
)
@Composable
private fun judgementPlural(j: MoveJudgement): String = stringResource(
when (j) {
MoveJudgement.INACCURACY -> R.string.review_inaccuracies
MoveJudgement.MISTAKE -> R.string.review_mistakes
MoveJudgement.BLUNDER -> R.string.review_blunders
},
)
/// The engine's mark after a main-line move in the notation (§21.4): a layer of its own,
/// apart from the author's NAGs.
@Composable
fun ReviewBadge(j: MoveJudgement, modifier: Modifier = Modifier) {
val c = judgementColor(j, LocalChessColors.current.dark)
Text(
judgementSymbol(j),
fontSize = 13.sp,
fontWeight = FontWeight.Bold,
color = c,
modifier = modifier
.clip(RoundedCornerShape(4.dp))
.background(c.copy(alpha = 0.16f))
.padding(horizontal = 4.dp, vertical = 1.dp),
)
}
/// The place in `state.points` of a node: itself on the main line, or the main-line move
/// its variation leaves from.
fun pointIndex(points: Map<Int, Int>, game: GameData, node: Int): Int? {
var n = node
while (true) {
points[n]?.let { return it }
n = game.nodes.getOrNull(n)?.parent?.toInt() ?: return null
}
}
/// "91%", or "—" when the accuracy is not known yet.
private fun percent(a: Double?): String = a?.let { "${it.roundToInt()}%" } ?: "—"
/// The analysis between the board and the notation (§21.3): what is going on or what the
/// current move was, and the evaluation graph.
@Composable
fun ReviewPanel(
state: ReviewState,
cursor: Int?,
mark: ReviewMove?,
preparing: Boolean,
notation: (String) -> AnnotatedString,
onIndex: (Int) -> Unit,
onBest: (ReviewMove) -> Unit,
onReport: () -> Unit,
onStop: () -> Unit,
onResume: () -> Unit,
cursorLabel: String? = null,
showGraph: Boolean = true,
) {
val dark = LocalChessColors.current.dark
Column(Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceContainerLow)) {
// 48 dp: every button here and the error row itself are touch targets (§21.3).
Row(
Modifier.fillMaxWidth().height(48.dp).padding(start = 16.dp, end = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
val textStyle = MaterialTheme.typography.bodyMedium
val report: @Composable () -> Unit = {
TextButton(onClick = onReport) { Text(stringResource(R.string.review_report)) }
}
when {
state.running -> {
Text(
stringResource(R.string.review_progress, state.done.toInt(), state.total.toInt()),
style = textStyle.merge(Tabular),
modifier = Modifier.weight(1f),
)
IconButton(onClick = onStop) { Icon(Icons.Rounded.Close, stringResource(R.string.review_stop)) }
}
preparing -> Text(
stringResource(R.string.preparing_engine),
style = textStyle,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.weight(1f),
)
mark != null -> {
val c = judgementColor(mark.judgement, dark)
val name = judgementName(mark.judgement)
val canShow = mark.best?.steps?.isNotEmpty() == true
// Without a line (evaluations from the PGN) the better move is not named.
val better = mark.bestLabel.takeIf { it.isNotEmpty() && canShow }?.let { notation(it) }
// The template around the move ("{move} was better", "лучше было {move}").
val betterText = better?.let { stringResource(R.string.review_better, "\u0000").split('\u0000') }
val link = MaterialTheme.colorScheme.primary
val text = buildAnnotatedString {
withStyle(SpanStyle(color = c, fontWeight = FontWeight.Bold)) { append(judgementSymbol(mark.judgement) + " " + name) }
if (better != null && betterText != null) {
append(" · ")
append(betterText.first())
// The move in the link color: the row can be tapped (§21.3).
withStyle(SpanStyle(color = link, fontWeight = FontWeight.Medium)) { append(better) }
append(betterText.getOrElse(1) { "" })
}
}
Box(
Modifier
.weight(1f)
.height(48.dp)
.then(if (canShow) Modifier.clickable(onClickLabel = stringResource(R.string.review_show_best)) { onBest(mark) } else Modifier),
contentAlignment = Alignment.CenterStart,
) {
Text(text, style = textStyle, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
report()
}
state.failure != null -> {
Text(stringResource(R.string.review_failed), style = textStyle, color = MaterialTheme.colorScheme.error, modifier = Modifier.weight(1f))
TextButton(onClick = onResume) { Text(stringResource(R.string.review_resume)) }
report()
}
state.missing > 0u -> {
Text(
stringResource(R.string.review_missing, state.missing.toInt()),
style = textStyle.merge(Tabular),
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.weight(1f),
)
TextButton(onClick = onResume) { Text(stringResource(R.string.review_fill)) }
report()
}
else -> {
val spoken = stringResource(R.string.review_accuracy_of, percent(state.white.accuracy), percent(state.black.accuracy))
Row(
Modifier.weight(1f).clearAndSetSemantics { contentDescription = spoken },
verticalAlignment = Alignment.CenterVertically,
) {
Text(stringResource(R.string.review_accuracy), style = textStyle, color = MaterialTheme.colorScheme.onSurfaceVariant)
Spacer(Modifier.width(10.dp))
SideDot(white = true)
Text(percent(state.white.accuracy), style = textStyle.merge(Tabular), fontWeight = FontWeight.Medium, modifier = Modifier.padding(start = 6.dp))
Spacer(Modifier.width(14.dp))
SideDot(white = false)
Text(percent(state.black.accuracy), style = textStyle.merge(Tabular), fontWeight = FontWeight.Medium, modifier = Modifier.padding(start = 6.dp))
}
report()
}
}
}
if (showGraph) {
EvalGraph(state, cursor, cursorLabel, onIndex, Modifier.fillMaxWidth().height(40.dp).padding(start = 16.dp, end = 16.dp, bottom = 8.dp))
}
}
}
/// A circle in a side's color, outlined so the white one shows on a light background.
@Composable
private fun SideDot(white: Boolean, size: Int = 12) {
Box(
Modifier
.size(size.dp)
.clip(CircleShape)
.background(if (white) Color(0xFFF5F5F0) else Color(0xFF26282B))
.border(1.dp, MaterialTheme.colorScheme.outline, CircleShape),
)
}
/// White's chance of winning along the main line (§21.3), as on the desktop: light area
/// for White, dark for Black, the curve, the errors as dots, the phases and the current
/// move. A tap or a drag goes to a move.
@Composable
fun EvalGraph(state: ReviewState, cursor: Int?, cursorLabel: String?, onIndex: (Int) -> Unit, modifier: Modifier) {
val chess = LocalChessColors.current
val dark = chess.dark
// In the light theme a shade darker than the panel, so that White's area shows.
val bg = if (dark) MaterialTheme.colorScheme.surfaceContainerHighest else Color(0xFFDCDFE3)
val whiteFill = if (dark) Color(0xFF969696) else Color(0xFFFFFFFF)
val blackFill = if (dark) Color(0xFF0A0A0A) else Color(0xFF464646)
val curve = Color(0xFFE07B1F)
val midColor = MaterialTheme.colorScheme.outline
val phaseColor = MaterialTheme.colorScheme.onSurfaceVariant
val description = stringResource(R.string.review_graph)
val now = cursor?.let { state.points.getOrNull(it) }
val spokenState = now?.eval?.takeIf { it.isNotEmpty() }?.let { e ->
stringResource(R.string.review_graph_state, cursorLabel ?: stringResource(R.string.review_start_position), e)
}
val points = state.points
val n = points.size
val pick by rememberUpdatedState(onIndex)
Canvas(
modifier
.clip(RoundedCornerShape(6.dp))
.background(bg)
.semantics {
contentDescription = description
spokenState?.let { stateDescription = it }
}
.pointerInput(n) {
if (n < 2) return@pointerInput
val pad = 6.dp.toPx()
fun index(x: Float): Int {
val t = ((x - pad) / (size.width - 2 * pad)).coerceIn(0f, 1f)
return (t * (n - 1)).roundToInt()
}
awaitEachGesture {
val down = awaitFirstDown()
var last = index(down.position.x)
pick(last)
down.consume()
while (true) {
val event = awaitPointerEvent()
val change = event.changes.firstOrNull { it.id == down.id } ?: break
if (!change.pressed) break
val i = index(change.position.x)
if (i != last) {
last = i
pick(i)
}
change.consume()
}
}
},
) {
if (n < 2) return@Canvas
val padX = 6.dp.toPx()
val padY = 4.dp.toPx()
val w = size.width - 2 * padX
val h = size.height - 2 * padY
fun x(i: Int) = padX + w * i / (n - 1)
fun y(wp: Float) = padY + h * (1f - wp / 100f)
val mid = y(50f)
// Advantage areas between the curve and the middle line: one outline per run of
// evaluated positions, drawn light above the middle and dark below it (one shape,
// so no seams between the moves).
val area = Path()
var open = false
var lastX = 0f
points.forEachIndexed { i, p ->
val wp = p.whiteWin
if (wp == null) {
if (open) {
area.lineTo(lastX, mid)
area.close()
open = false
}
} else {
if (!open) {
area.moveTo(x(i), mid)
open = true
}
area.lineTo(x(i), y(wp))
lastX = x(i)
}
}
if (open) {
area.lineTo(lastX, mid)
area.close()
}
clipRect(bottom = mid) { drawPath(area, whiteFill) }
clipRect(top = mid) { drawPath(area, blackFill) }
drawLine(midColor.copy(alpha = 0.6f), Offset(padX, mid), Offset(size.width - padX, mid), 1.dp.toPx())
// Phase boundaries, without labels: at this height they would cover the curve
// (§21.3); the report has the accuracy per phase.
listOfNotNull(state.middlegame?.toInt(), state.endgame?.toInt()).filter { it in 1 until n }.forEach { i ->
drawLine(phaseColor.copy(alpha = 0.5f), Offset(x(i), 0f), Offset(x(i), size.height), 1.dp.toPx())
}
// The curve, broken where positions are not evaluated yet.
val stroke = Stroke(width = 1.6.dp.toPx())
var path: Path? = null
var count = 0
fun flush() {
if (count > 1) path?.let { drawPath(it, curve, style = stroke) }
path = null
count = 0
}
points.forEachIndexed { i, p ->
val wp = p.whiteWin
if (wp == null) {
flush()
} else {
val px = x(i)
val py = y(wp)
val current = path
if (current == null) {
path = Path().apply { moveTo(px, py) }
} else {
current.lineTo(px, py)
}
count++
}
}
flush()
// The errors on top of everything but the current move.
points.forEachIndexed { i, p ->
val j = p.judgement ?: return@forEachIndexed
val wp = p.whiteWin ?: return@forEachIndexed
drawCircle(judgementColor(j, dark), 3.5.dp.toPx(), Offset(x(i), y(wp)))
}
if (cursor != null && cursor in 0 until n) {
drawLine(curve, Offset(x(cursor), 0f), Offset(x(cursor), size.height), 1.5.dp.toPx())
}
}
}
/// The sheet that starts the analysis (§21.2).
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ReviewStartSheet(
state: ReviewState?,
quality: Int,
threads: Int,
npsPerThread: Long,
onQuality: (Int) -> Unit,
onStart: (full: Boolean) -> Unit,
onDismiss: () -> Unit,
) {
ModalBottomSheet(onDismissRequest = onDismiss) {
Column(Modifier.fillMaxWidth().navigationBarsPadding().padding(start = 24.dp, end = 24.dp, bottom = 24.dp)) {
Text(stringResource(R.string.review_menu), style = MaterialTheme.typography.titleLarge)
Spacer(Modifier.height(12.dp))
Text(stringResource(R.string.review_text), style = MaterialTheme.typography.bodyLarge)
Spacer(Modifier.height(20.dp))
Text(stringResource(R.string.review_quality), style = MaterialTheme.typography.labelLarge)
Spacer(Modifier.height(8.dp))
val names = listOf(R.string.review_fast, R.string.review_normal, R.string.review_deep)
SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) {
names.forEachIndexed { i, res ->
SegmentedButton(
selected = quality == i,
onClick = { onQuality(i) },
shape = SegmentedButtonDefaults.itemShape(i, names.size),
) { Text(stringResource(res), maxLines = 1) }
}
}
Spacer(Modifier.height(12.dp))
val total = state?.positions?.toInt() ?: 0
val missing = state?.missing?.toInt() ?: total
// Some positions already have an engine evaluation: fill in, or start over.
val partial = state != null && state.hasData && state.nodes > 0UL && missing in 1 until total
val positions = if (partial) missing else total
// "Fill in" keeps the quality of the first run; the choice is for starting over.
val nodes = (if (partial) state.nodes else REVIEW_NODES[quality.coerceIn(0, REVIEW_NODES.size - 1)]).toDouble()
val nps = (if (npsPerThread > 0) npsPerThread else GUESS_NPS_PER_THREAD).toDouble() * threads.coerceAtLeast(1)
val secs = ceil(positions * nodes / nps).toInt().coerceAtLeast(1)
val time = if (secs < 60) stringResource(R.string.review_seconds, secs) else stringResource(R.string.review_minutes, (secs + 59) / 60)
Text(
pluralStringResource(R.plurals.review_estimate, positions, positions, time),
style = MaterialTheme.typography.bodyMedium.merge(Tabular),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (partial) {
Spacer(Modifier.height(4.dp))
Text(
stringResource(R.string.review_partial, total - missing, total),
style = MaterialTheme.typography.bodyMedium.merge(Tabular),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Spacer(Modifier.height(24.dp))
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) {
if (partial) {
TextButton(onClick = { onStart(true) }) { Text(stringResource(R.string.review_restart)) }
Button(onClick = { onStart(false) }) { Text(stringResource(R.string.review_fill)) }
} else {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
// Everything evaluated already: analysing again starts over.
Button(onClick = { onStart(state?.hasData == true) }) { Text(stringResource(R.string.review_start)) }
}
}
}
}
}
/// The report (§21.5): White and Black side by side, as on Lichess; a count above zero
/// goes to the next such move of that player.
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
fun ReviewSheet(
state: ReviewState,
white: String,
black: String,
onError: (white: Boolean, MoveJudgement) -> Unit,
onAgain: () -> Unit,
onHide: () -> Unit,
onDismiss: () -> Unit,
) {
// Opened whole: nothing in it should hide below the edge (§21.5).
ModalBottomSheet(onDismissRequest = onDismiss, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).navigationBarsPadding().padding(start = 24.dp, end = 16.dp, bottom = 24.dp)) {
Text(stringResource(R.string.review_report_menu), style = MaterialTheme.typography.titleLarge)
Spacer(Modifier.height(16.dp))
val dark = LocalChessColors.current.dark
val variant = MaterialTheme.colorScheme.onSurfaceVariant
// Player names over the two columns.
ReportRow(
label = {},
white = { PlayerHead(white, true) },
black = { PlayerHead(black, false) },
height = null,
)
ReportRow(
label = { Text(stringResource(R.string.review_accuracy), style = MaterialTheme.typography.bodyLarge) },
white = { ReportNumber(percent(state.white.accuracy), MaterialTheme.typography.headlineSmall) },
black = { ReportNumber(percent(state.black.accuracy), MaterialTheme.typography.headlineSmall) },
)
val next = stringResource(R.string.review_next)
listOf(MoveJudgement.INACCURACY, MoveJudgement.MISTAKE, MoveJudgement.BLUNDER).forEach { j ->
val c = judgementColor(j, dark)
val label = judgementPlural(j)
val cell: @Composable (Boolean, UInt, String) -> Unit = { isWhite, count, side ->
val active = count > 0u
Row(
Modifier
.fillMaxWidth()
.height(48.dp)
.then(
if (active) {
Modifier
.clickable(onClickLabel = next) { onError(isWhite, j) }
.semantics {
role = Role.Button
contentDescription = "$label, $side, $count"
}
} else {
Modifier.clearAndSetSemantics { contentDescription = "$label, $side, $count" }
},
),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.End,
) {
Text(
count.toString(),
style = MaterialTheme.typography.titleMedium.merge(Tabular),
color = if (active) c else variant,
)
Box(Modifier.width(24.dp), contentAlignment = Alignment.CenterEnd) {
if (active) Icon(Icons.Rounded.ChevronRight, null, tint = variant, modifier = Modifier.size(20.dp))
}
}
}
val whiteSide = stringResource(R.string.tag_white)
val blackSide = stringResource(R.string.tag_black)
ReportRow(
label = {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(judgementSymbol(j), color = c, fontWeight = FontWeight.Bold, modifier = Modifier.width(28.dp))
Text(label, style = MaterialTheme.typography.bodyLarge)
}
},
white = { cell(true, state.white.inaccuraciesOf(j), whiteSide) },
black = { cell(false, state.black.inaccuraciesOf(j), blackSide) },
)
}
ReportRow(
label = { Text(stringResource(R.string.review_acpl), style = MaterialTheme.typography.bodyMedium, color = variant) },
white = { ReportNumber(state.white.acpl?.toString() ?: "\u2014") },
black = { ReportNumber(state.black.acpl?.toString() ?: "\u2014") },
height = null,
)
listOf(
Triple(R.string.review_opening, state.white.opening, state.black.opening),
Triple(R.string.review_middlegame, state.white.middlegame, state.black.middlegame),
Triple(R.string.review_endgame, state.white.endgame, state.black.endgame),
).filter { it.second != null || it.third != null }.forEach { (res, w, b) ->
ReportRow(
label = { Text(stringResource(res), style = MaterialTheme.typography.bodyMedium, color = variant) },
white = { ReportNumber(percent(w)) },
black = { ReportNumber(percent(b)) },
height = 40,
)
}
Spacer(Modifier.height(12.dp))
Text(
if (state.nodes == 0UL) {
stringResource(R.string.review_source_pgn)
} else {
stringResource(R.string.review_source, state.engine, compactCount(state.nodes))
},
style = MaterialTheme.typography.bodySmall,
color = variant,
)
Spacer(Modifier.height(20.dp))
// With a large font the two buttons go on two lines instead of breaking words.
FlowRow(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) {
TextButton(onClick = onHide) { Text(stringResource(R.string.review_hide)) }
OutlinedButton(onClick = onAgain, enabled = !state.running) { Text(stringResource(R.string.review_again)) }
}
}
}
}
private fun SideReview.inaccuraciesOf(j: MoveJudgement): UInt = when (j) {
MoveJudgement.INACCURACY -> inaccuracies
MoveJudgement.MISTAKE -> mistakes
MoveJudgement.BLUNDER -> blunders
}
/// A row of the report: its label, then White's and Black's cells, 96 dp each.
@Composable
private fun ReportRow(
label: @Composable () -> Unit,
white: @Composable () -> Unit,
black: @Composable () -> Unit,
height: Int? = 48,
) {
Row(
Modifier.fillMaxWidth().then(if (height != null) Modifier.height(height.dp) else Modifier.padding(vertical = 4.dp)),
verticalAlignment = Alignment.CenterVertically,
) {
Box(Modifier.weight(1f)) { label() }
Box(Modifier.width(96.dp), contentAlignment = Alignment.CenterEnd) { white() }
Box(Modifier.width(96.dp), contentAlignment = Alignment.CenterEnd) { black() }
}
}
/// A player over a column: the side's circle and the surname, up to two lines; the full
/// name for TalkBack.
@Composable
private fun PlayerHead(name: String, white: Boolean) {
Row(
Modifier.padding(start = 4.dp).semantics(mergeDescendants = true) { contentDescription = name },
verticalAlignment = Alignment.CenterVertically,
) {
SideDot(white, 12)
Text(
name.substringBefore(',').trim(),
style = MaterialTheme.typography.labelLarge,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(start = 8.dp),
)
}
}
@Composable
private fun ReportNumber(text: String, style: TextStyle = MaterialTheme.typography.bodyLarge) {
Text(text, style = style.merge(Tabular), fontWeight = FontWeight.Medium, modifier = Modifier.padding(end = 24.dp))
}
/// 250 000 → "250k", 1 000 000 → "1M", 1 500 000 → "1.5M" (as on the desktop).
private fun compactCount(n: ULong): String {
val v = n.toLong()
return when {
v >= 1_000_000 && v % 100_000 == 0L -> if (v % 1_000_000 == 0L) "${v / 1_000_000}M" else "%.1fM".format(java.util.Locale.ROOT, v / 1e6)
v >= 1000 -> "${v / 1000}k"
else -> v.toString()
}
}

View file

@ -223,4 +223,52 @@
<string name="file_copy_failed">Die App konnte keine Kopie der Datei speichern. Prüfen Sie, ob auf dem Telefon Platz frei ist.</string>
<string name="db_copy">Kopie</string>
<string name="removed_copy">Datenbank aus ChessPenguin gelöscht</string>
<!-- Game report (android-ui.md §21) -->
<string name="review_menu">Partieanalyse</string>
<string name="review_report_menu">Partiebericht</string>
<string name="review_text">Die Engine bewertet jede Stellung der Hauptvariante. Die Partie selbst wird nicht verändert.</string>
<string name="review_quality">Qualität</string>
<string name="review_fast">Schnell</string>
<string name="review_normal">Normal</string>
<string name="review_deep">Gründlich</string>
<string name="review_seconds">%d s</string>
<string name="review_minutes">%d Min.</string>
<string name="review_start">Analysieren</string>
<string name="review_fill">Ergänzen</string>
<string name="review_again">Erneut analysieren</string>
<string name="review_partial">%1$d von %2$d Stellungen sind schon bewertet.</string>
<string name="review_progress">Partieanalyse · %1$d von %2$d</string>
<string name="review_stop">Analyse anhalten</string>
<string name="review_accuracy">Genauigkeit</string>
<string name="review_accuracy_of">Genauigkeit: Weiß %1$s, Schwarz %2$s</string>
<string name="review_report">Bericht</string>
<string name="review_better">besser war %1$s</string>
<string name="review_inaccuracy">Ungenauigkeit</string>
<string name="review_mistake">Fehler</string>
<string name="review_blunder">Grober Fehler</string>
<string name="review_inaccuracies">Ungenauigkeiten</string>
<string name="review_mistakes">Fehler</string>
<string name="review_blunders">Grobe Fehler</string>
<string name="review_missing">Ohne Bewertung: %d</string>
<string name="review_failed">Die Analyse wurde unterbrochen</string>
<string name="review_resume">Fortsetzen</string>
<string name="review_acpl">Durchschnittlicher Centibauernverlust</string>
<string name="review_opening">Eröffnung</string>
<string name="review_middlegame">Mittelspiel</string>
<string name="review_endgame">Endspiel</string>
<string name="review_source">%1$s · %2$s Knoten pro Zug</string>
<string name="review_source_pgn" formatted="false">Bewertungen aus der PGN ([%eval])</string>
<string name="review_hide">Analyse ausblenden</string>
<string name="review_graph">Bewertungsgrafik</string>
<string name="review_engine_paused">Pausiert: Partie wird analysiert</string>
<string name="review_best_preview">Bessere Variante · Zug %1$d von %2$d</string>
<string name="review_next">Zum nächsten solchen Zug</string>
<string name="review_show_best">Die bessere Variante auf dem Brett zeigen</string>
<string name="review_restart">Von vorn</string>
<string name="review_graph_state">%1$s, Bewertung %2$s</string>
<string name="review_start_position">Ausgangsstellung</string>
<plurals name="review_estimate">
<item quantity="one">%1$d Stellung, etwa %2$s</item>
<item quantity="other">%1$d Stellungen, etwa %2$s</item>
</plurals>
</resources>

View file

@ -227,4 +227,53 @@
<string name="file_copy_failed">La aplicación no pudo guardar una copia del archivo. Compruebe que el teléfono tiene espacio libre.</string>
<string name="db_copy">copia</string>
<string name="removed_copy">Base eliminada de ChessPenguin</string>
<!-- Game report (android-ui.md §21) -->
<string name="review_menu">Análisis de la partida</string>
<string name="review_report_menu">Informe de la partida</string>
<string name="review_text">El motor evalúa cada posición de la línea principal. La partida en sí no cambia.</string>
<string name="review_quality">Calidad</string>
<string name="review_fast">Rápido</string>
<string name="review_normal">Normal</string>
<string name="review_deep">Profundo</string>
<string name="review_seconds">%d s</string>
<string name="review_minutes">%d min</string>
<string name="review_start">Analizar</string>
<string name="review_fill">Completar</string>
<string name="review_again">Analizar de nuevo</string>
<string name="review_partial">Ya hay %1$d de %2$d posiciones evaluadas.</string>
<string name="review_progress">Análisis · %1$d de %2$d</string>
<string name="review_stop">Detener el análisis</string>
<string name="review_accuracy">Precisión</string>
<string name="review_accuracy_of">Precisión: blancas %1$s, negras %2$s</string>
<string name="review_report">Informe</string>
<string name="review_better">era mejor %1$s</string>
<string name="review_inaccuracy">Imprecisión</string>
<string name="review_mistake">Error</string>
<string name="review_blunder">Error grave</string>
<string name="review_inaccuracies">Imprecisiones</string>
<string name="review_mistakes">Errores</string>
<string name="review_blunders">Errores graves</string>
<string name="review_missing">Sin evaluar: %d</string>
<string name="review_failed">El análisis se interrumpió</string>
<string name="review_resume">Continuar</string>
<string name="review_acpl">Pérdida media de centipeones</string>
<string name="review_opening">Apertura</string>
<string name="review_middlegame">Medio juego</string>
<string name="review_endgame">Final</string>
<string name="review_source">%1$s · %2$s nodos por jugada</string>
<string name="review_source_pgn" formatted="false">Evaluaciones del PGN ([%eval])</string>
<string name="review_hide">Ocultar el análisis</string>
<string name="review_graph">Gráfico de evaluación</string>
<string name="review_engine_paused">En pausa: se está analizando la partida</string>
<string name="review_best_preview">Mejor línea · jugada %1$d de %2$d</string>
<string name="review_next">Ir a la siguiente jugada así</string>
<string name="review_show_best">Mostrar la mejor línea en el tablero</string>
<string name="review_restart">Empezar de nuevo</string>
<string name="review_graph_state">%1$s, evaluación %2$s</string>
<string name="review_start_position">Posición inicial</string>
<plurals name="review_estimate">
<item quantity="one">%1$d posición, unos %2$s</item>
<item quantity="many">%1$d posiciones, unos %2$s</item>
<item quantity="other">%1$d posiciones, unos %2$s</item>
</plurals>
</resources>

View file

@ -227,4 +227,53 @@
<string name="file_copy_failed">L’application n’a pas pu garder une copie du fichier. Vérifiez qu’il reste de la place sur le téléphone.</string>
<string name="db_copy">copie</string>
<string name="removed_copy">Base supprimée de ChessPenguin</string>
<!-- Game report (android-ui.md §21) -->
<string name="review_menu">Analyse de la partie</string>
<string name="review_report_menu">Rapport de la partie</string>
<string name="review_text">Le moteur évalue chaque position de la ligne principale. La partie elle-même n\'est pas modifiée.</string>
<string name="review_quality">Qualité</string>
<string name="review_fast">Rapide</string>
<string name="review_normal">Normal</string>
<string name="review_deep">Approfondi</string>
<string name="review_seconds">%d s</string>
<string name="review_minutes">%d min</string>
<string name="review_start">Analyser</string>
<string name="review_fill">Compléter</string>
<string name="review_again">Analyser de nouveau</string>
<string name="review_partial">%1$d positions sur %2$d sont déjà évaluées.</string>
<string name="review_progress">Analyse · %1$d sur %2$d</string>
<string name="review_stop">Arrêter l\'analyse</string>
<string name="review_accuracy">Précision</string>
<string name="review_accuracy_of">Précision : Blancs %1$s, Noirs %2$s</string>
<string name="review_report">Rapport</string>
<string name="review_better">%1$s était meilleur</string>
<string name="review_inaccuracy">Imprécision</string>
<string name="review_mistake">Erreur</string>
<string name="review_blunder">Gaffe</string>
<string name="review_inaccuracies">Imprécisions</string>
<string name="review_mistakes">Erreurs</string>
<string name="review_blunders">Gaffes</string>
<string name="review_missing">Non évaluées : %d</string>
<string name="review_failed">L\'analyse s\'est interrompue</string>
<string name="review_resume">Continuer</string>
<string name="review_acpl">Perte moyenne en centipions</string>
<string name="review_opening">Ouverture</string>
<string name="review_middlegame">Milieu de partie</string>
<string name="review_endgame">Finale</string>
<string name="review_source">%1$s · %2$s nœuds par coup</string>
<string name="review_source_pgn" formatted="false">Évaluations issues du PGN ([%eval])</string>
<string name="review_hide">Masquer l\'analyse</string>
<string name="review_graph">Graphique d\'évaluation</string>
<string name="review_engine_paused">En pause : analyse de la partie en cours</string>
<string name="review_best_preview">Meilleure ligne · coup %1$d sur %2$d</string>
<string name="review_next">Aller au coup suivant de ce type</string>
<string name="review_show_best">Afficher la meilleure ligne sur l\'échiquier</string>
<string name="review_restart">Recommencer</string>
<string name="review_graph_state">%1$s, évaluation %2$s</string>
<string name="review_start_position">Position de départ</string>
<plurals name="review_estimate">
<item quantity="one">%1$d position, environ %2$s</item>
<item quantity="many">%1$d positions, environ %2$s</item>
<item quantity="other">%1$d positions, environ %2$s</item>
</plurals>
</resources>

View file

@ -227,4 +227,53 @@
<string name="file_copy_failed">L’app non è riuscita a salvare una copia del file. Controlla che sul telefono ci sia spazio libero.</string>
<string name="db_copy">copia</string>
<string name="removed_copy">Database eliminato da ChessPenguin</string>
<!-- Game report (android-ui.md §21) -->
<string name="review_menu">Analisi della partita</string>
<string name="review_report_menu">Resoconto della partita</string>
<string name="review_text">Il motore valuta ogni posizione della linea principale. La partita non viene modificata.</string>
<string name="review_quality">Qualità</string>
<string name="review_fast">Veloce</string>
<string name="review_normal">Normale</string>
<string name="review_deep">Approfondito</string>
<string name="review_seconds">%d s</string>
<string name="review_minutes">%d min</string>
<string name="review_start">Analizza</string>
<string name="review_fill">Completa</string>
<string name="review_again">Analizza di nuovo</string>
<string name="review_partial">%1$d posizioni su %2$d sono già valutate.</string>
<string name="review_progress">Analisi · %1$d di %2$d</string>
<string name="review_stop">Interrompi l\'analisi</string>
<string name="review_accuracy">Precisione</string>
<string name="review_accuracy_of">Precisione: Bianco %1$s, Nero %2$s</string>
<string name="review_report">Resoconto</string>
<string name="review_better">era meglio %1$s</string>
<string name="review_inaccuracy">Imprecisione</string>
<string name="review_mistake">Errore</string>
<string name="review_blunder">Svarione</string>
<string name="review_inaccuracies">Imprecisioni</string>
<string name="review_mistakes">Errori</string>
<string name="review_blunders">Svarioni</string>
<string name="review_missing">Non valutate: %d</string>
<string name="review_failed">L\'analisi si è interrotta</string>
<string name="review_resume">Continua</string>
<string name="review_acpl">Perdita media in centipedoni</string>
<string name="review_opening">Apertura</string>
<string name="review_middlegame">Mediogioco</string>
<string name="review_endgame">Finale</string>
<string name="review_source">%1$s · %2$s nodi per mossa</string>
<string name="review_source_pgn" formatted="false">Valutazioni dal PGN ([%eval])</string>
<string name="review_hide">Nascondi l\'analisi</string>
<string name="review_graph">Grafico di valutazione</string>
<string name="review_engine_paused">In pausa: analisi della partita in corso</string>
<string name="review_best_preview">Linea migliore · mossa %1$d di %2$d</string>
<string name="review_next">Vai alla prossima mossa di questo tipo</string>
<string name="review_show_best">Mostra la linea migliore sulla scacchiera</string>
<string name="review_restart">Ricomincia</string>
<string name="review_graph_state">%1$s, valutazione %2$s</string>
<string name="review_start_position">Posizione iniziale</string>
<plurals name="review_estimate">
<item quantity="one">%1$d posizione, circa %2$s</item>
<item quantity="many">%1$d posizioni, circa %2$s</item>
<item quantity="other">%1$d posizioni, circa %2$s</item>
</plurals>
</resources>

View file

@ -231,4 +231,54 @@
<string name="file_copy_failed">Приложению не удалось сохранить копию файла. Проверьте, есть ли на телефоне свободное место.</string>
<string name="db_copy">копия</string>
<string name="removed_copy">База удалена из ChessPenguin</string>
<!-- Game report (android-ui.md §21) -->
<string name="review_menu">Анализ партии</string>
<string name="review_report_menu">Отчёт по партии</string>
<string name="review_text">Движок оценит каждую позицию основной линии. Сама партия не изменится.</string>
<string name="review_quality">Качество</string>
<string name="review_fast">Быстро</string>
<string name="review_normal">Обычно</string>
<string name="review_deep">Глубоко</string>
<string name="review_seconds">%d с</string>
<string name="review_minutes">%d мин</string>
<string name="review_start">Анализировать</string>
<string name="review_fill">Дополнить</string>
<string name="review_again">Анализировать заново</string>
<string name="review_partial">Уже оценено позиций: %1$d из %2$d.</string>
<string name="review_progress">Анализ партии · %1$d из %2$d</string>
<string name="review_stop">Остановить анализ</string>
<string name="review_accuracy">Точность</string>
<string name="review_accuracy_of">Точность: белые %1$s, чёрные %2$s</string>
<string name="review_report">Отчёт</string>
<string name="review_better">лучше было %1$s</string>
<string name="review_inaccuracy">Неточность</string>
<string name="review_mistake">Ошибка</string>
<string name="review_blunder">Зевок</string>
<string name="review_inaccuracies">Неточности</string>
<string name="review_mistakes">Ошибки</string>
<string name="review_blunders">Зевки</string>
<string name="review_missing">Без оценки: %d</string>
<string name="review_failed">Анализ прервался</string>
<string name="review_resume">Продолжить</string>
<string name="review_acpl">Средняя потеря сантипешек</string>
<string name="review_opening">Дебют</string>
<string name="review_middlegame">Миттельшпиль</string>
<string name="review_endgame">Эндшпиль</string>
<string name="review_source">%1$s · %2$s узлов на ход</string>
<string name="review_source_pgn" formatted="false">Оценки из PGN ([%eval])</string>
<string name="review_hide">Скрыть анализ</string>
<string name="review_graph">График оценки</string>
<string name="review_engine_paused">Пауза: идёт анализ партии</string>
<string name="review_best_preview">Лучшая линия · ход %1$d из %2$d</string>
<string name="review_next">Перейти к следующему такому ходу</string>
<string name="review_show_best">Показать лучшую линию на доске</string>
<string name="review_restart">Заново</string>
<string name="review_graph_state">%1$s, оценка %2$s</string>
<string name="review_start_position">Начальная позиция</string>
<plurals name="review_estimate">
<item quantity="one">Позиций: %1$d, примерно %2$s</item>
<item quantity="few">Позиций: %1$d, примерно %2$s</item>
<item quantity="many">Позиций: %1$d, примерно %2$s</item>
<item quantity="other">Позиций: %1$d, примерно %2$s</item>
</plurals>
</resources>

View file

@ -226,4 +226,52 @@
<string name="file_copy_failed">The app could not keep a copy of the file. Check that the phone has free space.</string>
<string name="db_copy">copy</string>
<string name="removed_copy">Database deleted from ChessPenguin</string>
<!-- Game report (android-ui.md §21) -->
<string name="review_menu">Game analysis</string>
<string name="review_report_menu">Game report</string>
<string name="review_text">The engine evaluates every position of the main line. The game itself is not changed.</string>
<string name="review_quality">Quality</string>
<string name="review_fast">Fast</string>
<string name="review_normal">Normal</string>
<string name="review_deep">Deep</string>
<string name="review_seconds">%d s</string>
<string name="review_minutes">%d min</string>
<string name="review_start">Analyse</string>
<string name="review_fill">Fill in</string>
<string name="review_again">Analyse again</string>
<string name="review_partial">%1$d of %2$d positions are evaluated already.</string>
<string name="review_progress">Game analysis · %1$d of %2$d</string>
<string name="review_stop">Stop the analysis</string>
<string name="review_accuracy">Accuracy</string>
<string name="review_accuracy_of">Accuracy: White %1$s, Black %2$s</string>
<string name="review_report">Report</string>
<string name="review_better">%1$s was better</string>
<string name="review_inaccuracy">Inaccuracy</string>
<string name="review_mistake">Mistake</string>
<string name="review_blunder">Blunder</string>
<string name="review_inaccuracies">Inaccuracies</string>
<string name="review_mistakes">Mistakes</string>
<string name="review_blunders">Blunders</string>
<string name="review_missing">Not evaluated: %d</string>
<string name="review_failed">The analysis stopped</string>
<string name="review_resume">Continue</string>
<string name="review_acpl">Average centipawn loss</string>
<string name="review_opening">Opening</string>
<string name="review_middlegame">Middlegame</string>
<string name="review_endgame">Endgame</string>
<string name="review_source">%1$s · %2$s nodes per move</string>
<string name="review_source_pgn" formatted="false">Evaluations from the PGN ([%eval])</string>
<string name="review_hide">Hide analysis</string>
<string name="review_graph">Evaluation graph</string>
<string name="review_engine_paused">Paused: the game is being analysed</string>
<string name="review_best_preview">Better line · move %1$d of %2$d</string>
<string name="review_next">Go to the next such move</string>
<string name="review_show_best">Show the better line on the board</string>
<string name="review_restart">Start over</string>
<string name="review_graph_state">%1$s, evaluation %2$s</string>
<string name="review_start_position">Start position</string>
<plurals name="review_estimate">
<item quantity="one">%1$d position, about %2$s</item>
<item quantity="other">%1$d positions, about %2$s</item>
</plurals>
</resources>