diff --git a/CHANGELOG.md b/CHANGELOG.md index 2263cb6..8c9bc22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). +## [Unreleased] + +- Android: **game report** — ⋮ → «Game analysis» lets Stockfish evaluate every move of the + main line, as on the desktop: inaccuracies, mistakes and blunders marked in the notation, + an evaluation graph under the board (tap or drag to go to a move), each player's accuracy + and average centipawn loss in the report, the better move of every error shown on the + board. Games with `[%eval]` comments (Lichess exports) and games analysed before show + their report at once. The live engine waits while the game is analysed. +- The game report's evaluations, judgements, accuracy and cache are now one shared part of + the desktop and Android apps, so both give the same numbers. + ## [0.12.0] — 2026-10-23 - Android: **paste PGN** — when the clipboard holds text, «Add a database» offers to paste diff --git a/Cargo.lock b/Cargo.lock index 1dafbaa..f6404fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -803,6 +803,7 @@ dependencies = [ "egui_extras", "flate2", "form_urlencoded", + "game-review", "getrandom 0.3.4", "image", "rfd", @@ -1647,6 +1648,17 @@ dependencies = [ "slab", ] +[[package]] +name = "game-review" +version = "0.12.0" +dependencies = [ + "chess-core", + "serde", + "serde_json", + "shakmaty", + "uci", +] + [[package]] name = "gethostname" version = "1.1.0" @@ -2403,6 +2415,7 @@ version = "0.12.0" dependencies = [ "chess-core", "chess-import", + "game-review", "shakmaty", "thiserror 2.0.21", "uci", diff --git a/Cargo.toml b/Cargo.toml index c9e434a..92525d3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,7 @@ members = [ "crates/chess-core", "crates/chess-import", "crates/uci", + "crates/game-review", "crates/mobile-api", "apps/desktop", ] @@ -35,6 +36,7 @@ directories = "6" chess-core = { path = "crates/chess-core" } chess-import = { path = "crates/chess-import" } uci = { path = "crates/uci" } +game-review = { path = "crates/game-review" } [profile.dev.package."*"] opt-level = 2 diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ReviewSession.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ReviewSession.kt new file mode 100644 index 0000000..e006fa7 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ReviewSession.kt @@ -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(null) + /// The analysis of the game shown, `null` while it loads. + val state: StateFlow = _state.asStateFlow() + + private val lock = Mutex() + private var review: GameReview? = null + private var game: Pair? = 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 + } +} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt index 102048d..121cc41 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt @@ -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() } } diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/EngineViews.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/EngineViews.kt index 136bf67..503eab4 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/EngineViews.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/EngineViews.kt @@ -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), diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt index 2edc2a5..42219a6 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt @@ -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(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(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(null) } + // The download sheet was opened to analyse the game (not for the engine button). + var sheetForReview by remember { mutableStateOf(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, 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 }, ) } } diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Notation.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Notation.kt index b9fd01d..784f982 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Notation.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Notation.kt @@ -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 = 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, ) { 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)) } } } diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/ReviewViews.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/ReviewViews.kt new file mode 100644 index 0000000..7c136f6 --- /dev/null +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/ReviewViews.kt @@ -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, 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() + } +} diff --git a/androidApp/app/src/main/res/values-de/strings.xml b/androidApp/app/src/main/res/values-de/strings.xml index 5d6ac45..3c0dbe8 100644 --- a/androidApp/app/src/main/res/values-de/strings.xml +++ b/androidApp/app/src/main/res/values-de/strings.xml @@ -223,4 +223,52 @@ Die App konnte keine Kopie der Datei speichern. Prüfen Sie, ob auf dem Telefon Platz frei ist. Kopie Datenbank aus ChessPenguin gelöscht + + Partieanalyse + Partiebericht + Die Engine bewertet jede Stellung der Hauptvariante. Die Partie selbst wird nicht verändert. + Qualität + Schnell + Normal + Gründlich + %d s + %d Min. + Analysieren + Ergänzen + Erneut analysieren + %1$d von %2$d Stellungen sind schon bewertet. + Partieanalyse · %1$d von %2$d + Analyse anhalten + Genauigkeit + Genauigkeit: Weiß %1$s, Schwarz %2$s + Bericht + besser war %1$s + Ungenauigkeit + Fehler + Grober Fehler + Ungenauigkeiten + Fehler + Grobe Fehler + Ohne Bewertung: %d + Die Analyse wurde unterbrochen + Fortsetzen + Durchschnittlicher Centibauernverlust + Eröffnung + Mittelspiel + Endspiel + %1$s · %2$s Knoten pro Zug + Bewertungen aus der PGN ([%eval]) + Analyse ausblenden + Bewertungsgrafik + Pausiert: Partie wird analysiert + Bessere Variante · Zug %1$d von %2$d + Zum nächsten solchen Zug + Die bessere Variante auf dem Brett zeigen + Von vorn + %1$s, Bewertung %2$s + Ausgangsstellung + + %1$d Stellung, etwa %2$s + %1$d Stellungen, etwa %2$s + diff --git a/androidApp/app/src/main/res/values-es/strings.xml b/androidApp/app/src/main/res/values-es/strings.xml index f1861ef..255014f 100644 --- a/androidApp/app/src/main/res/values-es/strings.xml +++ b/androidApp/app/src/main/res/values-es/strings.xml @@ -227,4 +227,53 @@ La aplicación no pudo guardar una copia del archivo. Compruebe que el teléfono tiene espacio libre. copia Base eliminada de ChessPenguin + + Análisis de la partida + Informe de la partida + El motor evalúa cada posición de la línea principal. La partida en sí no cambia. + Calidad + Rápido + Normal + Profundo + %d s + %d min + Analizar + Completar + Analizar de nuevo + Ya hay %1$d de %2$d posiciones evaluadas. + Análisis · %1$d de %2$d + Detener el análisis + Precisión + Precisión: blancas %1$s, negras %2$s + Informe + era mejor %1$s + Imprecisión + Error + Error grave + Imprecisiones + Errores + Errores graves + Sin evaluar: %d + El análisis se interrumpió + Continuar + Pérdida media de centipeones + Apertura + Medio juego + Final + %1$s · %2$s nodos por jugada + Evaluaciones del PGN ([%eval]) + Ocultar el análisis + Gráfico de evaluación + En pausa: se está analizando la partida + Mejor línea · jugada %1$d de %2$d + Ir a la siguiente jugada así + Mostrar la mejor línea en el tablero + Empezar de nuevo + %1$s, evaluación %2$s + Posición inicial + + %1$d posición, unos %2$s + %1$d posiciones, unos %2$s + %1$d posiciones, unos %2$s + diff --git a/androidApp/app/src/main/res/values-fr/strings.xml b/androidApp/app/src/main/res/values-fr/strings.xml index 80e3d22..2ecb523 100644 --- a/androidApp/app/src/main/res/values-fr/strings.xml +++ b/androidApp/app/src/main/res/values-fr/strings.xml @@ -227,4 +227,53 @@ L’application n’a pas pu garder une copie du fichier. Vérifiez qu’il reste de la place sur le téléphone. copie Base supprimée de ChessPenguin + + Analyse de la partie + Rapport de la partie + Le moteur évalue chaque position de la ligne principale. La partie elle-même n\'est pas modifiée. + Qualité + Rapide + Normal + Approfondi + %d s + %d min + Analyser + Compléter + Analyser de nouveau + %1$d positions sur %2$d sont déjà évaluées. + Analyse · %1$d sur %2$d + Arrêter l\'analyse + Précision + Précision : Blancs %1$s, Noirs %2$s + Rapport + %1$s était meilleur + Imprécision + Erreur + Gaffe + Imprécisions + Erreurs + Gaffes + Non évaluées : %d + L\'analyse s\'est interrompue + Continuer + Perte moyenne en centipions + Ouverture + Milieu de partie + Finale + %1$s · %2$s nœuds par coup + Évaluations issues du PGN ([%eval]) + Masquer l\'analyse + Graphique d\'évaluation + En pause : analyse de la partie en cours + Meilleure ligne · coup %1$d sur %2$d + Aller au coup suivant de ce type + Afficher la meilleure ligne sur l\'échiquier + Recommencer + %1$s, évaluation %2$s + Position de départ + + %1$d position, environ %2$s + %1$d positions, environ %2$s + %1$d positions, environ %2$s + diff --git a/androidApp/app/src/main/res/values-it/strings.xml b/androidApp/app/src/main/res/values-it/strings.xml index a13c32c..7ed0c23 100644 --- a/androidApp/app/src/main/res/values-it/strings.xml +++ b/androidApp/app/src/main/res/values-it/strings.xml @@ -227,4 +227,53 @@ L’app non è riuscita a salvare una copia del file. Controlla che sul telefono ci sia spazio libero. copia Database eliminato da ChessPenguin + + Analisi della partita + Resoconto della partita + Il motore valuta ogni posizione della linea principale. La partita non viene modificata. + Qualità + Veloce + Normale + Approfondito + %d s + %d min + Analizza + Completa + Analizza di nuovo + %1$d posizioni su %2$d sono già valutate. + Analisi · %1$d di %2$d + Interrompi l\'analisi + Precisione + Precisione: Bianco %1$s, Nero %2$s + Resoconto + era meglio %1$s + Imprecisione + Errore + Svarione + Imprecisioni + Errori + Svarioni + Non valutate: %d + L\'analisi si è interrotta + Continua + Perdita media in centipedoni + Apertura + Mediogioco + Finale + %1$s · %2$s nodi per mossa + Valutazioni dal PGN ([%eval]) + Nascondi l\'analisi + Grafico di valutazione + In pausa: analisi della partita in corso + Linea migliore · mossa %1$d di %2$d + Vai alla prossima mossa di questo tipo + Mostra la linea migliore sulla scacchiera + Ricomincia + %1$s, valutazione %2$s + Posizione iniziale + + %1$d posizione, circa %2$s + %1$d posizioni, circa %2$s + %1$d posizioni, circa %2$s + diff --git a/androidApp/app/src/main/res/values-ru/strings.xml b/androidApp/app/src/main/res/values-ru/strings.xml index 2dd26cd..71e1498 100644 --- a/androidApp/app/src/main/res/values-ru/strings.xml +++ b/androidApp/app/src/main/res/values-ru/strings.xml @@ -231,4 +231,54 @@ Приложению не удалось сохранить копию файла. Проверьте, есть ли на телефоне свободное место. копия База удалена из ChessPenguin + + Анализ партии + Отчёт по партии + Движок оценит каждую позицию основной линии. Сама партия не изменится. + Качество + Быстро + Обычно + Глубоко + %d с + %d мин + Анализировать + Дополнить + Анализировать заново + Уже оценено позиций: %1$d из %2$d. + Анализ партии · %1$d из %2$d + Остановить анализ + Точность + Точность: белые %1$s, чёрные %2$s + Отчёт + лучше было %1$s + Неточность + Ошибка + Зевок + Неточности + Ошибки + Зевки + Без оценки: %d + Анализ прервался + Продолжить + Средняя потеря сантипешек + Дебют + Миттельшпиль + Эндшпиль + %1$s · %2$s узлов на ход + Оценки из PGN ([%eval]) + Скрыть анализ + График оценки + Пауза: идёт анализ партии + Лучшая линия · ход %1$d из %2$d + Перейти к следующему такому ходу + Показать лучшую линию на доске + Заново + %1$s, оценка %2$s + Начальная позиция + + Позиций: %1$d, примерно %2$s + Позиций: %1$d, примерно %2$s + Позиций: %1$d, примерно %2$s + Позиций: %1$d, примерно %2$s + diff --git a/androidApp/app/src/main/res/values/strings.xml b/androidApp/app/src/main/res/values/strings.xml index 27ab296..ed2d0e7 100644 --- a/androidApp/app/src/main/res/values/strings.xml +++ b/androidApp/app/src/main/res/values/strings.xml @@ -226,4 +226,52 @@ The app could not keep a copy of the file. Check that the phone has free space. copy Database deleted from ChessPenguin + + Game analysis + Game report + The engine evaluates every position of the main line. The game itself is not changed. + Quality + Fast + Normal + Deep + %d s + %d min + Analyse + Fill in + Analyse again + %1$d of %2$d positions are evaluated already. + Game analysis · %1$d of %2$d + Stop the analysis + Accuracy + Accuracy: White %1$s, Black %2$s + Report + %1$s was better + Inaccuracy + Mistake + Blunder + Inaccuracies + Mistakes + Blunders + Not evaluated: %d + The analysis stopped + Continue + Average centipawn loss + Opening + Middlegame + Endgame + %1$s · %2$s nodes per move + Evaluations from the PGN ([%eval]) + Hide analysis + Evaluation graph + Paused: the game is being analysed + Better line · move %1$d of %2$d + Go to the next such move + Show the better line on the board + Start over + %1$s, evaluation %2$s + Start position + + %1$d position, about %2$s + %1$d positions, about %2$s + diff --git a/apps/desktop/Cargo.toml b/apps/desktop/Cargo.toml index 9144852..c2a28cc 100644 --- a/apps/desktop/Cargo.toml +++ b/apps/desktop/Cargo.toml @@ -11,6 +11,7 @@ license.workspace = true [dependencies] chess-core.workspace = true +game-review.workspace = true chess-import.workspace = true shakmaty.workspace = true uci.workspace = true diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index ff71e8d..2cececa 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -209,7 +209,7 @@ impl GameView { MoveKind::Null => return None, }; if self.review.visible - && let Some(mark) = self.review.marks.get(&self.cursor) + && let Some(mark) = self.review.analysis.marks.get(&self.cursor) { return Some(board::Badge { square, @@ -853,7 +853,7 @@ impl GameView { game: &self.game, cursor: self.cursor, scroll_to_cursor: self.scroll_to_cursor, - marks: self.review.visible.then_some(&self.review.marks), + marks: self.review.visible.then_some(&self.review.analysis.marks), preview: self .preview .as_ref() @@ -865,7 +865,7 @@ impl GameView { self.goto(id); } if let Some((id, shown)) = resp.best - && let Some(mark) = self.review.marks.get(&id) + && let Some(mark) = self.review.analysis.marks.get(&id) && let Some(root) = self.game.position(mark.base) && !mark.best.is_empty() { @@ -1240,7 +1240,7 @@ impl GameView { .game .mainline() .into_iter() - .find_map(|id| self.review.marks.get(&id).cloned()); + .find_map(|id| self.review.analysis.marks.get(&id).cloned()); if let Some(mark) = mark && let Some(root) = self.game.position(mark.base) && !mark.best.is_empty() diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index c298f50..7cc1c5a 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -5889,7 +5889,6 @@ mod tests { include_str!("online_ui.rs"), include_str!("update.rs"), include_str!("update_ui.rs"), - include_str!("report.rs"), include_str!("board.rs"), include_str!("engine_download.rs"), include_str!("main.rs"), @@ -5961,7 +5960,6 @@ mod tests { include_str!("online_ui.rs"), include_str!("update.rs"), include_str!("update_ui.rs"), - include_str!("report.rs"), include_str!("board.rs"), include_str!("engine_download.rs"), include_str!("main.rs"), diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index 6e327ad..b62f615 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -20,7 +20,6 @@ mod notation; mod online; mod online_ui; mod reference; -mod report; mod review; mod san; mod settings; diff --git a/apps/desktop/src/review.rs b/apps/desktop/src/review.rs index c874988..a6a5699 100644 --- a/apps/desktop/src/review.rs +++ b/apps/desktop/src/review.rs @@ -1,5 +1,7 @@ -//! Whole-game analysis: a background engine job over the main line, cached results, -//! the evaluation graph under the board, the report tab and the launch dialog. +//! Whole-game analysis on the desktop: the background engine job over the main line, +//! the evaluation graph under the board, the report tab and the launch dialog. The +//! evaluations, judgements, cache and the job itself are the `game-review` crate's, +//! shared with the Android app. //! //! The job uses its own engine process and never touches the game; writing the results //! into the game is a separate, undoable action ([`Review::write_to_game`]). @@ -8,63 +10,18 @@ use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc::{Receiver, Sender, channel}; -use std::time::{Duration, Instant}; +use std::sync::mpsc::{Receiver, channel}; -use chess_core::shakmaty::san::SanPlus; -use chess_core::shakmaty::uci::UciMove; -use chess_core::shakmaty::{Chess, Color, Move, Position}; -use chess_core::{Annotation, CommentPart, Game, Nag, NodeId, parse_comment}; +use chess_core::shakmaty::{Color, Move}; +use chess_core::{Game, Nag, NodeId}; use egui::{Color32, RichText, Sense, Stroke, Ui, pos2, vec2}; -use serde::{Deserialize, Serialize}; -use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits, Side}; +use game_review::{Eval, GameAnalysis, JobEvent, JobFailure, JobSettings, Judgement, ReviewMeta}; + +pub use game_review::Mark; use crate::i18n::{tr, trf}; -use crate::report::{Eval, Judgement, Phases, Ply, Report}; use crate::settings::{EngineConfig, REVIEW_QUALITY, ReviewSettings, Settings}; -/// Engine result for one position of the main line. -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct PosEval { - pub eval: Eval, - /// Principal variation in UCI; the first move is the engine's best move. - #[serde(default)] - pub pv: Vec, - #[serde(default)] - pub depth: u32, -} - -/// Where the evaluations came from. -#[derive(Clone, Debug, Default, Serialize, Deserialize)] -pub struct ReviewMeta { - pub engine: String, - /// Nodes per position; 0 = read from `[%eval]` comments of the PGN. - pub nodes: u64, -} - -#[derive(Serialize, Deserialize)] -struct CacheFile { - version: u32, - meta: ReviewMeta, - evals: Vec<(String, PosEval)>, -} - -const CACHE_VERSION: u32 = 1; -/// A node-limited search should never take this long; stop it if it does. -const SEARCH_GUARD: Duration = Duration::from_secs(300); - -/// An engine assessment of a main-line move, shown over the notation. -#[derive(Clone, Debug)] -pub struct Mark { - pub judgement: Judgement, - /// Node before the move (where the better line starts). - pub base: NodeId, - pub best: Vec, - pub best_san: Vec, - /// "23…Nf6". - pub best_label: Option, -} - pub enum ReportAction { Goto(NodeId), Write, @@ -78,19 +35,8 @@ pub enum DialogAction { OpenEngines, } -struct Target { - key: String, - pos: EnginePosition, - turn: Side, -} - enum JobMsg { - Engine(String), - Eval { - key: String, - eval: PosEval, - nps: u64, - }, + Event(JobEvent), Done, Failed(String), } @@ -110,8 +56,8 @@ impl Drop for Job { } pub struct Review { - evals: HashMap, - pub meta: Option, + /// Evaluations of the main line and the report built from them. + pub analysis: GameAnalysis, job: Option, pub error: Option, /// Graph and report tab are shown. @@ -119,51 +65,31 @@ pub struct Review { pub dialog_open: bool, /// Measured engine speed per thread, for time estimates. nps_per_thread: Option, - built_rev: Option, - dirty: bool, - /// Root and main-line nodes: the analysed positions. - line: Vec, - keys: Vec, - /// Side making each move of the line. - movers: Vec, - /// Evaluation per position (engine result or a terminal position). - values: Vec>, - pub report: Report, - pub marks: HashMap, /// Report tab: index of the last visited error per side and kind. cycle: HashMap<(Color, Judgement), usize>, } +/// The folder of the cached analyses. +fn cache_dir() -> Option { + Settings::cache_dir().map(|d| d.join("analysis")) +} + impl Review { pub fn new(game: &Game) -> Self { - let mut r = Review { - evals: HashMap::new(), - meta: None, + let analysis = GameAnalysis::new(game, cache_dir().as_deref()); + Review { + visible: analysis.has_data(), + analysis, job: None, error: None, - visible: false, dialog_open: false, nps_per_thread: None, - built_rev: None, - dirty: false, - line: Vec::new(), - keys: Vec::new(), - movers: Vec::new(), - values: Vec::new(), - report: Report::default(), - marks: HashMap::new(), cycle: HashMap::new(), - }; - r.rebuild(game); - if r.load_cache() || r.load_pgn_evals(game) { - r.rebuild(game); - r.visible = true; } - r } pub fn has_data(&self) -> bool { - !self.evals.is_empty() + self.analysis.has_data() } pub fn running(&self) -> bool { @@ -176,78 +102,12 @@ impl Review { /// Positions of the current main line without an evaluation. pub fn missing(&self) -> usize { - self.values.iter().filter(|v| v.is_none()).count() + self.analysis.missing() } /// Re-derives the report when the game or the evaluations changed. Cheap otherwise. pub fn refresh(&mut self, game: &Game) { - if self.dirty || self.built_rev != Some(game.revision()) { - self.rebuild(game); - } - } - - fn rebuild(&mut self, game: &Game) { - self.line = std::iter::once(NodeId::ROOT) - .chain(game.mainline()) - .collect(); - let positions: Vec = self - .line - .iter() - .filter_map(|id| game.position(*id).cloned()) - .collect(); - self.keys = self - .line - .iter() - .map(|id| position_key(game, *id).map(|k| k.0).unwrap_or_default()) - .collect(); - self.values = (0..self.line.len()) - .map(|i| { - self.evals - .get(&self.keys[i]) - .map(|e| e.eval) - .or_else(|| positions.get(i).and_then(terminal_eval)) - }) - .collect(); - let mut plies = Vec::with_capacity(self.line.len().saturating_sub(1)); - for i in 1..self.line.len() { - let mv = game.game_move(self.line[i]); - let best = self.evals.get(&self.keys[i - 1]).and_then(|e| e.pv.first()); - plies.push(Ply { - mover: positions.get(i - 1).map_or(Color::White, |p| p.turn()), - null: mv.is_none_or(|m| m.is_null()), - best: best.is_some() && mv.and_then(|m| m.uci()).as_ref() == best, - }); - } - self.movers = plies.iter().map(|p| p.mover).collect(); - self.report = Report::build(&self.values, &plies, Phases::divide(&positions)); - self.marks.clear(); - for (i, j) in self.report.judgements.iter().enumerate() { - let Some(judgement) = *j else { continue }; - let (base, node) = (self.line[i], self.line[i + 1]); - let (best, best_san) = match (self.evals.get(&self.keys[i]), positions.get(i)) { - (Some(e), Some(root)) => parse_pv(root, &e.pv), - _ => (Vec::new(), Vec::new()), - }; - let best_label = best_san.first().and_then(|san| { - let (num, color) = game.move_number(node)?; - Some(match color { - Color::White => format!("{num}.{san}"), - Color::Black => format!("{num}…{san}"), - }) - }); - self.marks.insert( - node, - Mark { - judgement, - base, - best, - best_san, - best_label, - }, - ); - } - self.built_rev = Some(game.revision()); - self.dirty = false; + self.analysis.refresh(game); } /// Starts the engine job. `full` discards earlier results; otherwise only positions @@ -266,41 +126,46 @@ impl Review { self.error = Some(tr("The built-in engine is not part of this build").into()); return false; }; - if full { - self.evals.clear(); - self.dirty = true; - } - self.meta = Some(ReviewMeta { + let meta = ReviewMeta { engine: engine.name.clone(), nodes: rs.nodes(), - }); - self.rebuild(game); - let targets: Vec = (0..self.line.len()) - .filter(|i| self.values[*i].is_none()) - .filter_map(|i| { - let (key, pos) = position_key(game, self.line[i])?; - let turn = match game.position(self.line[i])?.turn() { - Color::White => Side::White, - Color::Black => Side::Black, - }; - Some(Target { key, pos, turn }) - }) - .collect(); + }; + let targets = self.analysis.begin(game, meta, full); if targets.is_empty() { return false; } let (tx, rx) = channel(); let cancel = Arc::new(AtomicBool::new(false)); let total = targets.len(); - let (path, threads, hash, nodes) = (path, rs.threads.max(1), rs.hash_mb, rs.nodes()); + // Filling in keeps the quality of the earlier run (see `GameAnalysis::begin`). + let nodes = self.analysis.meta.as_ref().map_or(rs.nodes(), |m| m.nodes); + let settings = JobSettings { + threads: rs.threads.max(1), + hash_mb: rs.hash_mb, + nodes, + eval_file: None, + }; + let threads = settings.threads; let (cancel_w, ctx_w) = (cancel.clone(), ctx.clone()); let spawned = std::thread::Builder::new() .name("game-review".into()) .spawn(move || { - let msg = match run_job(path, threads, hash, nodes, targets, &tx, &cancel_w, &ctx_w) - { + let result = game_review::run( + uci::EngineConfig::new(&path), + &settings, + targets, + &cancel_w, + &mut |e| { + let _ = tx.send(JobMsg::Event(e)); + ctx_w.request_repaint(); + }, + ); + let msg = match result { Ok(()) => JobMsg::Done, - Err(e) => JobMsg::Failed(e), + Err(JobFailure::Start(e) | JobFailure::Engine(e)) => JobMsg::Failed(e), + Err(JobFailure::Terminated(reason)) => { + JobMsg::Failed(crate::analysis::termination_message(&reason)) + } }; let _ = tx.send(msg); ctx_w.request_repaint(); @@ -334,18 +199,14 @@ impl Review { let mut ended = false; while let Ok(msg) = job.rx.try_recv() { match msg { - JobMsg::Engine(name) => { - if let Some(m) = &mut self.meta { - m.engine = name; + JobMsg::Event(e) => { + if let JobEvent::Eval { nps, .. } = &e { + job.done += 1; + if *nps > 0 { + self.nps_per_thread = Some(*nps as f64 / f64::from(job.threads)); + } } - } - JobMsg::Eval { key, eval, nps } => { - job.done += 1; - if nps > 0 { - self.nps_per_thread = Some(nps as f64 / f64::from(job.threads)); - } - self.evals.insert(key, eval); - self.dirty = true; + self.analysis.apply(e); } JobMsg::Done => ended = true, JobMsg::Failed(e) => { @@ -369,138 +230,17 @@ impl Review { } /// After an inaccuracy, mistake or blunder: how the opponent punishes it and how - /// the player best answers, the first two moves of the engine line from the position - /// after the move (shown as arrows, as on Lichess). + /// the player best answers (shown as arrows, as on Lichess). pub fn refutation(&self, node: NodeId, game: &Game) -> Vec { - if !self.marks.contains_key(&node) { - return Vec::new(); - } - let (Some(i), Some(pos)) = ( - self.line.iter().position(|n| *n == node), - game.position(node), - ) else { - return Vec::new(); - }; - let Some(e) = self.keys.get(i).and_then(|k| self.evals.get(k)) else { - return Vec::new(); - }; - let (mut moves, _) = parse_pv(pos, &e.pv); - moves.truncate(2); - moves - } - - // ----- cache ----------------------------------------------------------------- - - fn cache_path(&self) -> Option { - let mut h: u64 = 0xcbf2_9ce4_8422_2325; - for k in &self.keys { - for b in k.bytes().chain(std::iter::once(b'\n')) { - h ^= u64::from(b); - h = h.wrapping_mul(0x0100_0000_01b3); - } - } - Some( - Settings::cache_dir()? - .join("analysis") - .join(format!("{h:016x}.json")), - ) + self.analysis.refutation(node, game) } fn save_cache(&self) { - let Some(meta) = self.meta.clone().filter(|m| m.nodes > 0) else { - return; - }; - if self.evals.is_empty() { - return; + if let Some(dir) = cache_dir() + && let Err(e) = self.analysis.save_cache(&dir) + { + eprintln!("review cache: {}: {e}", dir.display()); } - let Some(path) = self.cache_path() else { - return; - }; - let file = CacheFile { - version: CACHE_VERSION, - meta, - evals: self - .evals - .iter() - .map(|(k, v)| (k.clone(), v.clone())) - .collect(), - }; - match serde_json::to_vec(&file) { - Ok(bytes) => { - if let Err(e) = crate::settings::write_atomic(&path, &bytes) { - eprintln!("review cache: {}: {e}", path.display()); - } - } - Err(e) => eprintln!("review cache: {e}"), - } - } - - fn load_cache(&mut self) -> bool { - let Some(bytes) = self.cache_path().and_then(|p| std::fs::read(p).ok()) else { - return false; - }; - let Ok(file) = serde_json::from_slice::(&bytes) else { - return false; - }; - if file.version != CACHE_VERSION || file.evals.is_empty() { - return false; - } - self.meta = Some(file.meta); - self.evals = file.evals.into_iter().collect(); - true - } - - /// Uses `[%eval]` comments (Lichess exports, or our own written analysis) when every - /// main-line move has one. - fn load_pgn_evals(&mut self, game: &Game) -> bool { - let mut found = Vec::new(); - for (i, id) in self.line.iter().enumerate().skip(1) { - let Some(node) = game.node(*id) else { - return false; - }; - let e = node - .comments_after() - .iter() - .flat_map(|c| parse_comment(c)) - .find_map(|p| match p { - CommentPart::Annotation(Annotation::Other { name, payload }) - if name == "eval" => - { - Eval::parse_pgn(&payload) - } - _ => None, - }); - match e { - Some(e) => found.push((i, e)), - None if self.values[i].is_some() => {} - None => return false, - } - } - let Some(&(_, first)) = found.first() else { - return false; - }; - // The start position carries no comment: Lichess assumes +0.15 for the initial one. - let root = if game.start().is_standard() { - Eval::Cp(15) - } else { - first - }; - found.insert(0, (0, root)); - for (i, eval) in found { - self.evals.insert( - self.keys[i].clone(), - PosEval { - eval, - pv: Vec::new(), - depth: 0, - }, - ); - } - self.meta = Some(ReviewMeta { - engine: "PGN".into(), - nodes: 0, - }); - true } // ----- writing into the game ------------------------------------------------- @@ -511,8 +251,8 @@ impl Review { pub fn write_to_game(&self, game: &mut Game) -> usize { game.edit_group(|g| { let mut errors = 0; - for i in 1..self.line.len() { - let id = self.line[i]; + for i in 1..self.analysis.line().len() { + let id = self.analysis.line()[i]; let Some(node) = g.node(id) else { continue }; let mut nags = node.nags().to_vec(); let mut comments: Vec = node @@ -521,12 +261,12 @@ impl Review { .map(|c| strip_eval(c)) .filter(|c| !c.trim().is_empty()) .collect(); - if let Some(e) = self.values[i] + if let Some(e) = self.analysis.values()[i] && !matches!(e, Eval::Mate { moves: 0, .. }) { comments.insert(0, format!("[%eval {}]", e.pgn())); } - if let Some(mark) = self.marks.get(&id) { + if let Some(mark) = self.analysis.marks.get(&id) { errors += 1; if !nags.iter().any(|n| n.is_move_assessment()) { nags.push(match mark.judgement { @@ -571,7 +311,7 @@ impl Review { let painter = ui.painter_at(rect); let visuals = ui.visuals(); painter.rect_filled(rect, 4.0, visuals.extreme_bg_color); - let n = self.values.len(); + let n = self.analysis.values().len(); if n < 2 { return None; } @@ -580,7 +320,8 @@ impl Review { let y_of = |wp: f64| inner.bottom() - inner.height() * (wp / 100.0) as f32; let mid = y_of(50.0); let wp: Vec> = self - .values + .analysis + .values() .iter() .map(|v| v.map(|e| e.win_percent(Color::White))) .collect(); @@ -609,12 +350,18 @@ impl Review { visuals.weak_text_color(), ); }; - if self.report.phases.middlegame.is_some_and(|m| m > 0) { + if self + .analysis + .report + .phases + .middlegame + .is_some_and(|m| m > 0) + { label(inner.left(), tr("Opening")); } for (idx, name) in [ - (self.report.phases.middlegame, tr("Middlegame")), - (self.report.phases.endgame, tr("Endgame")), + (self.analysis.report.phases.middlegame, tr("Middlegame")), + (self.analysis.report.phases.endgame, tr("Endgame")), ] { if let Some(i) = idx { let x = x_of(i); @@ -673,7 +420,7 @@ impl Review { if run.len() > 1 { painter.add(egui::Shape::line(run, curve)); } - for (i, j) in self.report.judgements.iter().enumerate() { + for (i, j) in self.analysis.report.judgements.iter().enumerate() { if let (Some(j), Some(w)) = (j, wp[i + 1]) { painter.circle_filled(pos2(x_of(i + 1), y_of(w)), 3.5, judgement_color(*j)); } @@ -707,12 +454,14 @@ impl Review { let label = if i == 0 { tr("Start position").to_string() } else { - crate::san::show(&game.move_label(self.line[i]).unwrap_or_default()).into_owned() + crate::san::show(&game.move_label(self.analysis.line()[i]).unwrap_or_default()) + .into_owned() }; - let eval = self.values[i] + let eval = self.analysis.values()[i] .map(Eval::format) .unwrap_or_else(|| "…".into()); let mark = self + .analysis .report .judgements .get(i.wrapping_sub(1)) @@ -731,7 +480,7 @@ impl Review { if (resp.clicked() || resp.dragged()) && let Some(p) = resp.interact_pointer_pos() { - let target = self.line[index_at(p.x)]; + let target = self.analysis.line()[index_at(p.x)]; if target != cursor { return Some(target); } @@ -741,13 +490,7 @@ impl Review { /// Index in the main line of `cursor`, or of the main-line move a variation leaves from. fn line_index(&self, cursor: NodeId, game: &Game) -> Option { - let mut id = cursor; - loop { - if let Some(i) = self.line.iter().position(|n| *n == id) { - return Some(i); - } - id = game.parent(id)?; - } + self.analysis.line_index(cursor, game) } /// Report tab: per-player statistics in the Lichess layout. @@ -761,7 +504,7 @@ impl Review { ui.add_space(10.0); } ui.separator(); - if let Some(meta) = &self.meta { + if let Some(meta) = &self.analysis.meta { let source = if meta.nodes == 0 { tr("Evaluations from the PGN ([%eval])").to_string() } else { @@ -785,7 +528,7 @@ impl Review { RichText::new(trf("Positions without evaluation: {n}", &[("n", &missing)])) .color(ui.visuals().warn_fg_color), ); - let can_update = self.meta.as_ref().is_some_and(|m| m.nodes > 0); + let can_update = self.analysis.meta.as_ref().is_some_and(|m| m.nodes > 0); if can_update && ui.button(tr("Update")).clicked() { action = Some(ReportAction::Update); } @@ -842,7 +585,7 @@ impl Review { } ui.label(RichText::new(name).strong().size(16.0)); }); - let s = self.report.side(color).clone(); + let s = self.analysis.report.side(color).clone(); egui::Grid::new(("review_side", color as u8)) .num_columns(2) .spacing(vec2(10.0, 3.0)) @@ -919,14 +662,7 @@ impl Review { /// Next main-line move of `color` with judgement `j` (cycles). fn next_error(&mut self, color: Color, j: Judgement) -> Option { - let hits: Vec = self - .report - .judgements - .iter() - .enumerate() - .filter(|(i, x)| **x == Some(j) && self.movers.get(*i) == Some(&color)) - .map(|(i, _)| self.line[i + 1]) - .collect(); + let hits = self.analysis.errors(color, j); if hits.is_empty() { return None; } @@ -1020,11 +756,7 @@ impl Review { ui.end_row(); }); ui.add_space(6.0); - let positions = self - .values - .iter() - .filter(|v| !matches!(v, Some(Eval::Mate { moves: 0, .. }))) - .count(); + let positions = self.analysis.positions(); let per_thread = self.nps_per_thread.unwrap_or(700_000.0); let secs = positions as f64 * rs.nodes() as f64 / (per_thread * f64::from(rs.threads)); ui.label(trf( @@ -1076,136 +808,6 @@ impl Drop for Review { } } -#[allow(clippy::too_many_arguments)] -fn run_job( - path: PathBuf, - threads: u32, - hash_mb: u32, - nodes: u64, - targets: Vec, - tx: &Sender, - cancel: &AtomicBool, - ctx: &egui::Context, -) -> Result<(), String> { - let handle = uci::Engine::spawn_with(uci::EngineConfig::new(&path), Box::new(|| {})) - .map_err(|e| e.to_string())?; - if let Some(name) = &handle.info().name { - let _ = tx.send(JobMsg::Engine(name.clone())); - } - // Unknown options are not fatal: some engines lack Threads/Hash/MultiPV. - let _ = handle.set_threads(threads); - let _ = handle.set_hash_mb(hash_mb); - let _ = handle.set_multipv(1); - let _ = handle.new_game(); - for (i, t) in targets.into_iter().enumerate() { - let id = SearchId(i as u64 + 1); - handle - .search(t.pos.clone(), id, SearchLimits::Nodes(nodes)) - .map_err(|e| e.to_string())?; - let started = Instant::now(); - let mut stopping = false; - let mut last: Option = None; - loop { - if cancel.load(Ordering::Relaxed) { - handle.quit(); - return Ok(()); - } - if !stopping && started.elapsed() > SEARCH_GUARD { - let _ = handle.stop(); - stopping = true; - } - match handle.recv_timeout(Duration::from_millis(100)) { - Some(EngineEvent::Info { search_id, info }) if search_id == id => { - if info.multipv_index() == 1 && info.score.is_some() { - let exact = info.score.is_some_and(|s| s.bound == ScoreBound::Exact); - if exact || last.is_none() { - last = Some(info); - } - } - } - Some(EngineEvent::BestMove { - search_id, best, .. - }) if search_id == id => { - if let Some(info) = last.take() - && let Some(score) = info.score - { - let eval = Eval::from_white_eval(score.to_white(t.turn).eval); - let mut pv: Vec = info.pv.iter().take(12).cloned().collect(); - if let Some(b) = best - && pv.first() != Some(&b) - { - pv = vec![b]; - } - let _ = tx.send(JobMsg::Eval { - key: t.key, - eval: PosEval { - eval, - pv, - depth: info.depth.unwrap_or(0), - }, - nps: info.nps.unwrap_or(0), - }); - ctx.request_repaint(); - } - break; - } - Some(EngineEvent::Terminated(reason)) => { - return Err(crate::analysis::termination_message(&reason)); - } - _ => {} - } - } - } - handle.quit(); - Ok(()) -} - -/// Cache key and UCI position of a node (full history, see [`Game::engine_history`]). -fn position_key(game: &Game, id: NodeId) -> Option<(String, EnginePosition)> { - let h = game.engine_history(id)?; - let key = format!( - "{}|{}", - h.start_fen.as_deref().unwrap_or("startpos"), - h.moves.join(" ") - ); - let pos = match h.start_fen { - None => EnginePosition::startpos(h.moves), - Some(fen) => EnginePosition::fen(fen, h.moves), - }; - Some((key, pos)) -} - -/// Evaluation of a position without legal moves. -fn terminal_eval(pos: &Chess) -> Option { - if pos.is_checkmate() { - Some(Eval::Mate { - white: pos.turn() == Color::Black, - moves: 0, - }) - } else if pos.is_stalemate() { - Some(Eval::Cp(0)) - } else { - None - } -} - -fn parse_pv(root: &Chess, pv: &[String]) -> (Vec, Vec) { - let mut pos = root.clone(); - let (mut moves, mut san) = (Vec::new(), Vec::new()); - for u in pv { - let Some(m) = u - .parse::() - .ok() - .and_then(|um| um.to_move(&pos).ok()) - else { - break; - }; - san.push(SanPlus::from_move_and_play_unchecked(&mut pos, m).to_string()); - moves.push(m); - } - (moves, san) -} - /// Removes `[%eval …]` commands from a comment. fn strip_eval(c: &str) -> String { let mut out = String::new(); @@ -1327,17 +929,17 @@ mod tests { let mut r = Review::new(&game); assert!(r.has_data() && r.visible); assert_eq!(r.missing(), 0); - assert!(r.report.complete); + assert!(r.analysis.report.complete); // 2…Ke7 throws the game away; 3.Qxe5# is a terminal position. let ke7 = game.mainline()[3]; assert_eq!( - r.marks.get(&ke7).map(|m| m.judgement), + r.analysis.marks.get(&ke7).map(|m| m.judgement), Some(Judgement::Blunder) ); - assert_eq!(r.report.black.blunders, 1); + assert_eq!(r.analysis.report.black.blunders, 1); let errors = r.write_to_game(&mut game); - assert_eq!(errors, r.marks.len()); + assert_eq!(errors, r.analysis.marks.len()); let node = game.node(ke7).expect("node"); assert!(node.nags().contains(&Nag::BLUNDER)); assert!(node.comments_after()[0].starts_with("[%eval 6.50]")); diff --git a/crates/game-review/Cargo.toml b/crates/game-review/Cargo.toml new file mode 100644 index 0000000..44a1452 --- /dev/null +++ b/crates/game-review/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "game-review" +description = "Whole-game analysis of ChessPenguin: engine evaluations of the main line, move judgements, accuracy (the desktop and Android apps share it)" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[dependencies] +chess-core.workspace = true +shakmaty.workspace = true +uci.workspace = true +serde.workspace = true +serde_json.workspace = true diff --git a/crates/game-review/src/job.rs b/crates/game-review/src/job.rs new file mode 100644 index 0000000..1e98c4d --- /dev/null +++ b/crates/game-review/src/job.rs @@ -0,0 +1,211 @@ +//! The engine job of a game analysis: its own engine process, one node-limited search +//! per position, results reported as they come. Runs on the caller's thread until it +//! is done or cancelled; the game is never touched. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits, Side}; + +use crate::{Eval, PosEval}; + +/// A node-limited search should never take this long; stop it if it does. +const SEARCH_GUARD: Duration = Duration::from_secs(300); + +/// A position to evaluate (from [`crate::GameAnalysis::begin`]). +#[derive(Clone, Debug)] +pub struct Target { + pub key: String, + pub pos: EnginePosition, + pub turn: Side, +} + +/// How the engine searches. +#[derive(Clone, Debug)] +pub struct JobSettings { + pub threads: u32, + pub hash_mb: u32, + /// Nodes per position. + pub nodes: u64, + /// The network file of the engine (Stockfish `EvalFile`), when it is not beside it. + pub eval_file: Option, +} + +/// What the job reports, for [`crate::GameAnalysis::apply`]. +#[derive(Clone, Debug)] +pub enum JobEvent { + /// The engine's own name. + Engine(String), + Eval { + key: String, + eval: PosEval, + /// The engine's speed in this search (0 if it did not say). + nps: u64, + }, +} + +/// Why the job stopped before the end. +#[derive(Debug)] +pub enum JobFailure { + /// The engine did not start or did not accept its settings. + Start(String), + /// Talking to the engine failed. + Engine(String), + /// The engine process ended (crashed, or hung and was killed). + Terminated(uci::TerminationReason), +} + +/// Evaluates `targets` one by one; `on_event` gets every result. Returns when all are +/// done, or soon after `cancel` is set (then with `Ok`). +pub fn run( + config: uci::EngineConfig, + settings: &JobSettings, + targets: Vec, + cancel: &AtomicBool, + on_event: &mut dyn FnMut(JobEvent), +) -> Result<(), JobFailure> { + let handle = uci::Engine::spawn_with(config, Box::new(|| {})) + .map_err(|e| JobFailure::Start(e.to_string()))?; + if let Some(name) = &handle.info().name { + on_event(JobEvent::Engine(name.clone())); + } + if let Some(file) = &settings.eval_file { + handle + .set_option("EvalFile", Some(file)) + .map_err(|e| JobFailure::Start(e.to_string()))?; + } + // Unknown options are not fatal: some engines lack Threads/Hash/MultiPV. + let _ = handle.set_threads(settings.threads.max(1)); + let _ = handle.set_hash_mb(settings.hash_mb.max(1)); + let _ = handle.set_multipv(1); + let _ = handle.new_game(); + for (i, t) in targets.into_iter().enumerate() { + let id = SearchId(i as u64 + 1); + handle + .search(t.pos.clone(), id, SearchLimits::Nodes(settings.nodes)) + .map_err(|e| JobFailure::Engine(e.to_string()))?; + let started = Instant::now(); + let mut stopping = false; + let mut last: Option = None; + loop { + if cancel.load(Ordering::Relaxed) { + handle.quit(); + return Ok(()); + } + if !stopping && started.elapsed() > SEARCH_GUARD { + let _ = handle.stop(); + stopping = true; + } + match handle.recv_timeout(Duration::from_millis(100)) { + Some(EngineEvent::Info { search_id, info }) if search_id == id => { + if info.multipv_index() == 1 && info.score.is_some() { + let exact = info.score.is_some_and(|s| s.bound == ScoreBound::Exact); + if exact || last.is_none() { + last = Some(info); + } + } + } + Some(EngineEvent::BestMove { + search_id, best, .. + }) if search_id == id => { + if let Some(info) = last.take() + && let Some(score) = info.score + { + let eval = Eval::from_white_eval(score.to_white(t.turn).eval); + let mut pv: Vec = info.pv.iter().take(12).cloned().collect(); + if let Some(b) = best + && pv.first() != Some(&b) + { + pv = vec![b]; + } + on_event(JobEvent::Eval { + key: t.key, + eval: PosEval { + eval, + pv, + depth: info.depth.unwrap_or(0), + }, + nps: info.nps.unwrap_or(0), + }); + } + break; + } + Some(EngineEvent::Terminated(reason)) => { + return Err(JobFailure::Terminated(reason)); + } + _ => {} + } + } + } + handle.quit(); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{GameAnalysis, ReviewMeta}; + + /// The fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`) answers + /// like Stockfish: every position gets an evaluation, in order. + #[test] + fn the_job_evaluates_every_position() { + let fake = concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/debug/fake_uci"); + assert!( + std::path::Path::new(fake).exists(), + "build the fake engine first: cargo build -p uci --bin fake_uci" + ); + let game = chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 *").game; + let mut a = GameAnalysis::new(&game, None); + let meta = ReviewMeta { + engine: String::new(), + nodes: 1000, + }; + let targets = a.begin(&game, meta, false); + let n = targets.len(); + let settings = JobSettings { + threads: 1, + hash_mb: 16, + nodes: 1000, + eval_file: None, + }; + let mut evals = 0; + let cancel = AtomicBool::new(false); + run( + uci::EngineConfig::new(fake), + &settings, + targets, + &cancel, + &mut |e| { + if matches!(e, JobEvent::Eval { .. }) { + evals += 1; + } + a.apply(e); + }, + ) + .expect("the job runs"); + assert_eq!(evals, n); + a.refresh(&game); + assert_eq!(a.missing(), 0); + assert!(a.report.complete); + + // A cancelled job ends at once, without results. + let mut b = GameAnalysis::new(&game, None); + let targets = b.begin(&game, ReviewMeta::default(), false); + cancel.store(true, Ordering::Relaxed); + let mut got = 0; + run( + uci::EngineConfig::new(fake), + &settings, + targets, + &cancel, + &mut |e| { + if matches!(e, JobEvent::Eval { .. }) { + got += 1; + } + }, + ) + .expect("cancelled cleanly"); + assert_eq!(got, 0); + } +} diff --git a/crates/game-review/src/lib.rs b/crates/game-review/src/lib.rs new file mode 100644 index 0000000..70f0702 --- /dev/null +++ b/crates/game-review/src/lib.rs @@ -0,0 +1,581 @@ +//! Whole-game analysis, shared by the desktop and the Android app: the engine evaluates +//! every position of the main line, and the evaluations give the move judgements +//! (inaccuracy, mistake, blunder), the accuracy and the evaluation graph. +//! +//! [`GameAnalysis`] holds the evaluations of one game and what follows from them; it +//! never changes the game. [`run`] is the engine job (its own engine process) that +//! produces them. Results are cached per main line, and `[%eval]` comments of the PGN +//! are used without an engine. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use chess_core::shakmaty::san::SanPlus; +use chess_core::shakmaty::uci::UciMove; +use chess_core::shakmaty::{Chess, Color, Move, Position}; +use chess_core::{Annotation, CommentPart, Game, NodeId, parse_comment}; +use serde::{Deserialize, Serialize}; +use uci::{EnginePosition, Side}; + +mod job; +pub mod report; + +pub use job::{JobEvent, JobFailure, JobSettings, Target, run}; +pub use report::{Eval, Judgement, Phase, Phases, Ply, Report, SideStats}; + +/// Engine result for one position of the main line. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct PosEval { + pub eval: Eval, + /// Principal variation in UCI; the first move is the engine's best move. + #[serde(default)] + pub pv: Vec, + #[serde(default)] + pub depth: u32, +} + +/// Where the evaluations came from. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct ReviewMeta { + pub engine: String, + /// Nodes per position; 0 = read from `[%eval]` comments of the PGN. + pub nodes: u64, +} + +#[derive(Serialize, Deserialize)] +struct CacheFile { + version: u32, + meta: ReviewMeta, + evals: Vec<(String, PosEval)>, +} + +const CACHE_VERSION: u32 = 1; + +/// An engine assessment of a main-line move. +#[derive(Clone, Debug)] +pub struct Mark { + pub judgement: Judgement, + /// Node before the move (where the better line starts). + pub base: NodeId, + pub best: Vec, + /// The better line in SAN (Latin letters, as in PGN). + pub best_san: Vec, + /// "23…Nf6". + pub best_label: Option, +} + +/// The evaluations of a game's main line and the report built from them. +pub struct GameAnalysis { + evals: HashMap, + pub meta: Option, + built_rev: Option, + dirty: bool, + /// Root and main-line nodes: the analysed positions. + line: Vec, + keys: Vec, + /// Side making each move of the line. + movers: Vec, + /// Evaluation per position (engine result or a terminal position). + values: Vec>, + /// Positions without legal moves (mate, stalemate): no engine needed. + terminal: Vec, + pub report: Report, + pub marks: HashMap, +} + +impl GameAnalysis { + /// The analysis of `game`: from the cache in `cache_dir` (the folder of the cached + /// analyses) when this main line was analysed before, else from `[%eval]` comments + /// when every move has one, else empty. + pub fn new(game: &Game, cache_dir: Option<&Path>) -> Self { + let mut a = GameAnalysis { + evals: HashMap::new(), + meta: None, + built_rev: None, + dirty: false, + line: Vec::new(), + keys: Vec::new(), + movers: Vec::new(), + values: Vec::new(), + terminal: Vec::new(), + report: Report::default(), + marks: HashMap::new(), + }; + a.rebuild(game); + if cache_dir.is_some_and(|d| a.load_cache(d)) || a.load_pgn_evals(game) { + a.rebuild(game); + } + a + } + + pub fn has_data(&self) -> bool { + !self.evals.is_empty() + } + + /// Root and main-line nodes, in order: index `i` of [`Self::values`] belongs here. + pub fn line(&self) -> &[NodeId] { + &self.line + } + + /// Evaluation per position of [`Self::line`]. + pub fn values(&self) -> &[Option] { + &self.values + } + + /// The side making each move of the line (`movers[i]` plays from position `i`). + pub fn movers(&self) -> &[Color] { + &self.movers + } + + /// The engine result for position `i` of the line, if there is one. + pub fn eval_at(&self, i: usize) -> Option<&PosEval> { + self.keys.get(i).and_then(|k| self.evals.get(k)) + } + + /// Positions of the current main line without an evaluation. + pub fn missing(&self) -> usize { + self.values.iter().filter(|v| v.is_none()).count() + } + + /// Positions an engine would look at in a full analysis (not a final mate or + /// stalemate). + pub fn positions(&self) -> usize { + self.terminal.iter().filter(|t| !**t).count() + } + + /// Re-derives the report when the game or the evaluations changed. Cheap otherwise. + pub fn refresh(&mut self, game: &Game) { + if self.dirty || self.built_rev != Some(game.revision()) { + self.rebuild(game); + } + } + + /// Prepares an engine run: `full` drops the earlier results. Returns the positions + /// without an evaluation, for [`run`]. Filling in an engine analysis keeps its + /// nodes per position, so that one report never mixes two qualities: the run must use + /// `self.meta`'s nodes, not the asked ones. + pub fn begin(&mut self, game: &Game, meta: ReviewMeta, full: bool) -> Vec { + if full { + self.evals.clear(); + } + let nodes = match &self.meta { + Some(old) if !full && old.nodes > 0 && self.has_data() => old.nodes, + _ => meta.nodes, + }; + self.meta = Some(ReviewMeta { nodes, ..meta }); + self.rebuild(game); + (0..self.line.len()) + .filter(|i| self.values[*i].is_none()) + .filter_map(|i| { + let (key, pos) = position_key(game, self.line[i])?; + let turn = match game.position(self.line[i])?.turn() { + Color::White => Side::White, + Color::Black => Side::Black, + }; + Some(Target { key, pos, turn }) + }) + .collect() + } + + /// Takes in what the engine job reported. + pub fn apply(&mut self, event: JobEvent) { + match event { + JobEvent::Engine(name) => { + if let Some(m) = &mut self.meta { + m.engine = name; + } + } + JobEvent::Eval { key, eval, .. } => { + self.evals.insert(key, eval); + self.dirty = true; + } + } + } + + fn rebuild(&mut self, game: &Game) { + self.line = std::iter::once(NodeId::ROOT) + .chain(game.mainline()) + .collect(); + let positions: Vec = self + .line + .iter() + .filter_map(|id| game.position(*id).cloned()) + .collect(); + self.keys = self + .line + .iter() + .map(|id| position_key(game, *id).map(|k| k.0).unwrap_or_default()) + .collect(); + self.terminal = (0..self.line.len()) + .map(|i| positions.get(i).and_then(terminal_eval).is_some()) + .collect(); + self.values = (0..self.line.len()) + .map(|i| { + self.evals + .get(&self.keys[i]) + .map(|e| e.eval) + .or_else(|| positions.get(i).and_then(terminal_eval)) + }) + .collect(); + let mut plies = Vec::with_capacity(self.line.len().saturating_sub(1)); + for i in 1..self.line.len() { + let mv = game.game_move(self.line[i]); + let best = self.evals.get(&self.keys[i - 1]).and_then(|e| e.pv.first()); + plies.push(Ply { + mover: positions.get(i - 1).map_or(Color::White, |p| p.turn()), + null: mv.is_none_or(|m| m.is_null()), + best: best.is_some() && mv.and_then(|m| m.uci()).as_ref() == best, + }); + } + self.movers = plies.iter().map(|p| p.mover).collect(); + self.report = Report::build(&self.values, &plies, Phases::divide(&positions)); + self.marks.clear(); + for (i, j) in self.report.judgements.iter().enumerate() { + let Some(judgement) = *j else { continue }; + let (base, node) = (self.line[i], self.line[i + 1]); + let (best, best_san) = match (self.evals.get(&self.keys[i]), positions.get(i)) { + (Some(e), Some(root)) => parse_pv(root, &e.pv), + _ => (Vec::new(), Vec::new()), + }; + let best_label = best_san.first().and_then(|san| { + let (num, color) = game.move_number(node)?; + Some(match color { + Color::White => format!("{num}.{san}"), + Color::Black => format!("{num}…{san}"), + }) + }); + self.marks.insert( + node, + Mark { + judgement, + base, + best, + best_san, + best_label, + }, + ); + } + self.built_rev = Some(game.revision()); + self.dirty = false; + } + + /// After an inaccuracy, mistake or blunder: how the opponent punishes it and how + /// the player best answers, the first two moves of the engine line from the position + /// after the move (shown as arrows, as on Lichess). + pub fn refutation(&self, node: NodeId, game: &Game) -> Vec { + if !self.marks.contains_key(&node) { + return Vec::new(); + } + let (Some(i), Some(pos)) = ( + self.line.iter().position(|n| *n == node), + game.position(node), + ) else { + return Vec::new(); + }; + let Some(e) = self.eval_at(i) else { + return Vec::new(); + }; + let (mut moves, _) = parse_pv(pos, &e.pv); + moves.truncate(2); + moves + } + + /// Index in the main line of `cursor`, or of the main-line move a variation leaves from. + pub fn line_index(&self, cursor: NodeId, game: &Game) -> Option { + let mut id = cursor; + loop { + if let Some(i) = self.line.iter().position(|n| *n == id) { + return Some(i); + } + id = game.parent(id)?; + } + } + + /// The main-line moves of `color` judged `j`, in order. + pub fn errors(&self, color: Color, j: Judgement) -> Vec { + self.report + .judgements + .iter() + .enumerate() + .filter(|(i, x)| **x == Some(j) && self.movers.get(*i) == Some(&color)) + .map(|(i, _)| self.line[i + 1]) + .collect() + } + + // ----- cache ----------------------------------------------------------------- + + /// The cache file of this main line in `dir`. + fn cache_path(&self, dir: &Path) -> PathBuf { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for k in &self.keys { + for b in k.bytes().chain(std::iter::once(b'\n')) { + h ^= u64::from(b); + h = h.wrapping_mul(0x0100_0000_01b3); + } + } + dir.join(format!("{h:016x}.json")) + } + + /// Keeps engine results in `dir` (nothing for evaluations read from the PGN). + pub fn save_cache(&self, dir: &Path) -> std::io::Result<()> { + let Some(meta) = self.meta.clone().filter(|m| m.nodes > 0) else { + return Ok(()); + }; + // A game without moves has nothing to report, and every such game would share + // this one file. + if self.evals.is_empty() || self.line.len() < 2 { + return Ok(()); + } + let file = CacheFile { + version: CACHE_VERSION, + meta, + evals: self + .evals + .iter() + .map(|(k, v)| (k.clone(), v.clone())) + .collect(), + }; + let bytes = serde_json::to_vec(&file).map_err(std::io::Error::other)?; + write_atomic(&self.cache_path(dir), &bytes) + } + + fn load_cache(&mut self, dir: &Path) -> bool { + let Ok(bytes) = std::fs::read(self.cache_path(dir)) else { + return false; + }; + let Ok(file) = serde_json::from_slice::(&bytes) else { + return false; + }; + if file.version != CACHE_VERSION || file.evals.is_empty() { + return false; + } + self.meta = Some(file.meta); + self.evals = file.evals.into_iter().collect(); + true + } + + /// Uses `[%eval]` comments (Lichess exports, or our own written analysis) when every + /// main-line move has one. + fn load_pgn_evals(&mut self, game: &Game) -> bool { + let mut found = Vec::new(); + for (i, id) in self.line.iter().enumerate().skip(1) { + let Some(node) = game.node(*id) else { + return false; + }; + let e = node + .comments_after() + .iter() + .flat_map(|c| parse_comment(c)) + .find_map(|p| match p { + CommentPart::Annotation(Annotation::Other { name, payload }) + if name == "eval" => + { + Eval::parse_pgn(&payload) + } + _ => None, + }); + match e { + Some(e) => found.push((i, e)), + None if self.values[i].is_some() => {} + None => return false, + } + } + let Some(&(_, first)) = found.first() else { + return false; + }; + // The start position carries no comment: Lichess assumes +0.15 for the initial one. + let root = if game.start().is_standard() { + Eval::Cp(15) + } else { + first + }; + found.insert(0, (0, root)); + for (i, eval) in found { + self.evals.insert( + self.keys[i].clone(), + PosEval { + eval, + pv: Vec::new(), + depth: 0, + }, + ); + } + self.meta = Some(ReviewMeta { + engine: "PGN".into(), + nodes: 0, + }); + true + } +} + +/// Cache key and UCI position of a node (full history, see [`Game::engine_history`]). +fn position_key(game: &Game, id: NodeId) -> Option<(String, EnginePosition)> { + let h = game.engine_history(id)?; + let key = format!( + "{}|{}", + h.start_fen.as_deref().unwrap_or("startpos"), + h.moves.join(" ") + ); + let pos = match h.start_fen { + None => EnginePosition::startpos(h.moves), + Some(fen) => EnginePosition::fen(fen, h.moves), + }; + Some((key, pos)) +} + +/// Evaluation of a position without legal moves. +fn terminal_eval(pos: &Chess) -> Option { + if pos.is_checkmate() { + Some(Eval::Mate { + white: pos.turn() == Color::Black, + moves: 0, + }) + } else if pos.is_stalemate() { + Some(Eval::Cp(0)) + } else { + None + } +} + +/// The legal beginning of an engine line from `root`: its moves and their SAN. +pub fn parse_pv(root: &Chess, pv: &[String]) -> (Vec, Vec) { + let mut pos = root.clone(); + let (mut moves, mut san) = (Vec::new(), Vec::new()); + for u in pv { + let Some(m) = u + .parse::() + .ok() + .and_then(|um| um.to_move(&pos).ok()) + else { + break; + }; + san.push(SanPlus::from_move_and_play_unchecked(&mut pos, m).to_string()); + moves.push(m); + } + (moves, san) +} + +/// Writes through a temporary file, so a crash never leaves half a cache file. +fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let tmp = path.with_extension("json.tmp"); + std::fs::write(&tmp, bytes)?; + std::fs::rename(&tmp, path) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn game(pgn: &str) -> Game { + chess_core::parse_str(pgn).game + } + + #[test] + fn pgn_evals_give_the_report() { + let g = game( + "1. e4 {[%eval 0.3]} e5 {[%eval 0.32]} 2. Qh5 {[%eval -0.2]} Ke7 {[%eval 6.5]} \ + 3. Qxe5# 1-0", + ); + let a = GameAnalysis::new(&g, None); + assert!(a.has_data()); + assert_eq!(a.missing(), 0); + assert!(a.report.complete); + assert_eq!(a.meta.as_ref().map(|m| m.nodes), Some(0)); + let ke7 = g.mainline()[3]; + assert_eq!( + a.marks.get(&ke7).map(|m| m.judgement), + Some(Judgement::Blunder) + ); + assert_eq!(a.errors(Color::Black, Judgement::Blunder), vec![ke7]); + assert!(a.errors(Color::White, Judgement::Blunder).is_empty()); + // The final mate is evaluated without an engine and not counted for one. + assert_eq!(a.positions(), a.line().len() - 1); + // So is a final stalemate. + let stale = game("[FEN \"7k/8/6K1/8/8/8/8/5Q2 w - - 0 1\"] 1. Qf7 *"); + let s = GameAnalysis::new(&stale, None); + assert_eq!(s.line().len(), 2); + assert_eq!(s.positions(), 1); + assert_eq!(s.values()[1], Some(Eval::Cp(0))); + } + + #[test] + fn engine_results_are_cached_per_main_line() { + let dir = std::env::temp_dir().join(format!("game-review-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let g = game("1. e4 e5 2. Nf3 *"); + let mut a = GameAnalysis::new(&g, Some(&dir)); + assert!(!a.has_data()); + let meta = ReviewMeta { + engine: "Fake".into(), + nodes: 1000, + }; + let targets = a.begin(&g, meta.clone(), false); + assert_eq!(targets.len(), 4); + for (i, t) in targets.into_iter().enumerate() { + a.apply(JobEvent::Eval { + key: t.key, + eval: PosEval { + eval: Eval::Cp(20 - i as i32 * 300), + pv: vec!["e2e4".into()], + depth: 10, + }, + nps: 0, + }); + } + a.refresh(&g); + assert_eq!(a.missing(), 0); + a.save_cache(&dir).expect("saved"); + let b = GameAnalysis::new(&g, Some(&dir)); + assert_eq!(b.meta, Some(meta)); + assert_eq!(b.values(), a.values()); + // 1.e4 was the engine's own move: never an error, whatever the evaluations say. + assert!(!b.marks.contains_key(&g.mainline()[0])); + // Another main line has its own file. + assert!(!GameAnalysis::new(&game("1. d4 *"), Some(&dir)).has_data()); + // Filling in keeps the quality of the first run. + let mut c = GameAnalysis::new(&g, Some(&dir)); + let fast = ReviewMeta { + engine: "Fake".into(), + nodes: 250, + }; + assert!(c.begin(&g, fast.clone(), false).is_empty()); + assert_eq!(c.meta.as_ref().map(|m| m.nodes), Some(1000)); + c.begin(&g, fast, true); + assert_eq!(c.meta.as_ref().map(|m| m.nodes), Some(250)); + // A game without moves is never cached. + let empty = game("*"); + let mut e = GameAnalysis::new(&empty, Some(&dir)); + let t = e.begin( + &empty, + ReviewMeta { + engine: "Fake".into(), + nodes: 1000, + }, + false, + ); + for t in t { + e.apply(JobEvent::Eval { + key: t.key, + eval: PosEval { + eval: Eval::Cp(20), + pv: vec![], + depth: 1, + }, + nps: 0, + }); + } + e.save_cache(&dir).expect("nothing to save is fine"); + assert!( + !GameAnalysis::new( + &game("[FEN \"8/8/8/8/8/8/8/K1k5 w - - 0 1\"] *"), + Some(&dir) + ) + .has_data() + ); + assert!(!GameAnalysis::new(&empty, Some(&dir)).has_data()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/apps/desktop/src/report.rs b/crates/game-review/src/report.rs similarity index 100% rename from apps/desktop/src/report.rs rename to crates/game-review/src/report.rs diff --git a/crates/mobile-api/Cargo.toml b/crates/mobile-api/Cargo.toml index 8418bc9..6e87cd0 100644 --- a/crates/mobile-api/Cargo.toml +++ b/crates/mobile-api/Cargo.toml @@ -24,6 +24,7 @@ bindgen = ["uniffi/cli"] [dependencies] chess-core.workspace = true chess-import.workspace = true +game-review.workspace = true shakmaty.workspace = true thiserror.workspace = true uci.workspace = true diff --git a/crates/mobile-api/src/engine.rs b/crates/mobile-api/src/engine.rs index 9429f77..7ff2016 100644 --- a/crates/mobile-api/src/engine.rs +++ b/crates/mobile-api/src/engine.rs @@ -286,17 +286,30 @@ fn engine_line(root: &Chess, multipv: u32, score: Score, pv: &[String]) -> Engin bound: uci::ScoreBound::Exact, } .to_white(side); - let (eval, cp, mate) = match white.eval { - WhiteEval::Cp(cp) => (pawns(cp), Some(cp), None), + let (cp, mate) = match white.eval { + WhiteEval::Cp(cp) => (Some(cp), None), WhiteEval::Mate { winner, moves } => { let n = moves as i32; - if winner == Side::White { - (format!("#{n}"), None, Some(n)) - } else { - (format!("#\u{2212}{n}"), None, Some(-n)) - } + (None, Some(if winner == Side::White { n } else { -n })) } }; + line_with(root, multipv, cp, mate, pv) +} + +/// The line `pv` (UCI) from `root` with its evaluation for White: centipawns, or moves +/// to mate (positive when White mates). Stops at the first move that is not legal. +pub(crate) fn line_with( + root: &Chess, + multipv: u32, + cp: Option, + mate: Option, + pv: &[String], +) -> EngineLine { + let eval = match (mate, cp) { + (Some(n), _) if n < 0 => format!("#\u{2212}{}", -n), + (Some(n), _) => format!("#{n}"), + (None, cp) => pawns(cp.unwrap_or(0)), + }; let mut pos = root.clone(); let mut words = Vec::new(); let mut steps = Vec::new(); @@ -337,7 +350,7 @@ fn engine_line(root: &Chess, multipv: u32, score: Score, pv: &[String]) -> Engin } /// Centipawns as pawns with a sign: "+0.45", "−1.20", "0.00". -fn pawns(cp: i32) -> String { +pub(crate) fn pawns(cp: i32) -> String { let sign = match cp.signum() { 1 => "+", -1 => "\u{2212}", diff --git a/crates/mobile-api/src/lib.rs b/crates/mobile-api/src/lib.rs index c082003..dbcc1f9 100644 --- a/crates/mobile-api/src/lib.rs +++ b/crates/mobile-api/src/lib.rs @@ -12,8 +12,10 @@ use chess_core::{Game, MoveKind, NodeId}; use shakmaty::Position; mod engine; +mod review; pub use engine::{Analysis, Analyzer, EngineFailure, EngineLine, LineStep}; +pub use review::{GameReview, MoveJudgement, ReviewMove, ReviewPoint, ReviewState, SideReview}; uniffi::setup_scaffolding!(); @@ -330,12 +332,12 @@ impl Database { .collect() } - /// The game `index`, ready to show. /// The game `index` as PGN text, as it is in the file (to copy or share). pub fn pgn(&self, index: u32) -> Option { self.db.raw_text(index as usize) } + /// The game `index`, ready to show. pub fn game(&self, index: u32) -> Result { let parsed = self .db @@ -343,6 +345,38 @@ impl Database { .ok_or(ApiError::NoGame { index })?; Ok(game_data(&parsed.game, &parsed.diagnostics)) } + + /// The analysis of the game `index` (its report), with earlier results from the + /// cache folder `cache_dir` ("" for none) or from `[%eval]` comments of the game. + pub fn review(&self, index: u32, cache_dir: String) -> Result, ApiError> { + let parsed = self + .db + .load_game(index as usize) + .ok_or(ApiError::NoGame { index })?; + Ok(GameReview::new(parsed.game, cache_dir)) + } +} + +/// Node ids in tree order (the root first, each line before its variations' tails), +/// mapped to their places in [`GameData::nodes`]. +fn order(game: &Game) -> Vec { + let mut order = vec![NodeId::ROOT]; + let mut i = 0; + while i < order.len() { + let id = order[i]; + order.extend(game.children(id).iter().copied()); + i += 1; + } + order +} + +/// The place in [`GameData::nodes`] of every node of the game. +fn places(game: &Game) -> std::collections::HashMap { + order(game) + .iter() + .enumerate() + .map(|(i, id)| (*id, i as u32)) + .collect() } fn row(e: &chess_core::GameEntry) -> GameRow { @@ -398,20 +432,8 @@ fn marks(comments: &[String]) -> Vec { } fn game_data(game: &Game, diagnostics: &[chess_core::Diagnostic]) -> GameData { - // Ids in tree order (the root first, each line before its variations' tails), mapped - // to their places in the list. - let mut order = vec![NodeId::ROOT]; - let mut i = 0; - while i < order.len() { - let id = order[i]; - order.extend(game.children(id).iter().copied()); - i += 1; - } - let places: std::collections::HashMap = order - .iter() - .enumerate() - .map(|(i, id)| (*id, i as u32)) - .collect(); + let order = order(game); + let places = places(game); let place = |id: NodeId| places.get(&id).copied(); let main: std::collections::HashSet = game.mainline().into_iter().collect(); let nodes = order diff --git a/crates/mobile-api/src/review.rs b/crates/mobile-api/src/review.rs new file mode 100644 index 0000000..e2af865 --- /dev/null +++ b/crates/mobile-api/src/review.rs @@ -0,0 +1,520 @@ +//! The game report for the Android app: the analysis of a game's main line by the +//! `game-review` crate (the same evaluations, judgements, accuracy and cache as on the +//! desktop), with its engine job on a thread of its own. The app starts it, asks for +//! the state while it runs, and gets everything the graph, the report and the marks in +//! the notation need, in the node numbers of [`crate::GameData`]. +//! +//! The game is never changed. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, channel}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use chess_core::{Game, NodeId}; +use game_review::{ + Eval, GameAnalysis, JobEvent, JobFailure, JobSettings, Judgement, ReviewMeta, SideStats, +}; +use shakmaty::Color; + +use crate::EngineLine; +use crate::engine::{line_with, pawns}; + +/// How bad a move was. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum MoveJudgement { + Inaccuracy, + Mistake, + Blunder, +} + +impl From for MoveJudgement { + fn from(j: Judgement) -> Self { + match j { + Judgement::Inaccuracy => MoveJudgement::Inaccuracy, + Judgement::Mistake => MoveJudgement::Mistake, + Judgement::Blunder => MoveJudgement::Blunder, + } + } +} + +/// A position of the main line: the start, then the one after each move. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct ReviewPoint { + /// The node (of [`crate::GameData`]) of this position. + pub node: u32, + /// White's chance of winning, 0..100, when the position is evaluated. + pub white_win: Option, + /// "+0.35", "−1.20", "#3", "#−2", "1-0" ("" while not evaluated). + pub eval: String, + /// The judgement of the move that led here. + pub judgement: Option, +} + +/// One player's numbers. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct SideReview { + pub inaccuracies: u32, + pub mistakes: u32, + pub blunders: u32, + /// Average centipawn loss. + pub acpl: Option, + /// Accuracy 0..100 (only when every position is evaluated). + pub accuracy: Option, + pub opening: Option, + pub middlegame: Option, + pub endgame: Option, +} + +/// An inaccuracy, mistake or blunder of the main line. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct ReviewMove { + /// The node of the move. + pub node: u32, + pub judgement: MoveJudgement, + /// White made the move. + pub white: bool, + /// The engine's line from the position before the move (its first move was + /// better), to show on the board; `None` when the evaluation came from the PGN. + pub best: Option, + /// The better move with its number, Latin letters: "23…Nf6" ("" when unknown). + pub best_label: String, + /// How the opponent punishes the move: the engine's reply, for an arrow. + pub reply_from: Option, + pub reply_to: Option, +} + +/// Everything about the analysis of the game at this moment. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct ReviewState { + /// The engine job is running. + pub running: bool, + /// Positions evaluated by this run, of `total`. + pub done: u32, + pub total: u32, + /// Why the last run stopped early (the engine crashed, did not start). + pub failure: Option, + /// Some evaluations exist (from the engine, the cache or the PGN). + pub has_data: bool, + /// The engine's name; "PGN" when the evaluations come from `[%eval]` comments. + pub engine: String, + /// Nodes per position; 0 for evaluations from the PGN. + pub nodes: u64, + /// Positions of the main line without an evaluation. + pub missing: u32, + /// Positions a full analysis looks at (for the time estimate). + pub positions: u32, + /// The engine's speed in the last run, per thread (0 when unknown). + pub nps_per_thread: u64, + /// The start position and the position after every main-line move. + pub points: Vec, + /// Where the middlegame and the endgame begin, as indices of `points`. + pub middlegame: Option, + pub endgame: Option, + pub white: SideReview, + pub black: SideReview, + /// The errors, in the order of the game. + pub moves: Vec, +} + +enum Msg { + Event(JobEvent), + Done, + Failed(String), +} + +struct Job { + rx: Receiver, + cancel: Arc, + threads: u32, +} + +impl Drop for Job { + fn drop(&mut self) { + self.cancel.store(true, Ordering::Relaxed); + } +} + +struct Inner { + game: Game, + /// Node ids of the game → node numbers of [`crate::GameData`]. + places: HashMap, + analysis: GameAnalysis, + cache_dir: Option, + job: Option, + done: u32, + total: u32, + failure: Option, + nps_per_thread: u64, + /// When the cache was last written: a long run is kept now and then, so that a + /// crash or a killed app loses little of it. + saved: Instant, +} + +/// How often a running analysis is written to the cache. +const SAVE_EVERY: Duration = Duration::from_secs(10); + +/// The analysis of one game. +#[derive(uniffi::Object)] +pub struct GameReview { + inner: Mutex, +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, Inner> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +impl GameReview { + /// The analysis of `game`; earlier results come from `cache_dir` (empty: no cache). + pub(crate) fn new(game: Game, cache_dir: String) -> Arc { + let cache_dir = (!cache_dir.is_empty()).then(|| PathBuf::from(cache_dir)); + let analysis = GameAnalysis::new(&game, cache_dir.as_deref()); + Arc::new(GameReview { + inner: Mutex::new(Inner { + places: crate::places(&game), + game, + analysis, + cache_dir, + job: None, + done: 0, + total: 0, + failure: None, + nps_per_thread: 0, + saved: Instant::now(), + }), + }) + } +} + +#[uniffi::export] +impl GameReview { + /// Starts the engine at `path` (with its network `eval_file`, if not empty) on the + /// positions without an evaluation, or on all of them when `full`. Returns false when + /// there is nothing to analyse. Returns at once: the engine starts on its own thread. + pub fn start( + &self, + path: String, + eval_file: String, + threads: u32, + hash_mb: u32, + nodes: u64, + full: bool, + ) -> bool { + let mut st = lock(&self.inner); + stop(&mut st); + st.failure = None; + let meta = ReviewMeta { + engine: "Stockfish".into(), + nodes, + }; + let Inner { game, analysis, .. } = &mut *st; + let targets = analysis.begin(game, meta, full); + if targets.is_empty() { + return false; + } + // Filling in keeps the quality of the earlier run (see `GameAnalysis::begin`). + let nodes = analysis.meta.as_ref().map_or(nodes, |m| m.nodes); + let settings = JobSettings { + threads: threads.max(1), + hash_mb: hash_mb.max(1), + nodes, + eval_file: (!eval_file.is_empty()).then_some(eval_file), + }; + // Below the app (nice 10), as the live engine: the phone stays smooth. + let config = uci::EngineConfig { + nice: 10, + ..uci::EngineConfig::new(path) + }; + let (tx, rx) = channel(); + let cancel = Arc::new(AtomicBool::new(false)); + let stop = cancel.clone(); + st.total = targets.len() as u32; + st.done = 0; + let threads = settings.threads; + let spawned = std::thread::Builder::new() + .name("game-review".into()) + .spawn(move || { + let result = game_review::run(config, &settings, targets, &stop, &mut |e| { + let _ = tx.send(Msg::Event(e)); + }); + let _ = tx.send(match result { + Ok(()) => Msg::Done, + Err(JobFailure::Start(e) | JobFailure::Engine(e)) => Msg::Failed(e), + Err(JobFailure::Terminated(reason)) => Msg::Failed(format!("{reason:?}")), + }); + }); + if let Err(e) = spawned { + st.failure = Some(e.to_string()); + return false; + } + st.job = Some(Job { + rx, + cancel, + threads, + }); + true + } + + /// Stops the engine; what it has evaluated is kept (and cached). + pub fn cancel(&self) { + stop(&mut lock(&self.inner)); + } + + /// The state now, with what the engine has said since the last call. + pub fn state(&self) -> ReviewState { + let mut st = lock(&self.inner); + drain(&mut st); + let Inner { game, analysis, .. } = &mut *st; + analysis.refresh(game); + snapshot(&st) + } +} + +impl Drop for GameReview { + fn drop(&mut self) { + // Leaving the game mid-analysis keeps what was computed. + stop(&mut lock(&self.inner)); + } +} + +/// Ends the running job, keeping every result it has sent. +fn stop(st: &mut Inner) { + if st.job.is_none() { + return; + } + drain(st); + if st.job.take().is_some() { + save(st); + } +} + +fn drain(st: &mut Inner) { + let Some(job) = &st.job else { return }; + let mut events = Vec::new(); + let mut ended = None; + while let Ok(msg) = job.rx.try_recv() { + match msg { + Msg::Event(e) => events.push(e), + Msg::Done => ended = Some(None), + Msg::Failed(e) => ended = Some(Some(e)), + } + } + let threads = u64::from(job.threads.max(1)); + let got = !events.is_empty(); + for e in events { + if let JobEvent::Eval { nps, .. } = &e { + st.done += 1; + if *nps > 0 { + st.nps_per_thread = nps / threads; + } + } + st.analysis.apply(e); + } + if let Some(failure) = ended { + st.job = None; + st.failure = failure; + save(st); + } else if got && st.saved.elapsed() >= SAVE_EVERY { + save(st); + } +} + +fn save(st: &mut Inner) { + st.saved = Instant::now(); + if let Some(dir) = &st.cache_dir { + // A cache that cannot be written only means analysing again next time. + let _ = st.analysis.save_cache(dir); + } +} + +/// "+0.35", "−1.20", "#3", "#−2", "1-0". +fn eval_text(e: Eval) -> String { + match e { + Eval::Cp(cp) => pawns(cp), + Eval::Mate { white, moves: 0 } => if white { "1-0" } else { "0-1" }.into(), + Eval::Mate { white: true, moves } => format!("#{moves}"), + Eval::Mate { + white: false, + moves, + } => format!("#\u{2212}{moves}"), + } +} + +fn side(s: &SideStats) -> SideReview { + SideReview { + inaccuracies: s.inaccuracies, + mistakes: s.mistakes, + blunders: s.blunders, + acpl: s.acpl, + accuracy: s.accuracy, + opening: s.phase_accuracy[0], + middlegame: s.phase_accuracy[1], + endgame: s.phase_accuracy[2], + } +} + +fn snapshot(st: &Inner) -> ReviewState { + let a = &st.analysis; + let place = |id: NodeId| st.places.get(&id).copied().unwrap_or(0); + let line = a.line(); + let points = line + .iter() + .enumerate() + .map(|(i, id)| { + let v = a.values().get(i).copied().flatten(); + ReviewPoint { + node: place(*id), + white_win: v.map(|e| e.win_percent(Color::White) as f32), + eval: v.map(eval_text).unwrap_or_default(), + judgement: i + .checked_sub(1) + .and_then(|p| a.report.judgements.get(p).copied().flatten()) + .map(Into::into), + } + }) + .collect(); + let mut moves = Vec::new(); + for (i, id) in line.iter().enumerate().skip(1) { + let Some(mark) = a.marks.get(id) else { + continue; + }; + let best = a.eval_at(i - 1).filter(|e| !e.pv.is_empty()).and_then(|e| { + let root = st.game.position(mark.base)?; + let (cp, mate) = match e.eval { + Eval::Cp(cp) => (Some(cp), None), + Eval::Mate { white, moves } => ( + None, + Some(if white { moves as i32 } else { -(moves as i32) }), + ), + }; + Some(line_with(root, 1, cp, mate, &e.pv)) + }); + // The reply is the first move of the engine line after the bad move. + let reply = a + .eval_at(i) + .and_then(|e| e.pv.first()) + .filter(|_| !a.refutation(*id, &st.game).is_empty()) + .filter(|u| u.len() >= 4) + .map(|u| (u[0..2].to_owned(), u[2..4].to_owned())); + moves.push(ReviewMove { + node: place(*id), + judgement: mark.judgement.into(), + white: a.movers().get(i - 1) == Some(&Color::White), + best, + best_label: mark.best_label.clone().unwrap_or_default(), + reply_from: reply.as_ref().map(|r| r.0.clone()), + reply_to: reply.map(|r| r.1), + }); + } + let meta = a.meta.clone().unwrap_or_default(); + ReviewState { + running: st.job.is_some(), + done: st.done, + total: st.total, + failure: st.failure.clone(), + has_data: a.has_data(), + engine: meta.engine, + nodes: meta.nodes, + missing: a.missing() as u32, + positions: a.positions() as u32, + nps_per_thread: st.nps_per_thread, + points, + middlegame: a.report.phases.middlegame.map(|i| i as u32), + endgame: a.report.phases.endgame.map(|i| i as u32), + white: side(&a.report.white), + black: side(&a.report.black), + moves, + } +} + +#[cfg(test)] +mod tests { + use crate::open_bytes; + + #[test] + fn evaluations_of_the_pgn_make_a_report() { + let pgn = b"[Event \"t\"]\n\n1. e4 {[%eval 0.3]} e5 {[%eval 0.32]} 2. Qh5 {[%eval -0.2]} \ + Ke7 {[%eval 6.5]} 3. Qxe5# 1-0\n" + .to_vec(); + let db = open_bytes("t.pgn".into(), pgn).unwrap(); + let data = db.game(0).unwrap(); + let review = db.review(0, String::new()).unwrap(); + let s = review.state(); + assert!(s.has_data && !s.running); + assert_eq!((s.engine.as_str(), s.nodes, s.missing), ("PGN", 0, 0)); + assert_eq!(s.points.len(), 6); + assert_eq!(s.points[0].node, 0); + assert_eq!(s.points.last().unwrap().eval, "1-0"); + assert_eq!(s.black.blunders, 1); + assert_eq!(s.moves.len(), 1); + let ke7 = &s.moves[0]; + assert!(!ke7.white); + assert_eq!(data.nodes[ke7.node as usize].san, "Ke7"); + // Evaluations from the PGN have no lines: nothing to show on the board. + assert!(ke7.best.is_none() && ke7.reply_from.is_none()); + assert!(s.white.accuracy.is_some()); + // Nothing to analyse: every position has an evaluation. + assert!(!review.start("/nonexistent".into(), String::new(), 1, 16, 1000, false)); + } + + /// With the fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`). + #[test] + fn the_engine_job_runs_and_is_cached() { + let fake = concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/debug/fake_uci"); + assert!( + std::path::Path::new(fake).exists(), + "build the fake engine first: cargo build -p uci --bin fake_uci" + ); + let dir = std::env::temp_dir().join(format!("mobile-review-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let cache = dir.to_string_lossy().into_owned(); + let db = open_bytes("t.pgn".into(), b"1. e4 e5 2. Nf3 Nc6 *\n".to_vec()).unwrap(); + let review = db.review(0, cache.clone()).unwrap(); + assert!(!review.state().has_data); + assert!(review.start(fake.into(), String::new(), 1, 16, 1000, false)); + let mut s = review.state(); + for _ in 0..200 { + if !s.running { + break; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + s = review.state(); + } + assert!(!s.running, "the job did not end"); + assert_eq!(s.failure, None); + assert_eq!((s.done, s.total, s.missing), (5, 5, 0)); + assert!(s.points.iter().all(|p| p.white_win.is_some())); + drop(review); + // The next time the game opens, the results are there without the engine. + let again = db.review(0, cache).unwrap().state(); + assert!(again.has_data && again.missing == 0 && again.nodes == 1000); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_failing_engine_is_reported() { + let db = open_bytes("t.pgn".into(), b"1. e4 e5 *\n".to_vec()).unwrap(); + let review = db.review(0, String::new()).unwrap(); + assert!(review.start( + "/nonexistent/engine".into(), + String::new(), + 1, + 16, + 1000, + false + )); + let mut s = review.state(); + for _ in 0..200 { + if !s.running { + break; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + s = review.state(); + } + assert!(!s.running); + assert!(s.failure.is_some()); + assert!(!s.has_data); + } +} diff --git a/crates/uci/src/bin/fake_uci.rs b/crates/uci/src/bin/fake_uci.rs index 9347e5d..c862097 100644 --- a/crates/uci/src/bin/fake_uci.rs +++ b/crates/uci/src/bin/fake_uci.rs @@ -268,7 +268,9 @@ fn main() { .iter() .position(|&t| t == "depth") .and_then(|p| toks.get(p + 1)) - .and_then(|v| v.parse().ok()); + .and_then(|v| v.parse().ok()) + // `go nodes N`: a short search that ends by itself, like a real one. + .or_else(|| toks.contains(&"nodes").then_some(3)); search = Some(Search { marker: marker.clone(), depth: 0, diff --git a/docs/design/android-ui.md b/docs/design/android-ui.md index 6295ed2..4809af8 100644 --- a/docs/design/android-ui.md +++ b/docs/design/android-ui.md @@ -1046,6 +1046,9 @@ FAB открывает лист, а не сразу системный выбо | образец доски или набора (§9.1) | «Зелёная, выбрано, переключатель» / «merida, не выбрано, переключатель» | “Green, selected, radio button” / “merida, not selected, radio button” | | кнопка «Движок» | «Движок, выключен» / «Движок, не скачан» | “Engine, off” / “Engine, not downloaded” | | ‹ › | «Предыдущая партия» / «Следующая партия» | “Previous game” / “Next game” | +| ход с отметкой движка (§21.4) | «6, чёрные, конь f6, ошибка» | “6, Black, knight f6, mistake” | +| график оценки (§21.3) | «График оценки, ход 23, оценка плюс 1,2» | “Evaluation graph, move 23, evaluation plus 1.2” | +| ячейка отчёта (§21.5) | «Неточности, чёрные, 3, кнопка» | “Inaccuracies, Black, 3, button” | - Фигуры озвучиваются словами («конь»), а не буквами записи. Клетки читаются от a8 к h1, при перевёрнутой доске — от h1 к a8. - Смысл никогда не передаётся одним цветом: у NAG есть значок, у результата текст, у текущего хода — озвучивание «текущий». @@ -1297,6 +1300,43 @@ FAB открывает лист, а не сразу системный выбо | `about_version_full` / `about_version_light` | {v} · Stockfish уже внутри / {v} · Stockfish скачивается в приложении | {v} · Stockfish built in / {v} · Stockfish downloaded in the app | | `about_licenses` | Лицензии и авторы | Licenses and authors | +### 14.7. Отчёт по партии (§21) + +Слова те же, что на компьютере (`apps/desktop/src/i18n.rs`, «Whole-game analysis»), кроме отмеченных *. Немецкий, испанский, французский и итальянский — тоже как на компьютере («Grober Fehler», «Error grave», «Gaffe», «Svarione», «Resoconto»). + +| Ключ | RU | EN | +|---|---|---| +| `review_menu` / `review_report_menu` | Анализ партии / Отчёт по партии | Game analysis / Game report | +| `review_text` | Движок оценит каждую позицию основной линии. Сама партия не изменится. | The engine evaluates every position of the main line. The game itself is not changed. | +| `review_quality` / `review_fast` / `review_normal` / `review_deep` | Качество / Быстро / Обычно / Глубоко | Quality / Fast / Normal / Deep | +| `review_estimate` | Позиций: {n}, примерно {time} | {n} positions, about {time} | +| `review_seconds` / `review_minutes` | {n} с / {n} мин | {n} s / {n} min | +| `review_partial` | Уже оценено позиций: {done} из {total}. | {done} of {total} positions are evaluated already. | +| `review_start` / `review_fill` | Анализировать / Дополнить | Analyse / Fill in | +| `review_restart` * (лист запуска, рядом с «Дополнить») | Заново | Start over | +| `review_again` * (отчёт) | Анализировать заново | Analyse again | +| `review_progress` / `review_stop` | Анализ партии · {done} из {total} / Остановить анализ | Game analysis · {done} of {total} / Stop the analysis | +| `review_accuracy` / `review_accuracy_of` | Точность / Точность: белые {w}, чёрные {b} | Accuracy / Accuracy: White {w}, Black {b} | +| `review_report` | Отчёт | Report | +| `review_better` | лучше было {move} | {move} was better | +| `review_inaccuracy` / `review_mistake` / `review_blunder` | Неточность / Ошибка / Зевок | Inaccuracy / Mistake / Blunder | +| `review_inaccuracies` / `review_mistakes` / `review_blunders` | Неточности / Ошибки / Зевки | Inaccuracies / Mistakes / Blunders | +| `review_missing` | Без оценки: {n} | Not evaluated: {n} | +| `review_failed` / `review_resume` | Анализ прервался / Продолжить | The analysis stopped / Continue | +| `review_acpl` | Средняя потеря сантипешек | Average centipawn loss | +| `review_opening` / `review_middlegame` / `review_endgame` | Дебют / Миттельшпиль / Эндшпиль | Opening / Middlegame / Endgame | +| `review_source` / `review_source_pgn` | {engine} · {nodes} узлов на ход / Оценки из PGN ([%eval]) | {engine} · {nodes} nodes per move / Evaluations from the PGN ([%eval]) | +| `review_hide` * | Скрыть анализ | Hide analysis | +| `review_graph` * (TalkBack) | График оценки | Evaluation graph | +| `review_engine_paused` * | Пауза: идёт анализ партии | Paused: the game is being analysed | +| `review_best_preview` * | Лучшая линия · ход {i} из {n} | Better line · move {i} of {n} | +| `review_next` * (TalkBack) | Перейти к следующему такому ходу | Go to the next such move | +| `review_show_best` (TalkBack) | Показать лучшую линию на доске | Show the better line on the board | + +- `review_no_line` («Оценки взяты из PGN: лучшей линии в них нет.») не используется: без лучшей линии строка просто не нажимается (§21.3). Строку удалить. +- `review_next` на компьютере «Перейти к следующей» согласуется только с «неточностью» и «ошибкой», а не с «зевком»; на телефоне — нейтрально «к следующему такому ходу». Компьютеру — по желанию то же. +- Остальные пять языков для строк с *: «Erneut» / «Von vorn» (de), «Empezar de nuevo» (es), «Recommencer» (fr), «Ricomincia» (it) для `review_restart`; «Analyse ausblenden», «Ocultar el análisis», «Masquer l'analyse», «Nascondi l'analisi» для `review_hide`; `review_next` — «Zum nächsten solchen Zug», «Ir a la siguiente jugada así», «Aller au coup suivant de ce type», «Vai alla prossima mossa di questo tipo»; `review_engine_paused` — с заглавной: «Pausiert: …», «En pausa: …», «En pause : …», «In pausa: …». + ## 15. Первая версия и дальше ### 15.1. Первая версия @@ -1379,3 +1419,122 @@ FAB открывает лист, а не сразу системный выбо - §7.6 — партия из буфера или из файла с одной партией — «1 из 1» с неактивными ‹ ›. - §9 — потоков движка по умолчанию не больше 2. Кнопка «Движок» включает и выключает анализ, движок запускается только ею (§19); экран партии при анализе перерисовывает только строку движка и стрелки. - §14.1, §14.2 — новые и исправленные строки. + +## 21. Отчёт по партии (2026-10-23) + +Тот же анализ, что на компьютере (`docs/decisions.md` п. 9): движок оценивает каждую позицию основной линии, из оценок получаются неточности, ошибки и зевки, средняя потеря и точность по формулам Lichess. Расчёт, кэш и задание движка — общий крейт `game-review`, поэтому цифры на телефоне и на компьютере совпадают. Партия не меняется; «Записать анализ в партию» на телефоне нет (просмотр, §15.3). + +### 21.1. Пути пользователя + +1. **«Где он ошибся?»** Партия открыта → ⋮ → «Анализ партии» → лист запуска → «Анализировать». Пока движок считает, можно листать партию: график растёт, отметки появляются в нотации. Когда готово — строка над графиком показывает точность, «Отчёт» открывает цифры. +2. **«Почему это зевок?»** Человек стоит на ходе с отметкой (или нажал «Зевки 1 ›» в отчёте) → строка «?? Зевок · лучше было 23…Кf6». Касание строки показывает лучшую линию на доске (предпросмотр §8.3: ◀ ▶ листают, ✕ и «назад» выводят). На доске стрелка цвета отметки — как соперник наказывает ход. +3. **«Пройти все ошибки»** — в отчёте счётчики «Неточности / Ошибки / Зевки» у каждого игрока: касание закрывает лист и ведёт к следующему такому ходу этого игрока, по кругу. +4. **Партия уже оценена.** Если эта основная линия анализировалась раньше (кэш) или у каждого хода есть `[%eval]` (выгрузки Lichess), график и отметки видны сразу при открытии, движок не нужен. +5. **Сборка без движка.** «Анализировать» без скачанного движка открывает лист скачивания (§8.4); когда движок готов, анализ начинается сам. +6. **Вход один — первый пункт меню ⋮** (ревью 2026-10-23). Нижняя панель полна (§7.4), отдельной кнопки нет. Пункт называется «Анализ партии», пока оценок нет, и «Отчёт по партии», когда они есть (тогда он открывает отчёт и возвращает скрытую панель). Пока идёт первый анализ и оценок ещё нет, пункт неактивен: панель с ходом анализа уже на экране. Новый анализ при готовом отчёте — кнопкой «Анализировать заново» в отчёте. +7. **Убрать с экрана.** «Скрыть анализ» в отчёте убирает панель и отметки в нотации до следующего открытия партии. Анализ при этом не удаляется. + +### 21.2. Лист запуска «Анализ партии» + +``` +┌────────────────────────────────────┐ +│ Анализ партии │ 22sp +│ Движок оценит каждую позицию │ +│ основной линии. Сама партия не │ +│ изменится. │ +│ │ +│ Качество │ +│ [ Быстро | Обычно | Глубоко ] │ сегменты +│ Позиций: 80, примерно 2 мин │ +│ │ +│ [Отмена] [Анализировать] │ +└────────────────────────────────────┘ +``` + +- Качество — те же уровни, что на компьютере: 250 тыс., 1 млн, 3 млн узлов на позицию; по умолчанию «Обычно», выбор запоминается. +- Потоки и память — из настроек движка (§9, «Дополнительно»), отдельно не спрашиваются. +- Оценка времени — по скорости, измеренной в прошлый раз на этом телефоне (сначала — осторожная прикидка), словами «примерно 2 мин». +- Если часть позиций уже оценена, под оценкой времени строка «Уже оценено позиций: 60 из 80.», а кнопки — «Заново» (текстовая) и «Дополнить» (главная, только недостающие). «Отмена» здесь не нужна: лист закрывается свайпом и «назад». Короткое «Заново» понятно только рядом с «Дополнить», поэтому это отдельная строка `review_restart`, а не «Анализировать заново» из отчёта. +- Оценка времени считает только те позиции, которые будут считаться: при «Дополнить» — недостающие. + +### 21.3. Панель анализа + +Между доской (и строкой движка, если он включён) и нотацией, 88 dp: строка 48 dp и график 40 dp (кривая 32 dp и 8 dp снизу). Фон `surfaceContainerLow`, как у строки движка. + +``` +│ ?? Зевок · лучше было 23…Кf6 Отчёт │ 48 строка +│ ▁▂▃▅▆▇▇▆▅▃▂▁▁▂▃▅ · · │ │ 40 график +``` + +- **Строка 48 dp**, а не 40: в ней нажимаются «Отчёт», «Дополнить», ✕ и сама строка с ошибкой, а цели касания не меньше 48 dp (§12.2). Кнопка «Отчёт» не должна принимать касания на графике. +- **Строка** зависит от состояния (по порядку важности): + - идёт анализ — «Анализ партии · 23 из 80» и ✕ (остановить; посчитанное сохраняется); «Отчёта» нет; + - движок готовится (сборка с движком, первый запуск) — «Готовлю движок…»; + - текущий ход с отметкой — значок и название («?? Зевок») цветом отметки и «лучше было 23…Кf6». Ход «23…Кf6» набирается цветом `primary`, как ссылка: так видно, что строку можно нажать. Касание всей строки (кроме «Отчёта») — предпросмотр лучшей линии. Если лучшей линии нет (оценки из `[%eval]`), ход и «лучше было» не показываются, строка не нажимается; + - движок остановился — «Анализ прервался» цветом `error` и «Продолжить»; + - не все позиции оценены — «Без оценки: 12» и «Дополнить»; + - иначе — «Точность ○ 91% ● 84%» (кружки — цвета сторон, белый с рамкой `outline`); TalkBack: «Точность: белые 91%, чёрные 84%». + - Справа «Отчёт» во всех состояниях, кроме хода анализа и подготовки движка. +- **График** — шанс на победу, как на компьютере и Lichess: светлая область — перевес белых, тёмная — чёрных, оранжевая кривая, точки ошибок цветами отметок (поверх всего, кроме линии текущего хода), тонкие линии начала миттельшпиля и эндшпиля, вертикальная линия текущего хода (в варианте — хода, от которого он ответвился). Касание и протяжка по графику переводят к ходу. + - **Подписей стадий на графике нет** (ревью 2026-10-23). В 48 dp подписи 10sp занимали треть высоты, закрывали кривую там, где она обычно идёт — у верхнего края при перевесе белых, были мельче самого мелкого шрифта приложения (12sp, §10.2) и при крупном шрифте выросли бы до 20sp. Линии стадий остаются; точность по стадиям — в отчёте, названия — в описании для TalkBack. + - В TalkBack график — одно описание: «График оценки» и состояние «ход 23, оценка +1,2». Подсказку «коснитесь или проведите» не произносить: в TalkBack двойное касание не выбирает ход на графике, а переходы по партии делаются нотацией и ◀ ▶. +- Панель видна, пока есть оценки или идёт анализ. «Скрыть анализ» в отчёте убирает её до следующего открытия партии; ⋮ → «Отчёт по партии» возвращает. +- **Высота нотации.** Панель отнимает у нотации 88 dp из 256 (§7.1): остаётся 168 dp, около трёх строк; с включённым движком — 120, на развилке — 72. Поэтому панель — только по просьбе (кэш или `[%eval]` показывают её сразу, но «Скрыть анализ» убирает), а строка движка во время анализа не раскрывается (▾ скрыт). +- **В альбомной ориентации** панель стоит в правой колонке над нотацией. Колонка низкая (около 220 dp над кнопками), поэтому при включённом движке график скрывается и остаётся только строка 48 dp; без движка панель полная. + +### 21.4. Отметки в нотации + +- После хода основной линии — плашка «?!», «?» или «??» 13sp на подложке цвета отметки (16 %), скругление 4 dp, отдельно от авторских NAG: это слой движка, а не текст партии. Плашка стоит вне заливки текущего хода, поэтому сохраняет свой цвет и на текущем ходе. +- Если у хода уже есть авторский знак с тем же символом (автор поставил «?», движок — тоже ошибка), плашка не рисуется: «Кf6? ?» читается как опечатка. Если знаки разные («Кf6!?» и зевок движка) — видны оба. +- Цвета — цвета NAG Lichess (§10.3): неточность — как `?!`, ошибка — как `?`, зевок — как `??`. +- Отметки только в таблице основной линии; в тексте вариантов их нет (варианты не оцениваются). +- TalkBack читает «4, белые, Кf3, зевок». + +### 21.5. Лист «Отчёт по партии» + +Две колонки — белые и чёрные рядом, как на Lichess (ревью 2026-10-23). В первой реализации игроки шли друг под другом: лист высотой около 1000 dp открывался наполовину, и счётчики чёрных — обычно самое интересное — оказывались за краем экрана; сравнить игроков можно было только прокруткой. + +``` +│ Отчёт по партии │ 22sp +│ ○ Морфи ● Герцог │ имена 14sp/500, до 2 строк +│ Точность 98 % 79 % │ 24sp/500 +│ ?! Неточности 0 3 › │ строки 48 dp; ячейка +│ ? Ошибки 0 2 › │ со счётом > 0 нажимается +│ ?? Зевки 0 0 │ +│ Средняя потеря │ +│ сантипешек 8 64 │ 14sp, onSurfaceVariant +│ Дебют 96 % 80 % │ +│ Миттельшпиль 100 % 78 % │ строка стадии — если есть +│ Эндшпиль — — │ хоть у одного игрока +│ │ +│ Stockfish 19 · 250k узлов на ход │ или «Оценки из PGN ([%eval])» +│ [Скрыть анализ] (Анализировать заново) │ +``` + +- Колонка подписей занимает остаток ширины, колонки игроков — по 96 dp, числа по правому краю, моноширинные цифры. Имя игрока — фамилия до запятой («Morphy, Paul» → «Morphy»), до двух строк, дальше многоточие; полное имя — в TalkBack. +- Ячейка «3 ›» со счётом больше нуля — цель касания 96×48 dp: лист закрывается, партия переходит к следующему такому ходу этого игрока, по кругу. Счёт набирается цветом отметки, нуль — `onSurfaceVariant` без ›. +- TalkBack читает строку ячейками: «Неточности, чёрные, 3, кнопка, перейти к следующему такому ходу». +- Лист открывается сразу целиком (`skipPartiallyExpanded`), как лист «Добавить базу»: в нём нечего прятать за краем. На маленьком экране и при крупном шрифте он прокручивается. +- Точность по стадии показывается, только если в стадии не меньше трёх ходов игрока (как на компьютере); иначе «—». +- Пока оценены не все позиции, точности нет («—»), счётчики — по оценённому. +- Кнопки: «Скрыть анализ» (текстовая) и «Анализировать заново» (контурная, открывает лист запуска; пока идёт анализ, неактивна). + +### 21.6. Правила + +- Анализ — отдельный процесс движка (nice 10, потоки и память из настроек). Пока он идёт, живой движок стоит на паузе: строка движка «Пауза: идёт анализ партии» (с заглавной: это отдельная строка, а не хвост «гл. 26 · пауза»), без ▾; после анализа счёт продолжается сам. +- Экран погас или приложение ушло в фон — анализ останавливается (батарея, §8.3), посчитанное сохраняется; при возврате он продолжается сам с недостающих позиций. +- Выход из партии и ‹ › останавливают анализ; посчитанное хранится в кэше приложения и показывается при следующем открытии этой партии. +- Оценивается только основная линия; варианты не трогаются. + +## 22. Ревью отчёта по партии (2026-10-23) + +Что изменено в §21 по итогам ревью реализации (`ReviewViews.kt`, `GameScreen.kt`, `Notation.kt`) и снимков с эмулятора: + +- §21.1 — вход один: первый пункт ⋮; пункт неактивен, пока идёт первый анализ без оценок; «Скрыть анализ» убирает и панель, и отметки. +- §21.2 — при частичной оценке «Заново» (отдельная строка `review_restart`) и «Дополнить», без «Отмены»; время — только для считаемых позиций. +- §21.3 — строка 48 dp и график 40 dp (общая высота та же, 88 dp): цели касания по §12.2. Подписей стадий на графике нет. Ход «лучше было …» цветом `primary` как признак нажатия. Порядок состояний. TalkBack у графика без подсказки про жесты. Бюджет нотации и альбомная ориентация: при движке график скрыт. +- §21.4 — плашка не дублирует такой же авторский знак. +- §21.5 — отчёт в две колонки (белые | чёрные), лист открывается целиком. +- §21.6 — «Пауза: идёт анализ партии» с заглавной, без ▾. +- §12.3, §14.7 — озвучивание и таблица строк; правки «Скрыть анализ», «Лучшая линия · ход …», «к следующему такому ходу»; `review_no_line` удалить. +- По итогам тестирования (2026-10-23): поворот телефона во время анализа не останавливает его насовсем — анализ продолжается сам, как после возврата из фона; посчитанное пишется в кэш и по ходу работы (раз в 10 с), чтобы падение приложения не теряло минуты работы; «Дополнить» считает с тем же качеством, что и первый прогон (один отчёт — одно качество), поэтому оценка времени при «Дополнить» берёт прежнее качество, а выбор качества относится к «Заново»; у партии без ходов пункт ⋮ неактивен; пат в конце, как и мат, движку не отдаётся; в альбомной ориентации правая колонка не заходит под системные кнопки. diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index 5f01fe5..51a62db 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -26,8 +26,7 @@ egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `i | `engine_download.rs` | Скачивание официального Stockfish по запросу (решение 14): закреплённые архивы и SHA-256 по платформам, загрузка с прогрессом и отменой, проверка суммы, распаковка в каталог данных, пробный запуск | | `engine_offer.rs` | Окно «Для анализа нужен движок» (`docs/design/engine-download.md`): предложение, «уже установлен на компьютере», «файл пропал», ход загрузки, ошибки, индикатор скрытой загрузки; после установки запускает то, ради чего пришёл пользователь | | `engines.rs` | Поиск движков: встроенный Stockfish (`/lib/chesspenguin/stockfish` или `stockfish/` рядом с exe), системный `stockfish` в `PATH`; настройка при первом запуске, подсказки в настройках | -| `report.rs` | Метрики анализа партии без UI: шанс на победу, точность хода и партии, неточность/ошибка/зевок, средняя потеря сантипешек, стадии партии (формулы Lichess) | -| `review.rs` | Анализ партии целиком: фоновый поток с собственным процессом движка (`go nodes N`), кэш, `[%eval]` из PGN, график, вкладка «Отчёт», окно запуска, запись анализа в партию | +| `review.rs` | Анализ партии целиком на компьютере: фоновый поток задания, график, вкладка «Отчёт», окно запуска, запись анализа в партию. Оценки, суждения, точность, кэш и само задание движка (`go nodes N`) — в общем крейте `crates/game-review` (вместе с Android) | | `assets.rs`, `sound.rs` | Встроенные SVG-фигуры, темы доски, звуки (rodio в отдельном потоке) | | `settings.rs`, `settings_ui.rs` | JSON в `$XDG_CONFIG_HOME/chesspenguin/settings.json` (атомарная запись), окно настроек |