Compare commits
No commits in common. "main" and "feature/training-pgn-annotations-and-variations" have entirely different histories.
main
...
feature/tr
199 changed files with 20550 additions and 33451 deletions
|
|
@ -5,7 +5,7 @@
|
|||
- Исходное ТЗ: `техническое задание.txt`.
|
||||
- Пользовательские материалы: `designExample/`, `pgnFilesforExample/`, `engines/`.
|
||||
- Рабочий язык обсуждений и проектных заметок — русский; идентификаторы кода — английский.
|
||||
- Текущий этап: развитие выпускаемого продукта (релиз 2.5.2). Задачи и бэклог — `docs/dev/tasks.md`.
|
||||
- Текущий этап: развитие выпускаемого продукта (релиз 2.3.0). Задачи и бэклог — `docs/dev/tasks.md`.
|
||||
- Архитектура реализованной системы: `docs/architecture.md`; архитектурное предложение этапа исследования — `docs/research/architecture-proposal-2026-10-17.md`; исследования: `docs/research/`.
|
||||
- Журнал решений: `docs/decisions.md`; подтверждённые пользователем решения имеют приоритет над предложениями исследований.
|
||||
|
||||
|
|
@ -40,8 +40,4 @@
|
|||
|
||||
## Работа
|
||||
|
||||
Окна приложения для тестов и снимков запускать только через `scripts/dev/headless-run.sh -- ENV=… команда` (невидимый монитор Hyprland 1920×1080, без фокуса и курсора владельца); прямой запуск окна на мониторах владельца запрещён. Не запускать и не подменять службы сессии владельца (AT-SPI, D-Bus, порталы, ydotool и т. п.) для эмуляции ввода; нужное действие — через отладочный хук приложения.
|
||||
|
||||
Экономия (владелец, 2026-11-27): визуальная проверка — одно разрешение 1920×1080 и основная (тёмная) тема; светлая — только если меняются цвета. Минимум снимков: только те, что доказывают критерий; не снимать серии и другие разрешения без нужды, не держать несколько агентов на проверке одного и того же.
|
||||
|
||||
Не изменять исходное ТЗ и референсы. Не запускать неподтверждённые бинарники и незавершённые загрузки движков. Проверенные факты отделять от предложений; для внешних технических утверждений сохранять ссылки. Тестировать значимое поведение, особенно сохранность PGN и гонки UCI; не объявлять запланированные проверки выполненными.
|
||||
|
|
|
|||
47
CHANGELOG.md
47
CHANGELOG.md
|
|
@ -4,53 +4,6 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https
|
|||
|
||||
## [Unreleased]
|
||||
|
||||
## [2.5.2] — 2026-11-30
|
||||
|
||||
- Android: the «Analyse game» button is in the bottom bar next to the engine button and has the
|
||||
brilliant-move colour. Tap the previous/next arrows to go one move, or hold them to jump to the
|
||||
start/end of the line.
|
||||
- Android: simple opponent preparation. Pick an exact player name from a database or an open game,
|
||||
choose their colour, and study from your own side of the board. Continuations are shown by arrows
|
||||
and a frequency-sorted list with game counts and the selected player's wins/draws/losses; play a move
|
||||
on the board, from the list or with an arrow. Statistics use exact names, transpositions and main
|
||||
lines only, without engine analysis or changing the source games.
|
||||
|
||||
## [2.5.1] — 2026-11-28
|
||||
|
||||
- Desktop: select 1–100 games in a database and use «Find great moves» to analyse just those games.
|
||||
The confirmation shows how many selected games are hidden by the current filter; those games are
|
||||
included. Changing the selection after starting does not change the batch. Clear the selection to
|
||||
analyse the filtered games instead.
|
||||
|
||||
## [2.5.0] — 2026-11-27
|
||||
|
||||
- Desktop: find great moves in the filtered games of a database (up to 100). The «!! Find great moves»
|
||||
button on the right of the conditions line asks first with a time estimate, then Stockfish 19 goes
|
||||
through the games with «Analysed N of M» and «Stop»; games already analysed are taken from the cache.
|
||||
The summary adds up brilliant, great, inaccuracy, mistake and blunder moves, average centipawn loss and
|
||||
accuracy, and lists the brilliant moves; with a player in the filter only that player's moves count.
|
||||
A new «!!» column marks games with brilliant or great moves. Games against the engine wait for the search.
|
||||
- Desktop: select several games in a database (Ctrl/Shift-click, Shift+arrows, Ctrl+A) and make a new
|
||||
database of them («New database from selected…», Ctrl+Shift+S). The copy runs in the background with
|
||||
progress and cancel, never overwrites a file, keeps every game as «Add to database» does and skips only
|
||||
exact duplicates; the source database is not changed.
|
||||
- Desktop: a hint above the notation tells that arrows and circles can be drawn with the right mouse
|
||||
button and are saved in PGN; moves with arrows or circles get a small sign in the notation.
|
||||
- Desktop: the «Analyse game» button has the colour of a brilliant move.
|
||||
- Desktop opening training: four example repertoires — Spanish and Queen's Gambit for White, Najdorf and
|
||||
the Semi-Slav triangle for Black — with Russian comments in the Russian interface. Users who updated get
|
||||
the missing examples once; deleted examples do not come back. The repertoire panel is wider by default,
|
||||
names and progress are no longer cut, and side kings are drawn so White and Black read correctly on dark
|
||||
backgrounds.
|
||||
- Desktop: Enter in «Delete the game from the database?» no longer also opens the game.
|
||||
|
||||
## [2.4.0] — 2026-11-27
|
||||
|
||||
- Desktop play and opening training support multiple temporary right-button arrows and circles
|
||||
until the position changes. They are never written to PGN; shapes drawn in ordinary game
|
||||
analysis remain PGN annotations and are saved only with the game.
|
||||
- Desktop opening training rewritten to be simpler: one screen with repertoires and a clear daily session (reviews plus up to 10 new moves), new moves are shown before they are asked, mistakes show the right move and return in the same session, PGN comments and opening names are shown. Review all, train a branch and a lines view remain; modes, context parameters, the statistics dashboard and the both-colours mode are gone. Two example repertoires (Spanish for White, Najdorf for Black) are added on first use. Saved progress is kept.
|
||||
|
||||
## [2.3.0] — 2026-11-06
|
||||
|
||||
- Desktop opening training (α version) avoids repeated PGN parsing and repeated context planning during
|
||||
|
|
|
|||
29
Cargo.lock
generated
29
Cargo.lock
generated
|
|
@ -774,7 +774,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "chess-core"
|
||||
version = "2.5.2"
|
||||
version = "2.3.0"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"pgn-reader",
|
||||
|
|
@ -785,7 +785,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "chess-import"
|
||||
version = "2.5.2"
|
||||
version = "2.3.0"
|
||||
dependencies = [
|
||||
"chess-core",
|
||||
"encoding_rs",
|
||||
|
|
@ -798,7 +798,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "chess-openings"
|
||||
version = "2.5.2"
|
||||
version = "2.3.0"
|
||||
dependencies = [
|
||||
"chess-import",
|
||||
"serde",
|
||||
|
|
@ -807,7 +807,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "chesspenguin"
|
||||
version = "2.5.2"
|
||||
version = "2.3.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"base64 0.22.1",
|
||||
|
|
@ -840,7 +840,6 @@ dependencies = [
|
|||
"skrifa",
|
||||
"sys-locale",
|
||||
"tar",
|
||||
"thiserror 2.0.21",
|
||||
"trainer",
|
||||
"uci",
|
||||
"ureq",
|
||||
|
|
@ -855,7 +854,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "chesspenguin-web"
|
||||
version = "2.5.2"
|
||||
version = "2.3.0"
|
||||
dependencies = [
|
||||
"chesspenguin",
|
||||
"eframe",
|
||||
|
|
@ -1706,7 +1705,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "game-review"
|
||||
version = "2.5.2"
|
||||
version = "2.3.0"
|
||||
dependencies = [
|
||||
"chess-core",
|
||||
"chess-openings",
|
||||
|
|
@ -2427,7 +2426,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "maia"
|
||||
version = "2.5.2"
|
||||
version = "2.3.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"shakmaty",
|
||||
|
|
@ -2514,7 +2513,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "mobile-api"
|
||||
version = "2.5.2"
|
||||
version = "2.3.0"
|
||||
dependencies = [
|
||||
"chess-core",
|
||||
"chess-import",
|
||||
|
|
@ -3122,7 +3121,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
|||
|
||||
[[package]]
|
||||
name = "online-games"
|
||||
version = "2.5.2"
|
||||
version = "2.3.0"
|
||||
dependencies = [
|
||||
"chess-core",
|
||||
"serde",
|
||||
|
|
@ -3395,7 +3394,7 @@ checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
|
|||
|
||||
[[package]]
|
||||
name = "play"
|
||||
version = "2.5.2"
|
||||
version = "2.3.0"
|
||||
dependencies = [
|
||||
"chess-core",
|
||||
"getrandom 0.3.4",
|
||||
|
|
@ -3496,7 +3495,7 @@ checksum = "196a7c80b9a7652aba7cc070827516c2abe4ccdf53d128e1944003cf5726cff1"
|
|||
|
||||
[[package]]
|
||||
name = "prep"
|
||||
version = "2.5.2"
|
||||
version = "2.3.0"
|
||||
dependencies = [
|
||||
"chess-core",
|
||||
"chess-import",
|
||||
|
|
@ -3695,7 +3694,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "releases"
|
||||
version = "2.5.2"
|
||||
version = "2.3.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"ureq",
|
||||
|
|
@ -4693,7 +4692,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "trainer"
|
||||
version = "2.5.2"
|
||||
version = "2.3.0"
|
||||
dependencies = [
|
||||
"chess-core",
|
||||
"chrono",
|
||||
|
|
@ -4736,7 +4735,7 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
|||
|
||||
[[package]]
|
||||
name = "uci"
|
||||
version = "2.5.2"
|
||||
version = "2.3.0"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"libc",
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ members = [
|
|||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "2.5.2"
|
||||
version = "2.3.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.97"
|
||||
license = "GPL-3.0-or-later"
|
||||
|
|
|
|||
|
|
@ -45,19 +45,12 @@ import io.github.vrubelroman.chesspenguin.ui.NEW_GAME
|
|||
import io.github.vrubelroman.chesspenguin.ui.PLAY_GAME
|
||||
import io.github.vrubelroman.chesspenguin.ui.GamesScreen
|
||||
import io.github.vrubelroman.chesspenguin.ui.OnlineScreen
|
||||
import io.github.vrubelroman.chesspenguin.ui.PlayersScreen
|
||||
import io.github.vrubelroman.chesspenguin.ui.PrepScreen
|
||||
import io.github.vrubelroman.chesspenguin.ui.PrepStart
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable data object Databases : NavKey
|
||||
|
||||
@Serializable data class Games(val db: String) : NavKey
|
||||
|
||||
@Serializable data class Players(val db: String) : NavKey
|
||||
|
||||
@Serializable data class Preparation(val request: PrepStart) : NavKey
|
||||
|
||||
/// The game at `place` on the list of games found by `query` in the database (kept, so
|
||||
/// the same game comes back after Android restarts the app).
|
||||
@Serializable data class GameAt(val db: String, val place: Int, val query: String = "") : NavKey
|
||||
|
|
@ -195,35 +188,10 @@ fun MainNavigation() {
|
|||
}, onOpenDatabase = { id -> backStack.add(Games(id)) })
|
||||
}
|
||||
entry<Games> { key ->
|
||||
GamesScreen(
|
||||
key.db,
|
||||
onBack = { backStack.removeLastOrNull() },
|
||||
onGame = { place, query -> backStack.add(GameAt(key.db, place, query)) },
|
||||
onPlayers = { backStack.add(Players(key.db)) },
|
||||
)
|
||||
}
|
||||
entry<Players> { key ->
|
||||
PlayersScreen(
|
||||
key.db,
|
||||
onBack = { backStack.removeLastOrNull() },
|
||||
onPrepare = { player, white ->
|
||||
backStack.add(Preparation(PrepStart(db = key.db, player = player.name, white = white)))
|
||||
},
|
||||
)
|
||||
}
|
||||
entry<Preparation> { key ->
|
||||
PrepScreen(key.request, onBack = { backStack.removeLastOrNull() })
|
||||
GamesScreen(key.db, onBack = { backStack.removeLastOrNull() }, onGame = { place, query -> backStack.add(GameAt(key.db, place, query)) })
|
||||
}
|
||||
entry<GameAt> { key ->
|
||||
GameScreen(
|
||||
key.db,
|
||||
key.place,
|
||||
key.query,
|
||||
onBack = { backStack.removeLastOrNull() },
|
||||
onSettings = { backStack.add(SettingsKey) },
|
||||
onPlayGame = { backStack.add(PlayKey) },
|
||||
onPrepare = { backStack.add(Preparation(it)) },
|
||||
)
|
||||
GameScreen(key.db, key.place, key.query, onBack = { backStack.removeLastOrNull() }, onSettings = { backStack.add(SettingsKey) }, onPlayGame = { backStack.add(PlayKey) })
|
||||
}
|
||||
entry<SettingsKey> {
|
||||
SettingsScreen(
|
||||
|
|
|
|||
|
|
@ -1,129 +0,0 @@
|
|||
package io.github.vrubelroman.chesspenguin.data
|
||||
|
||||
import io.github.vrubelroman.chesspenguin.ui.PlayerPage
|
||||
import io.github.vrubelroman.chesspenguin.ui.PlayerSummary
|
||||
import io.github.vrubelroman.chesspenguin.ui.PrepContinuation
|
||||
import io.github.vrubelroman.chesspenguin.ui.PrepGameMatch
|
||||
import io.github.vrubelroman.chesspenguin.ui.PrepOutOfMemory
|
||||
import io.github.vrubelroman.chesspenguin.ui.PrepPlayerNotFound
|
||||
import io.github.vrubelroman.chesspenguin.ui.PrepPosition
|
||||
import io.github.vrubelroman.chesspenguin.ui.PrepSearchFailed
|
||||
import io.github.vrubelroman.chesspenguin.ui.PrepStart
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlin.coroutines.coroutineContext
|
||||
import uniffi.mobile_api.Database
|
||||
import uniffi.mobile_api.PrepPhase
|
||||
import uniffi.mobile_api.PrepResult
|
||||
import uniffi.mobile_api.PrepSearch as RustPrepSearch
|
||||
|
||||
internal data class PrepQuery(
|
||||
val player: String,
|
||||
val white: Boolean,
|
||||
val fen: String,
|
||||
)
|
||||
|
||||
internal fun PrepStart.query(fen: String): PrepQuery = PrepQuery(player, white, fen)
|
||||
|
||||
/// The Android side of mobile-api's preparation contract. Database aggregation stays in
|
||||
/// Rust; the object being closed is the search, never the library's shared Database.
|
||||
internal interface PrepBackend {
|
||||
suspend fun players(query: String, offset: Int, limit: Int): PlayerPage
|
||||
suspend fun position(query: PrepQuery): PrepPosition
|
||||
fun cancel()
|
||||
fun close()
|
||||
}
|
||||
|
||||
internal object PrepBackends {
|
||||
fun open(database: Database): PrepBackend = RustPrepBackend(database)
|
||||
}
|
||||
|
||||
private class RustPrepBackend(private val database: Database) : PrepBackend {
|
||||
private val lock = Any()
|
||||
private val playerIds = java.util.concurrent.ConcurrentHashMap<String, UInt>()
|
||||
private var active: RustPrepSearch? = null
|
||||
@Volatile private var closed = false
|
||||
|
||||
override suspend fun players(query: String, offset: Int, limit: Int): PlayerPage {
|
||||
coroutineContext.ensureActive()
|
||||
if (closed) throw CancellationException("The player list is closed")
|
||||
val start = offset.coerceAtLeast(0)
|
||||
val answer = database.suggestPlayers(query, start.toUInt(), limit.coerceIn(0, 200).toUInt())
|
||||
val players = answer.players.map {
|
||||
PlayerSummary(it.id.toInt(), it.name, it.games.toInt(), it.whiteGames.toInt(), it.blackGames.toInt())
|
||||
}
|
||||
val end = start + players.size
|
||||
return PlayerPage(players, answer.total.toInt(), end.takeIf { players.isNotEmpty() && it < answer.total.toInt() })
|
||||
}
|
||||
|
||||
override suspend fun position(query: PrepQuery): PrepPosition {
|
||||
coroutineContext.ensureActive()
|
||||
val id = findPlayer(query.player)
|
||||
coroutineContext.ensureActive()
|
||||
val search = synchronized(lock) {
|
||||
if (closed) throw CancellationException("The position search is closed")
|
||||
active?.cancel()
|
||||
database.preparePosition(id, query.white, query.fen).also { active = it }
|
||||
}
|
||||
try {
|
||||
while (true) {
|
||||
val state = search.state()
|
||||
when (state.phase) {
|
||||
PrepPhase.GAMES, PrepPhase.INDEX, PrepPhase.SEARCH -> delay(25)
|
||||
PrepPhase.READY -> return state.result?.toUi()
|
||||
?: throw PrepSearchFailed(state.failure.ifEmpty { "The position search returned no result" })
|
||||
PrepPhase.CANCELLED -> throw CancellationException("The position search was cancelled")
|
||||
PrepPhase.NO_MEMORY -> throw PrepOutOfMemory()
|
||||
PrepPhase.FAILED -> throw PrepSearchFailed(state.failure.ifEmpty { "The position search failed" })
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
synchronized(lock) {
|
||||
if (active === search) active = null
|
||||
}
|
||||
search.close()
|
||||
}
|
||||
}
|
||||
|
||||
private fun findPlayer(name: String): UInt {
|
||||
playerIds[name]?.let { return it }
|
||||
var offset = 0
|
||||
while (true) {
|
||||
val page = database.suggestPlayers(name, offset.toUInt(), 200u)
|
||||
page.players.firstOrNull { it.name == name }?.let {
|
||||
playerIds[name] = it.id
|
||||
return it.id
|
||||
}
|
||||
if (page.players.isEmpty()) break
|
||||
offset += page.players.size
|
||||
if (offset >= page.total.toInt()) break
|
||||
}
|
||||
throw PrepPlayerNotFound(name)
|
||||
}
|
||||
|
||||
override fun cancel() {
|
||||
synchronized(lock) { active?.cancel() }
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
synchronized(lock) {
|
||||
closed = true
|
||||
active?.cancel()
|
||||
active = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun PrepResult.toUi() = PrepPosition(
|
||||
games = games.toInt(),
|
||||
continuations = continuations.map {
|
||||
PrepContinuation(it.uci, it.san, it.count.toInt(), it.wins.toInt(), it.draws.toInt(), it.losses.toInt(), it.unknown.toInt())
|
||||
},
|
||||
endedHere = ended.toInt(),
|
||||
noNormalContinuation = noNormalContinuation.toInt(),
|
||||
unknownResults = unknown.toInt(),
|
||||
playerToMove = playerToMove,
|
||||
matches = matches.map { PrepGameMatch(it.index, it.ply) },
|
||||
matchesTotal = matchesTotal.toInt(),
|
||||
)
|
||||
|
|
@ -36,9 +36,7 @@ import androidx.compose.ui.platform.LocalViewConfiguration
|
|||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.semantics.CustomAccessibilityAction
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.customActions
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.drawText
|
||||
|
|
@ -155,15 +153,6 @@ class BoardInput(
|
|||
/// An arrow on the board: a comment's `[%cal]` or the engine's best move.
|
||||
data class BoardArrow(val from: String, val to: String, val color: Color, val weight: Float = 1f)
|
||||
|
||||
/// A continuation attached to an arrow. Several UCI moves may share one direction
|
||||
/// (promotions); in that case the callback receives all of them for an explicit choice.
|
||||
data class BoardArrowMove(
|
||||
val uci: String,
|
||||
val from: String,
|
||||
val to: String,
|
||||
val actionLabel: String,
|
||||
)
|
||||
|
||||
/// A marked square of a comment (`[%csl]`), drawn as a ring.
|
||||
data class BoardMark(val square: String, val color: Color)
|
||||
|
||||
|
|
@ -183,56 +172,6 @@ fun markColor(letter: String): Color = when (letter) {
|
|||
/// The engine's arrows are blue, as on the desktop.
|
||||
val EngineArrow = Color(0, 48, 136, 160)
|
||||
|
||||
internal fun boardCell(index: Int, square: Float, flipped: Boolean): Offset {
|
||||
val row = index / 8
|
||||
val col = index % 8
|
||||
val (r, c) = if (flipped) (7 - row) to (7 - col) else row to col
|
||||
return Offset(c * square, r * square)
|
||||
}
|
||||
|
||||
private data class ArrowGeometry(val start: Offset, val base: Offset, val tip: Offset)
|
||||
|
||||
private fun arrowGeometry(from: Offset, to: Offset, square: Float, weight: Float): ArrowGeometry? {
|
||||
val delta = to - from
|
||||
val length = delta.getDistance()
|
||||
if (length < 1f) return null
|
||||
val direction = delta / length
|
||||
val headLength = square * 0.42f * kotlin.math.sqrt(weight)
|
||||
val tip = to - direction * (square * 0.12f)
|
||||
return ArrowGeometry(from + direction * (square * 0.2f), tip - direction * headLength, tip)
|
||||
}
|
||||
|
||||
private fun distanceToSegment(point: Offset, start: Offset, end: Offset): Float {
|
||||
val segment = end - start
|
||||
val length2 = segment.x * segment.x + segment.y * segment.y
|
||||
if (length2 < 1f) return (point - start).getDistance()
|
||||
val t = (((point - start).x * segment.x + (point - start).y * segment.y) / length2).coerceIn(0f, 1f)
|
||||
return (point - (start + segment * t)).getDistance()
|
||||
}
|
||||
|
||||
/// Hit testing uses the same square transform and arrow endpoints as drawing. The head
|
||||
/// has at least a 48 dp target; shaft corridors stay narrower so neighbours do not all
|
||||
/// become one arbitrary shortcut.
|
||||
internal fun arrowHits(
|
||||
point: Offset,
|
||||
square: Float,
|
||||
flipped: Boolean,
|
||||
moves: List<BoardArrowMove>,
|
||||
headRadius: Float,
|
||||
): List<BoardArrowMove> {
|
||||
if (square <= 0f || point.x < 0 || point.y < 0 || point.x > square * 8 || point.y > square * 8) return emptyList()
|
||||
val corridor = maxOf(square * 0.16f, headRadius * 0.5f)
|
||||
return moves.filter { move ->
|
||||
val from = squareIndex(move.from) ?: return@filter false
|
||||
val to = squareIndex(move.to) ?: return@filter false
|
||||
val center = Offset(square / 2, square / 2)
|
||||
val geometry = arrowGeometry(boardCell(from, square, flipped) + center, boardCell(to, square, flipped) + center, square, 1f) ?: return@filter false
|
||||
(point - geometry.tip).getDistance() <= headRadius ||
|
||||
distanceToSegment(point, geometry.start, geometry.base) <= corridor ||
|
||||
distanceToSegment(point, geometry.base, geometry.tip) <= corridor
|
||||
}
|
||||
}
|
||||
|
||||
/// The board: full width, the chosen board and pieces, the last move lit, the
|
||||
/// coordinates inside the edge squares (as on Lichess). With `input` a move is made by
|
||||
/// tapping a piece and then a square, or by dragging it (android-play.md §29.2–29.3);
|
||||
|
|
@ -249,8 +188,6 @@ fun Board(
|
|||
description: String,
|
||||
modifier: Modifier = Modifier,
|
||||
arrows: List<BoardArrow> = emptyList(),
|
||||
arrowMoves: List<BoardArrowMove> = emptyList(),
|
||||
onArrowMoves: (List<String>) -> Unit = {},
|
||||
marks: List<BoardMark> = emptyList(),
|
||||
check: Boolean = false,
|
||||
animated: Boolean = true,
|
||||
|
|
@ -295,8 +232,6 @@ fun Board(
|
|||
var dragAt by remember(fen) { mutableStateOf<Offset?>(null) }
|
||||
val slop = LocalViewConfiguration.current.touchSlop
|
||||
val currentInput = androidx.compose.runtime.rememberUpdatedState(input)
|
||||
val currentArrowMoves = androidx.compose.runtime.rememberUpdatedState(arrowMoves)
|
||||
val currentArrowAction = androidx.compose.runtime.rememberUpdatedState(onArrowMoves)
|
||||
val lift = with(density) { 22.dp.toPx() }
|
||||
fun indexAt(p: Offset, sq: Float): Int? {
|
||||
val col = (p.x / sq).toInt()
|
||||
|
|
@ -313,8 +248,7 @@ fun Board(
|
|||
val startName = squareName(start)
|
||||
val movable = inp.targets(startName).isNotEmpty()
|
||||
val was = selected
|
||||
// A tap on a target of the piece chosen makes the move. An already chosen
|
||||
// piece always has priority over continuation arrows.
|
||||
// A tap on a target of the piece chosen makes the move.
|
||||
if (was != null && start != was) {
|
||||
inp.move(squareName(was), startName)?.let { m ->
|
||||
selected = null
|
||||
|
|
@ -323,7 +257,6 @@ fun Board(
|
|||
}
|
||||
}
|
||||
if (movable) selected = start
|
||||
val shortcutCandidate = was == null && !movable
|
||||
var dragging = false
|
||||
while (true) {
|
||||
val e = awaitPointerEvent()
|
||||
|
|
@ -338,29 +271,17 @@ fun Board(
|
|||
inp.onMove(m)
|
||||
}
|
||||
// A drop elsewhere: the piece goes back, still chosen.
|
||||
} else {
|
||||
if (!movable || start == was) {
|
||||
// A tap on the same piece, an empty square or the other side's
|
||||
// piece: nothing chosen any more.
|
||||
selected = null
|
||||
}
|
||||
if (shortcutCandidate) {
|
||||
val hits = arrowHits(
|
||||
c.position,
|
||||
sq,
|
||||
flipped,
|
||||
currentArrowMoves.value,
|
||||
with(density) { 24.dp.toPx() },
|
||||
)
|
||||
if (hits.isNotEmpty()) currentArrowAction.value(hits.map { it.uci }.distinct())
|
||||
}
|
||||
} else if (!movable || start == was) {
|
||||
// A tap on the same piece, an empty square or the other side's
|
||||
// piece: nothing chosen any more.
|
||||
selected = null
|
||||
}
|
||||
c.consume()
|
||||
break
|
||||
}
|
||||
if (!dragging && (c.position - down.position).getDistance() > slop) dragging = true
|
||||
if (movable && !dragging && (c.position - down.position).getDistance() > slop) dragging = true
|
||||
if (dragging) {
|
||||
if (movable) dragAt = c.position
|
||||
dragAt = c.position
|
||||
c.consume()
|
||||
}
|
||||
}
|
||||
|
|
@ -371,21 +292,16 @@ fun Board(
|
|||
.aspectRatio(1f)
|
||||
.onSizeChanged { side = it.width }
|
||||
.then(touch)
|
||||
.semantics {
|
||||
contentDescription = description
|
||||
if (arrowMoves.isNotEmpty()) {
|
||||
customActions = arrowMoves.map { move ->
|
||||
CustomAccessibilityAction(move.actionLabel) {
|
||||
onArrowMoves(listOf(move.uci))
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
.semantics { contentDescription = description },
|
||||
) {
|
||||
val sq = size.width / 8f
|
||||
val px = sq.toInt()
|
||||
fun cell(i: Int): Offset = boardCell(i, sq, flipped)
|
||||
fun cell(i: Int): Offset {
|
||||
val row = i / 8
|
||||
val col = i % 8
|
||||
val (r, c) = if (flipped) (7 - row) to (7 - col) else row to col
|
||||
return Offset(c * sq, r * sq)
|
||||
}
|
||||
val image = texture
|
||||
if (image != null) {
|
||||
// The squares of the image are the same seen from either side: it is not turned.
|
||||
|
|
@ -514,17 +430,22 @@ fun Board(
|
|||
/// An arrow as on the desktop (board.rs `draw_arrow`): a shaft and a head that stops
|
||||
/// short of the square's center.
|
||||
private fun DrawScope.drawArrow(from: Offset, to: Offset, sq: Float, a: BoardArrow) {
|
||||
val geometry = arrowGeometry(from, to, sq, a.weight) ?: return
|
||||
val d = to - from
|
||||
val dir = d / d.getDistance()
|
||||
val len = d.getDistance()
|
||||
if (len < 1f) return
|
||||
val dir = d / len
|
||||
val width = sq * 0.16f * a.weight
|
||||
val headLen = sq * 0.42f * kotlin.math.sqrt(a.weight)
|
||||
val headW = sq * 0.38f * kotlin.math.sqrt(a.weight)
|
||||
val tip = to - dir * (sq * 0.12f)
|
||||
val base = tip - dir * headLen
|
||||
val start = from + dir * (sq * 0.2f)
|
||||
val normal = Offset(-dir.y, dir.x)
|
||||
drawLine(a.color, geometry.start, geometry.base, strokeWidth = width)
|
||||
drawLine(a.color, start, base, strokeWidth = width)
|
||||
val head = Path().apply {
|
||||
moveTo(geometry.tip.x, geometry.tip.y)
|
||||
lineTo(geometry.base.x + normal.x * headW, geometry.base.y + normal.y * headW)
|
||||
lineTo(geometry.base.x - normal.x * headW, geometry.base.y - normal.y * headW)
|
||||
moveTo(tip.x, tip.y)
|
||||
lineTo(base.x + normal.x * headW, base.y + normal.y * headW)
|
||||
lineTo(base.x - normal.x * headW, base.y - normal.y * headW)
|
||||
close()
|
||||
}
|
||||
drawPath(head, a.color)
|
||||
|
|
|
|||
|
|
@ -1,19 +0,0 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
internal enum class ReviewAction { Start, Report, Wait }
|
||||
|
||||
/// The same availability the menu entry had, now used by the visible bottom-bar button.
|
||||
internal fun reviewEnabled(
|
||||
hasMoves: Boolean,
|
||||
gameOn: Boolean,
|
||||
sessionGame: Boolean,
|
||||
loaded: Boolean,
|
||||
hasData: Boolean,
|
||||
running: Boolean,
|
||||
): Boolean = hasMoves && !gameOn && (sessionGame || loaded) && (hasData || !running)
|
||||
|
||||
internal fun reviewAction(hasData: Boolean, running: Boolean): ReviewAction = when {
|
||||
hasData -> ReviewAction.Report
|
||||
running -> ReviewAction.Wait
|
||||
else -> ReviewAction.Start
|
||||
}
|
||||
|
|
@ -5,20 +5,19 @@ import android.content.res.Configuration
|
|||
import android.content.Intent
|
||||
import android.view.HapticFeedbackConstants
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.indication
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.PressInteraction
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.WindowInsetsSides
|
||||
import androidx.compose.foundation.layout.navigationBars
|
||||
|
|
@ -34,7 +33,6 @@ import androidx.compose.foundation.layout.size
|
|||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
|
||||
import androidx.compose.material.icons.outlined.Memory
|
||||
|
|
@ -46,10 +44,11 @@ import androidx.compose.material.icons.rounded.SmartToy
|
|||
import androidx.compose.material.icons.rounded.VerticalAlignTop
|
||||
import androidx.compose.material.icons.rounded.ChevronRight
|
||||
import androidx.compose.material.icons.rounded.Download
|
||||
import androidx.compose.material.icons.rounded.FirstPage
|
||||
import androidx.compose.material.icons.rounded.LastPage
|
||||
import androidx.compose.material.icons.rounded.Memory
|
||||
import androidx.compose.material.icons.rounded.MoreVert
|
||||
import androidx.compose.material.icons.rounded.PlayArrow
|
||||
import androidx.compose.material.icons.rounded.QueryStats
|
||||
import androidx.compose.material.icons.rounded.SwapVert
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
|
|
@ -71,6 +70,7 @@ import androidx.compose.material3.Surface
|
|||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.ripple
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
|
|
@ -85,7 +85,6 @@ import androidx.compose.runtime.saveable.rememberSaveable
|
|||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.scale
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
|
|
@ -95,14 +94,10 @@ import androidx.compose.ui.platform.LocalContext
|
|||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.CustomAccessibilityAction
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.customActions
|
||||
import androidx.compose.ui.semantics.disabled
|
||||
import androidx.compose.ui.semantics.onClick
|
||||
import androidx.compose.ui.semantics.onLongClick
|
||||
import androidx.compose.ui.semantics.role
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.semantics.stateDescription
|
||||
|
|
@ -124,6 +119,7 @@ import io.github.vrubelroman.chesspenguin.data.enginePosition
|
|||
import io.github.vrubelroman.chesspenguin.theme.LocalChessColors
|
||||
import io.github.vrubelroman.chesspenguin.theme.Tabular
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
|
@ -151,7 +147,6 @@ fun GameScreen(
|
|||
onSettings: () -> Unit,
|
||||
onPlayGame: () -> Unit = {},
|
||||
onOpenDatabase: (String) -> Unit = {},
|
||||
onPrepare: (PrepStart) -> Unit = {},
|
||||
) {
|
||||
val app = app()
|
||||
val context = LocalContext.current
|
||||
|
|
@ -300,7 +295,6 @@ fun GameScreen(
|
|||
val reviewCycle = remember(place) { HashMap<Pair<Boolean, MoveJudgement>, Int>() }
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
var info by remember { mutableStateOf(false) }
|
||||
var prepSheet by remember(place) { mutableStateOf(false) }
|
||||
@Suppress("DEPRECATION")
|
||||
val clipboard = androidx.compose.ui.platform.LocalClipboardManager.current
|
||||
val pgnCopied = stringResource(R.string.pgn_copied)
|
||||
|
|
@ -337,9 +331,6 @@ fun GameScreen(
|
|||
// The player bars above and below the board (§7.11); the top bar names the event.
|
||||
val whiteName = tag("White").trim().takeIf { it.isNotEmpty() && it != "?" }
|
||||
val blackName = tag("Black").trim().takeIf { it.isNotEmpty() && it != "?" }
|
||||
val prepPathAvailable = g?.let { data ->
|
||||
prepStartFromGame(data, current, db, whiteName ?: blackName.orEmpty(), whiteName != null) != null
|
||||
} == true
|
||||
val whiteLabel = stringResource(R.string.tag_white)
|
||||
val blackLabel = stringResource(R.string.tag_black)
|
||||
val resultText = g?.let { resultLine(context, it.result) } ?: ""
|
||||
|
|
@ -439,24 +430,6 @@ fun GameScreen(
|
|||
val reviewMarks = remember(rs) { rs?.moves?.associate { it.node.toInt() to it.judgement } ?: emptyMap() }
|
||||
val currentMark = if (reviewShown) rs.moves.firstOrNull { it.node.toInt() == current } else null
|
||||
|
||||
// The one visible entry to the report: start it, or bring its panel back and open it.
|
||||
fun openReview() {
|
||||
reviewHidden = false
|
||||
val e = edit
|
||||
if ((newGame || playGame) && e != null && rs == null) {
|
||||
scope.launch {
|
||||
review.openSession("${held.key}/${System.nanoTime()}", e)
|
||||
reviewStart = true
|
||||
}
|
||||
return
|
||||
}
|
||||
when (reviewAction(rs?.hasData == true, rs?.running == true)) {
|
||||
ReviewAction.Report -> reviewReport = true
|
||||
ReviewAction.Wait -> {}
|
||||
ReviewAction.Start -> reviewStart = true
|
||||
}
|
||||
}
|
||||
|
||||
fun buzz(edge: Boolean) {
|
||||
if (prefs.vibration) view.performHapticFeedback(if (edge) HapticFeedbackConstants.CONFIRM else HapticFeedbackConstants.CLOCK_TICK)
|
||||
}
|
||||
|
|
@ -810,13 +783,6 @@ fun GameScreen(
|
|||
fun forward() {
|
||||
if (preview != null) stepPreview(1) else node?.children?.firstOrNull()?.let { go(it.toInt()) }
|
||||
}
|
||||
fun start() {
|
||||
preview?.let {
|
||||
preview = it.copy(step = 0)
|
||||
return
|
||||
}
|
||||
go(0)
|
||||
}
|
||||
fun end() {
|
||||
preview?.let {
|
||||
preview = it.copy(step = it.line.steps.size - 1)
|
||||
|
|
@ -890,62 +856,24 @@ fun GameScreen(
|
|||
}
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
|
||||
Surface(color = MaterialTheme.colorScheme.surfaceContainer) {
|
||||
BoxWithConstraints(Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp)) {
|
||||
val compact = maxWidth < 320.dp
|
||||
val narrow = maxWidth < 360.dp
|
||||
val engineSlot = if (compact) 52f else if (narrow) 56f else 60f
|
||||
val reviewSlot = if (compact) 52f else if (narrow) 88f else 96f
|
||||
val moveSlot = if (compact || narrow) 64f else 78f
|
||||
Row(Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) {
|
||||
EngineButton(
|
||||
on = engineOn,
|
||||
needsDownload = !engineReady && !files.builtIn,
|
||||
loading = netState as? NetState.Loading,
|
||||
modifier = Modifier.weight(engineSlot),
|
||||
onClick = ::toggleEngine,
|
||||
)
|
||||
BarButton(Icons.Rounded.SwapVert, stringResource(R.string.flip), true, Modifier.weight(48f)) { flipped = !flipped }
|
||||
|
||||
BarButton(
|
||||
icon = Icons.Rounded.PlayArrow,
|
||||
label = stringResource(R.string.move_back),
|
||||
description = stringResource(R.string.move_back),
|
||||
enabled = canBack,
|
||||
modifier = Modifier.weight(moveSlot),
|
||||
iconSize = 32,
|
||||
mirrored = true,
|
||||
onLongClickLabel = stringResource(R.string.to_start),
|
||||
onLongClick = ::start,
|
||||
onClick = ::back,
|
||||
)
|
||||
BarButton(
|
||||
icon = Icons.Rounded.PlayArrow,
|
||||
label = stringResource(R.string.move_forward),
|
||||
description = stringResource(R.string.move_forward),
|
||||
enabled = canForward,
|
||||
modifier = Modifier.weight(moveSlot),
|
||||
iconSize = 32,
|
||||
onLongClickLabel = stringResource(R.string.to_end),
|
||||
onLongClick = ::end,
|
||||
onClick = ::forward,
|
||||
)
|
||||
ReviewButton(
|
||||
report = rs?.hasData == true,
|
||||
enabled = reviewEnabled(
|
||||
hasMoves = hasMoves,
|
||||
gameOn = gameOn,
|
||||
sessionGame = newGame || playGame,
|
||||
loaded = rs != null,
|
||||
hasData = rs?.hasData == true,
|
||||
running = rs?.running == true,
|
||||
) && !preparingReview,
|
||||
preparing = preparingReview,
|
||||
progress = if (rs?.running == true) rs.done.toInt() to rs.total.toInt() else null,
|
||||
showLabel = !compact,
|
||||
modifier = Modifier.weight(reviewSlot),
|
||||
onClick = ::openReview,
|
||||
)
|
||||
Row(
|
||||
Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
EngineButton(
|
||||
on = engineOn,
|
||||
needsDownload = !engineReady && !files.builtIn,
|
||||
loading = netState as? NetState.Loading,
|
||||
modifier = Modifier.weight(1.2f),
|
||||
onClick = ::toggleEngine,
|
||||
)
|
||||
BarButton(Icons.Rounded.SwapVert, stringResource(R.string.flip), true, Modifier.weight(1f)) { flipped = !flipped }
|
||||
BarButton(Icons.Rounded.FirstPage, stringResource(R.string.to_start), canBack, Modifier.weight(1f)) {
|
||||
if (preview != null) preview = null else go(0)
|
||||
}
|
||||
BarButton(Icons.Rounded.PlayArrow, stringResource(R.string.move_back), canBack, Modifier.weight(1.5f), 32, repeat = true, mirrored = true) { back() }
|
||||
BarButton(Icons.Rounded.PlayArrow, stringResource(R.string.move_forward), canForward, Modifier.weight(1.5f), 32, repeat = true) { forward() }
|
||||
BarButton(Icons.Rounded.LastPage, stringResource(R.string.to_end), canForward, Modifier.weight(1f)) { end() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -979,7 +907,6 @@ fun GameScreen(
|
|||
if (f != null && t != null) {
|
||||
add(BoardArrow(f, t, EngineArrow.copy(alpha = if (i == 0) 0.63f else 0.35f), if (i == 0) 1f else 0.7f))
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1249,32 +1176,32 @@ fun GameScreen(
|
|||
undo()
|
||||
})
|
||||
}
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(if (rs?.hasData == true) R.string.review_report_menu else R.string.review_menu)) },
|
||||
// During the first analysis the panel already shows its progress (§21.1).
|
||||
enabled = hasMoves && !gameOn && ((newGame || playGame) || (rs != null && (rs.hasData || !rs.running))),
|
||||
onClick = {
|
||||
menu = false
|
||||
reviewHidden = false
|
||||
val e = edit
|
||||
if ((newGame || playGame) && e != null && rs == null) {
|
||||
scope.launch {
|
||||
review.openSession("${held.key}/${System.nanoTime()}", e)
|
||||
reviewStart = true
|
||||
}
|
||||
return@DropdownMenuItem
|
||||
}
|
||||
when {
|
||||
rs?.hasData == true -> reviewReport = true
|
||||
rs?.running == true -> {}
|
||||
else -> reviewStart = true
|
||||
}
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.game_info)) }, enabled = g != null, onClick = {
|
||||
menu = false
|
||||
info = true
|
||||
})
|
||||
if (!newGame && !playGame && (whiteName != null || blackName != null)) {
|
||||
val reason = when {
|
||||
preview != null -> stringResource(R.string.prep_close_engine_line)
|
||||
!prepPathAvailable -> stringResource(R.string.prep_null_move_unavailable)
|
||||
else -> null
|
||||
}
|
||||
DropdownMenuItem(
|
||||
text = {
|
||||
Column {
|
||||
Text(stringResource(R.string.prep_opponent))
|
||||
if (reason != null) {
|
||||
Text(reason, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled = reason == null,
|
||||
onClick = {
|
||||
menu = false
|
||||
prepSheet = true
|
||||
},
|
||||
)
|
||||
}
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.copy_pgn)) }, enabled = g != null, onClick = {
|
||||
menu = false
|
||||
scope.launch {
|
||||
|
|
@ -1363,42 +1290,6 @@ fun GameScreen(
|
|||
}
|
||||
}
|
||||
}
|
||||
if (prepSheet && g != null) {
|
||||
androidx.compose.material3.ModalBottomSheet(onDismissRequest = { prepSheet = false }) {
|
||||
Column(Modifier.fillMaxWidth().padding(bottom = 24.dp)) {
|
||||
Text(
|
||||
stringResource(R.string.prep_title),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp),
|
||||
)
|
||||
listOfNotNull(
|
||||
whiteName?.let { true to it },
|
||||
blackName?.let { false to it },
|
||||
).forEach { (white, name) ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().heightIn(min = 64.dp).clickable {
|
||||
prepStartFromGame(g, current, db, name, white)?.let {
|
||||
prepSheet = false
|
||||
onPrepare(it)
|
||||
}
|
||||
}.padding(horizontal = 24.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
SideDisc(white)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column {
|
||||
PlayerName(name, MaterialTheme.typography.bodyLarge)
|
||||
Text(
|
||||
stringResource(if (white) R.string.prep_as_white else R.string.prep_as_black),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (info && g != null) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { info = false },
|
||||
|
|
@ -1726,92 +1617,6 @@ private fun EngineButton(on: Boolean, needsDownload: Boolean, loading: NetState.
|
|||
}
|
||||
}
|
||||
|
||||
/// The visible entry to whole-game analysis. The invitation uses the report's «!!»
|
||||
/// teal; a finished report drops the fill. Progress and stopping stay in `ReviewPanel`.
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
internal fun ReviewButton(
|
||||
report: Boolean,
|
||||
enabled: Boolean,
|
||||
modifier: Modifier,
|
||||
preparing: Boolean = false,
|
||||
progress: Pair<Int, Int>? = null,
|
||||
showLabel: Boolean = true,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val label = when {
|
||||
progress != null && !report -> "${progress.first}/${progress.second}"
|
||||
report -> stringResource(R.string.review_report)
|
||||
else -> stringResource(R.string.play_analyse_short)
|
||||
}
|
||||
val description = stringResource(if (report) R.string.review_report_menu else R.string.review_menu)
|
||||
val spokenState = when {
|
||||
preparing -> stringResource(R.string.preparing_engine)
|
||||
progress != null -> stringResource(R.string.review_progress, progress.first, progress.second)
|
||||
else -> null
|
||||
}
|
||||
val action by rememberUpdatedState(onClick)
|
||||
val dark = LocalChessColors.current.dark
|
||||
val accent = nagColor(3, dark) ?: LocalContentColor.current
|
||||
val disabled = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
|
||||
val filled = enabled && !report && !preparing && progress == null
|
||||
val iconColor = when {
|
||||
!enabled -> disabled
|
||||
filled && dark -> Color(0xFF1B1B1B)
|
||||
filled -> Color.White
|
||||
else -> accent
|
||||
}
|
||||
Column(
|
||||
modifier
|
||||
.fillMaxHeight()
|
||||
.clearAndSetSemantics {
|
||||
contentDescription = description
|
||||
role = Role.Button
|
||||
if (enabled) onClick(description) { action(); true } else disabled()
|
||||
spokenState?.let { stateDescription = it }
|
||||
}
|
||||
.combinedClickable(
|
||||
enabled = enabled,
|
||||
onClickLabel = description,
|
||||
role = Role.Button,
|
||||
hapticFeedbackEnabled = false,
|
||||
onClick = action,
|
||||
),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(36.dp).clip(RoundedCornerShape(10.dp)).background(if (filled) accent else Color.Transparent),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Rounded.QueryStats, null, tint = iconColor)
|
||||
when {
|
||||
progress != null -> CircularProgressIndicator(
|
||||
progress = { progress.first.toFloat() / progress.second.coerceAtLeast(1) },
|
||||
modifier = Modifier.size(34.dp),
|
||||
color = if (enabled) accent else disabled,
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
preparing -> CircularProgressIndicator(
|
||||
modifier = Modifier.size(34.dp),
|
||||
color = if (enabled) accent else disabled,
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (showLabel) {
|
||||
Text(
|
||||
label,
|
||||
style = MaterialTheme.typography.labelSmall.merge(Tabular),
|
||||
color = if (enabled) MaterialTheme.colorScheme.onSurface else disabled,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Box(Modifier.padding(top = 2.dp).width(24.dp).height(2.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/// The row of continuations at a fork (§7.5): the line's own move first and filled.
|
||||
@Composable
|
||||
private fun Forks(moves: List<MoveNode>, san: (String) -> AnnotatedString, onMove: (Int) -> Unit) {
|
||||
|
|
@ -1831,50 +1636,57 @@ private fun Forks(moves: List<MoveNode>, san: (String) -> AnnotatedString, onMov
|
|||
}
|
||||
}
|
||||
|
||||
/// A button of the bottom bar. A tap is one action; an optional long press is a separate
|
||||
/// action, never an auto-repeat. Long-press is also an accessibility custom action.
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
/// A button of the bottom bar. With `repeat`, holding it steps again after 400 ms and
|
||||
/// then every 120 ms (§7.4).
|
||||
@Composable
|
||||
internal fun BarButton(
|
||||
private fun BarButton(
|
||||
icon: ImageVector,
|
||||
label: String,
|
||||
enabled: Boolean,
|
||||
modifier: Modifier,
|
||||
iconSize: Int = 24,
|
||||
repeat: Boolean = false,
|
||||
mirrored: Boolean = false,
|
||||
description: String = label,
|
||||
onLongClickLabel: String? = null,
|
||||
onLongClick: (() -> Unit)? = null,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val color = if (enabled) LocalContentColor.current else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
|
||||
val action by rememberUpdatedState(onClick)
|
||||
val longAction by rememberUpdatedState(onLongClick)
|
||||
val on by rememberUpdatedState(enabled)
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val color = if (enabled) LocalContentColor.current else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
|
||||
Box(
|
||||
modifier
|
||||
.fillMaxHeight()
|
||||
.clearAndSetSemantics {
|
||||
contentDescription = description
|
||||
.semantics {
|
||||
contentDescription = label
|
||||
role = Role.Button
|
||||
if (enabled) {
|
||||
onClick(label) { action(); true }
|
||||
if (onLongClickLabel != null && longAction != null) {
|
||||
onLongClick(onLongClickLabel) { longAction?.invoke(); true }
|
||||
customActions = listOf(CustomAccessibilityAction(onLongClickLabel) { longAction?.invoke(); true })
|
||||
}
|
||||
} else {
|
||||
disabled()
|
||||
}
|
||||
if (!enabled) disabled()
|
||||
onClick { action(); true }
|
||||
}
|
||||
.combinedClickable(
|
||||
enabled = enabled,
|
||||
onClickLabel = label,
|
||||
role = Role.Button,
|
||||
onLongClickLabel = onLongClickLabel,
|
||||
onLongClick = onLongClick,
|
||||
hapticFeedbackEnabled = false,
|
||||
onClick = onClick,
|
||||
),
|
||||
.indication(interaction, ripple(bounded = false, radius = 32.dp))
|
||||
.pointerInput(repeat) {
|
||||
detectTapGestures(onPress = { at ->
|
||||
if (!on) return@detectTapGestures
|
||||
val press = PressInteraction.Press(at)
|
||||
interaction.emit(press)
|
||||
action()
|
||||
coroutineScope {
|
||||
val job = if (repeat) {
|
||||
launch {
|
||||
delay(400)
|
||||
while (on) {
|
||||
action()
|
||||
delay(120)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
tryAwaitRelease()
|
||||
job?.cancel()
|
||||
}
|
||||
interaction.emit(PressInteraction.Release(press))
|
||||
})
|
||||
},
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(icon, null, tint = color, modifier = Modifier.size(iconSize.dp).then(if (mirrored) Modifier.scale(-1f, 1f) else Modifier))
|
||||
|
|
|
|||
|
|
@ -73,7 +73,6 @@ import androidx.compose.material3.SnackbarHostState
|
|||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material.icons.rounded.Download
|
||||
import androidx.compose.material.icons.rounded.Groups
|
||||
import io.github.vrubelroman.chesspenguin.theme.Tabular
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
|
|
@ -87,12 +86,7 @@ private const val CHUNK = 100
|
|||
/// The games of a database, with a search (android-ui.md §6).
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun GamesScreen(
|
||||
db: String,
|
||||
onBack: () -> Unit,
|
||||
onGame: (place: Int, query: String) -> Unit,
|
||||
onPlayers: () -> Unit = {},
|
||||
) {
|
||||
fun GamesScreen(db: String, onBack: () -> Unit, onGame: (place: Int, query: String) -> Unit) {
|
||||
val app = app()
|
||||
val entries by app.library.entries.collectAsState()
|
||||
val entry = entries.firstOrNull { it.id == db }
|
||||
|
|
@ -202,7 +196,6 @@ fun GamesScreen(
|
|||
if (query.isEmpty()) searching = false else query = ""
|
||||
}) { Icon(Icons.Rounded.Close, stringResource(R.string.clear)) }
|
||||
} else if (database != null) {
|
||||
IconButton(onClick = onPlayers) { Icon(Icons.Rounded.Groups, stringResource(R.string.players)) }
|
||||
IconButton(onClick = { searching = true }) { Icon(Icons.Rounded.Search, stringResource(R.string.search)) }
|
||||
// A downloaded database: its new games from here, where they are
|
||||
// looked for (android-ui.md §23.3); ✕ while they come.
|
||||
|
|
|
|||
|
|
@ -1,444 +0,0 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.rounded.Close
|
||||
import androidx.compose.material.icons.rounded.Search
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
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.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.material3.TextFieldDefaults
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
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.disabled
|
||||
import androidx.compose.ui.semantics.onClick
|
||||
import androidx.compose.ui.semantics.role
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import io.github.vrubelroman.chesspenguin.R
|
||||
import io.github.vrubelroman.chesspenguin.data.PrepBackends
|
||||
import io.github.vrubelroman.chesspenguin.theme.Tabular
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
import uniffi.mobile_api.Database
|
||||
import java.text.Collator
|
||||
import java.util.Locale
|
||||
|
||||
private const val PLAYER_PAGE = 100
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun PlayersScreen(
|
||||
db: String,
|
||||
onBack: () -> Unit,
|
||||
onPrepare: (player: PlayerSummary, white: Boolean) -> Unit,
|
||||
) {
|
||||
val app = app()
|
||||
val entries by app.library.entries.collectAsState()
|
||||
val entry = entries.firstOrNull { it.id == db }
|
||||
var database by remember { mutableStateOf<Database?>(null) }
|
||||
var openFailure by remember { mutableStateOf<Throwable?>(null) }
|
||||
val backend = remember(database) { database?.let(PrepBackends::open) }
|
||||
DisposableEffect(backend) { onDispose { backend?.close() } }
|
||||
|
||||
var searching by rememberSaveable { mutableStateOf(false) }
|
||||
var query by rememberSaveable { mutableStateOf("") }
|
||||
var colorChoice by remember { mutableStateOf<PlayerSummary?>(null) }
|
||||
var players by remember { mutableStateOf<List<PlayerSummary>?>(null) }
|
||||
var nextOffset by remember { mutableStateOf<Int?>(null) }
|
||||
var failure by remember { mutableStateOf<Throwable?>(null) }
|
||||
var loadingMore by remember { mutableStateOf(false) }
|
||||
var generation by remember { mutableIntStateOf(0) }
|
||||
var retry by rememberSaveable { mutableIntStateOf(0) }
|
||||
LaunchedEffect(db, entry?.games, entry?.updated, retry) {
|
||||
database = null
|
||||
openFailure = null
|
||||
app.library.database(db).onSuccess { database = it }.onFailure { openFailure = it }
|
||||
}
|
||||
val list = rememberLazyListState()
|
||||
val focus = remember { FocusRequester() }
|
||||
val keyboard = LocalSoftwareKeyboardController.current
|
||||
BackHandler(searching) {
|
||||
searching = false
|
||||
query = ""
|
||||
}
|
||||
|
||||
LaunchedEffect(backend, query, retry) {
|
||||
val source = backend ?: return@LaunchedEffect
|
||||
val expected = ++generation
|
||||
players = null
|
||||
nextOffset = null
|
||||
failure = null
|
||||
loadingMore = false
|
||||
if (query.isNotEmpty()) delay(250)
|
||||
try {
|
||||
val page = withContext(Dispatchers.IO) { source.players(query, 0, PLAYER_PAGE) }
|
||||
if (expected != generation) return@LaunchedEffect
|
||||
players = sortPlayers(page.players)
|
||||
nextOffset = page.nextOffset
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Throwable) {
|
||||
if (expected == generation) failure = e
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) }
|
||||
},
|
||||
title = {
|
||||
if (searching) {
|
||||
TextField(
|
||||
value = query,
|
||||
onValueChange = { query = it },
|
||||
placeholder = { Text(stringResource(R.string.player_name_hint)) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
|
||||
keyboardActions = KeyboardActions(onSearch = { keyboard?.hide() }),
|
||||
colors = TextFieldDefaults.colors(
|
||||
focusedContainerColor = Color.Transparent,
|
||||
unfocusedContainerColor = Color.Transparent,
|
||||
focusedIndicatorColor = Color.Transparent,
|
||||
unfocusedIndicatorColor = Color.Transparent,
|
||||
),
|
||||
modifier = Modifier.fillMaxWidth().focusRequester(focus),
|
||||
)
|
||||
LaunchedEffect(Unit) { focus.requestFocus() }
|
||||
} else {
|
||||
Column {
|
||||
Text(stringResource(R.string.players), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
entry?.let { displayName(it) } ?: "",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
if (searching) {
|
||||
IconButton(onClick = { if (query.isEmpty()) searching = false else query = "" }) {
|
||||
Icon(Icons.Rounded.Close, stringResource(R.string.clear))
|
||||
}
|
||||
} else if (database != null) {
|
||||
IconButton(onClick = { searching = true }) { Icon(Icons.Rounded.Search, stringResource(R.string.search)) }
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.fillMaxSize().padding(padding)) {
|
||||
val shownPlayers = players
|
||||
when {
|
||||
openFailure != null -> PrepMessage(stringResource(R.string.players_read_failed), openProblem(openFailure!!)) {
|
||||
TextButton(onClick = { database = null; openFailure = null; retry += 1 }) { Text(stringResource(R.string.retry)) }
|
||||
}
|
||||
failure != null -> PrepMessage(stringResource(R.string.players_read_failed), openProblem(failure!!).ifEmpty { failure!!.message ?: "" }) {
|
||||
TextButton(onClick = { retry += 1 }) { Text(stringResource(R.string.retry)) }
|
||||
}
|
||||
shownPlayers == null -> LoadingPlayers()
|
||||
shownPlayers.isEmpty() && query.isEmpty() -> PrepMessage(stringResource(R.string.no_named_players), "") {
|
||||
TextButton(onClick = onBack) { Text(stringResource(R.string.to_games)) }
|
||||
}
|
||||
shownPlayers.isEmpty() -> PrepMessage(stringResource(R.string.player_not_found), "") {
|
||||
TextButton(onClick = { query = "" }) { Text(stringResource(R.string.reset_search)) }
|
||||
}
|
||||
else -> LazyColumn(Modifier.fillMaxSize(), state = list) {
|
||||
val shown = shownPlayers
|
||||
val expectedGeneration = generation
|
||||
items(shown.size, key = { shown[it].id }) { index ->
|
||||
val player = shown[index]
|
||||
PlayerPrepRow(
|
||||
player = player,
|
||||
divider = index < shown.lastIndex || nextOffset != null,
|
||||
onPlayerClick = { chosen ->
|
||||
keyboard?.hide()
|
||||
val onlyColor = solePlayerColor(chosen)
|
||||
when {
|
||||
playerNeedsColorChoice(chosen) -> colorChoice = chosen
|
||||
onlyColor != null -> onPrepare(chosen, onlyColor)
|
||||
}
|
||||
},
|
||||
)
|
||||
if (index == shown.lastIndex && nextOffset != null) {
|
||||
LaunchedEffect(nextOffset, generation) {
|
||||
val source = backend ?: return@LaunchedEffect
|
||||
val offset = nextOffset ?: return@LaunchedEffect
|
||||
loadingMore = true
|
||||
try {
|
||||
val page = withContext(Dispatchers.IO) { source.players(query, offset, PLAYER_PAGE) }
|
||||
if (expectedGeneration == generation) {
|
||||
players = sortPlayers((shown + page.players).distinctBy { it.id })
|
||||
nextOffset = page.nextOffset
|
||||
}
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Throwable) {
|
||||
if (expectedGeneration == generation) failure = e
|
||||
} finally {
|
||||
if (expectedGeneration == generation) loadingMore = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (loadingMore) {
|
||||
items(3, key = { "loading-$it" }) { PlayerPrepPlaceholder() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
colorChoice?.let { player ->
|
||||
PlayerColorSheet(
|
||||
player = player,
|
||||
onDismiss = { colorChoice = null },
|
||||
onPrepare = { chosen, white ->
|
||||
colorChoice = null
|
||||
onPrepare(chosen, white)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun sortPlayers(players: List<PlayerSummary>): List<PlayerSummary> {
|
||||
val collator = Collator.getInstance(Locale.getDefault()).apply { strength = Collator.PRIMARY }
|
||||
return players.sortedWith(compareBy(collator) { it.name })
|
||||
}
|
||||
|
||||
internal fun playerNeedsColorChoice(player: PlayerSummary): Boolean = player.whiteGames > 0 && player.blackGames > 0
|
||||
|
||||
internal fun solePlayerColor(player: PlayerSummary): Boolean? = when {
|
||||
player.whiteGames > 0 && player.blackGames == 0 -> true
|
||||
player.blackGames > 0 && player.whiteGames == 0 -> false
|
||||
else -> null
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
internal fun PlayerPrepRow(
|
||||
player: PlayerSummary,
|
||||
divider: Boolean = false,
|
||||
onPlayerClick: (PlayerSummary) -> Unit,
|
||||
) {
|
||||
val games = pluralStringResource(R.plurals.games_count, player.total, groupDigits(player.total))
|
||||
val whiteSide = stringResource(R.string.prep_as_white)
|
||||
val blackSide = stringResource(R.string.prep_as_black)
|
||||
val chooseColor = stringResource(R.string.prep_choose_color)
|
||||
val prepare = stringResource(R.string.prepare_action)
|
||||
val onlyColor = solePlayerColor(player)
|
||||
val hasAction = playerNeedsColorChoice(player) || onlyColor != null
|
||||
val action = when {
|
||||
playerNeedsColorChoice(player) -> chooseColor
|
||||
onlyColor == true -> "$prepare $whiteSide"
|
||||
onlyColor == false -> "$prepare $blackSide"
|
||||
else -> prepare
|
||||
}
|
||||
val description = "${player.name}, $games. $whiteSide ${groupDigits(player.whiteGames)}, $blackSide ${groupDigits(player.blackGames)}. $action"
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
val grows = maxWidth < 320.dp || LocalDensity.current.fontScale > 1f
|
||||
val height = if (grows) Modifier.heightIn(min = 72.dp) else Modifier.height(72.dp)
|
||||
Box(
|
||||
Modifier.fillMaxWidth().then(height)
|
||||
.clearAndSetSemantics {
|
||||
contentDescription = description
|
||||
role = Role.Button
|
||||
if (hasAction) onClick(action) { onPlayerClick(player); true } else disabled()
|
||||
}
|
||||
.clickable(enabled = hasAction, role = Role.Button, onClickLabel = action) { onPlayerClick(player) },
|
||||
) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(Modifier.fillMaxWidth().heightIn(min = 24.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
PlayerName(player.name, MaterialTheme.typography.bodyLarge, Modifier.weight(1f))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(games, style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
FlowRow(
|
||||
Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
PlayerColorText(true, whiteSide, player.whiteGames)
|
||||
PlayerColorText(false, blackSide, player.blackGames)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Icon(
|
||||
Icons.AutoMirrored.Rounded.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(24.dp),
|
||||
)
|
||||
}
|
||||
if (divider) HorizontalDivider(Modifier.align(Alignment.BottomCenter), color = MaterialTheme.colorScheme.outlineVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PlayerColorText(white: Boolean, side: String, count: Int) {
|
||||
Row(Modifier.heightIn(min = 20.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
SideDisc(white)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("$side · ${groupDigits(count)}", style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun PlayerColorSheet(player: PlayerSummary, onDismiss: () -> Unit, onPrepare: (PlayerSummary, Boolean) -> Unit) {
|
||||
val games = pluralStringResource(R.plurals.games_count, player.total, groupDigits(player.total))
|
||||
ModalBottomSheet(onDismissRequest = onDismiss) {
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 8.dp)) {
|
||||
Text(
|
||||
stringResource(R.string.prep_against_player, player.name),
|
||||
Modifier.fillMaxWidth(),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
games,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
PlayerColorAction(player, true, onPrepare)
|
||||
PlayerColorAction(player, false, onPrepare)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PlayerColorAction(player: PlayerSummary, white: Boolean, onPrepare: (PlayerSummary, Boolean) -> Unit) {
|
||||
val count = if (white) player.whiteGames else player.blackGames
|
||||
val side = stringResource(if (white) R.string.prep_against_white else R.string.prep_against_black)
|
||||
val games = pluralStringResource(R.plurals.games_count, count, groupDigits(count))
|
||||
val prepare = stringResource(R.string.prepare_action)
|
||||
Row(
|
||||
Modifier.fillMaxWidth().heightIn(min = 64.dp)
|
||||
.clearAndSetSemantics {
|
||||
contentDescription = "${player.name}, $side, $games. $prepare"
|
||||
role = Role.Button
|
||||
onClick(prepare) { onPrepare(player, white); true }
|
||||
}
|
||||
.clickable(role = Role.Button, onClickLabel = prepare) { onPrepare(player, white) }
|
||||
.padding(horizontal = 24.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
SideDisc(white)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(side, Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(groupDigits(count), style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Icon(Icons.AutoMirrored.Rounded.KeyboardArrowRight, null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(24.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PlayerPrepPlaceholder() {
|
||||
Box(Modifier.fillMaxWidth().height(72.dp)) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp)) {
|
||||
Row(Modifier.fillMaxWidth().height(24.dp)) {
|
||||
Box(Modifier.weight(1f).height(24.dp).background(MaterialTheme.colorScheme.surfaceContainerLow, RoundedCornerShape(4.dp)))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Box(Modifier.width(64.dp).height(24.dp).background(MaterialTheme.colorScheme.surfaceContainerLow, RoundedCornerShape(4.dp)))
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Box(Modifier.fillMaxWidth(0.65f).height(20.dp).background(MaterialTheme.colorScheme.surfaceContainerLow, RoundedCornerShape(4.dp)))
|
||||
}
|
||||
HorizontalDivider(Modifier.align(Alignment.BottomCenter), color = MaterialTheme.colorScheme.outlineVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LoadingPlayers() {
|
||||
Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
|
||||
CircularProgressIndicator()
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Text(stringResource(R.string.reading_players), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun PrepMessage(title: String, detail: String, action: (@Composable () -> Unit)? = null) {
|
||||
Column(Modifier.fillMaxSize().padding(32.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
|
||||
Text(title, style = MaterialTheme.typography.titleLarge, textAlign = TextAlign.Center)
|
||||
if (detail.isNotEmpty()) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(detail, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center)
|
||||
}
|
||||
if (action != null) {
|
||||
Spacer(Modifier.height(16.dp))
|
||||
action()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,161 +0,0 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import io.github.vrubelroman.chesspenguin.data.PrepBackend
|
||||
import io.github.vrubelroman.chesspenguin.data.PrepQuery
|
||||
import io.github.vrubelroman.chesspenguin.data.query
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import uniffi.mobile_api.GameData
|
||||
import uniffi.mobile_api.GameSession
|
||||
|
||||
internal class PrepController(val request: PrepStart) : ViewModel() {
|
||||
var line by mutableStateOf(PrepLineState(request.startFen, request.startFen))
|
||||
private set
|
||||
var data by mutableStateOf<GameData?>(null)
|
||||
private set
|
||||
var position by mutableStateOf<PrepPosition?>(null)
|
||||
private set
|
||||
var failure by mutableStateOf<Throwable?>(null)
|
||||
private set
|
||||
var loading by mutableStateOf(false)
|
||||
private set
|
||||
var initialised by mutableStateOf(false)
|
||||
private set
|
||||
var moveFailed by mutableStateOf(false)
|
||||
var retry by mutableIntStateOf(0)
|
||||
private set
|
||||
|
||||
private var session: GameSession? = null
|
||||
private var search: Job? = null
|
||||
private var generation = 0L
|
||||
|
||||
suspend fun initialise() {
|
||||
if (session != null) return
|
||||
failure = null
|
||||
val loaded = withContext(Dispatchers.Default) {
|
||||
runCatching {
|
||||
val fen = request.startFen
|
||||
val s = GameSession.fromPgn("[SetUp \"1\"]\n[FEN \"$fen\"]\n\n*")
|
||||
try {
|
||||
var edited = s.data() to 0
|
||||
for (uci in request.moves) {
|
||||
val next = s.play(edited.second.toUInt(), uci)
|
||||
edited = next.data to next.cursor.toInt()
|
||||
}
|
||||
Triple(s, edited.first, edited.second)
|
||||
} catch (e: Throwable) {
|
||||
s.close()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
if (session != null) {
|
||||
loaded.getOrNull()?.first?.close()
|
||||
return
|
||||
}
|
||||
val (s, game, cursor) = loaded.getOrElse {
|
||||
failure = it
|
||||
initialised = false
|
||||
return
|
||||
}
|
||||
session = s
|
||||
data = game
|
||||
line = prepLine(game, cursor, request.startFen)
|
||||
initialised = true
|
||||
}
|
||||
|
||||
private fun invalidate() {
|
||||
generation += 1
|
||||
search?.cancel()
|
||||
position = null
|
||||
failure = null
|
||||
loading = false
|
||||
}
|
||||
|
||||
fun back() {
|
||||
if (!line.canBack) return
|
||||
line = line.back()
|
||||
invalidate()
|
||||
}
|
||||
|
||||
fun forward() {
|
||||
if (!line.canForward) return
|
||||
line = line.forward()
|
||||
invalidate()
|
||||
}
|
||||
|
||||
fun start() {
|
||||
if (!line.canBack) return
|
||||
line = line.start()
|
||||
invalidate()
|
||||
}
|
||||
|
||||
fun end() {
|
||||
if (!line.canForward) return
|
||||
line = line.end()
|
||||
invalidate()
|
||||
}
|
||||
|
||||
fun legalMoves(): List<String> = session?.legalMoves(line.currentNode.toUInt()).orEmpty()
|
||||
|
||||
fun play(uci: String): String? {
|
||||
val s = session ?: return null
|
||||
if (s.legalMoves(line.currentNode.toUInt()).none { it == uci }) return null
|
||||
val edited = runCatching { s.play(line.currentNode.toUInt(), uci) }.getOrElse {
|
||||
moveFailed = true
|
||||
return null
|
||||
}
|
||||
val visible = prepLine(edited.data, edited.cursor.toInt(), request.startFen)
|
||||
line = visible
|
||||
data = edited.data
|
||||
invalidate()
|
||||
return visible.last?.san
|
||||
}
|
||||
|
||||
fun repeat() {
|
||||
retry += 1
|
||||
invalidate()
|
||||
}
|
||||
|
||||
fun search(backend: PrepBackend) {
|
||||
if (!initialised || failure != null) return
|
||||
invalidate()
|
||||
backend.cancel()
|
||||
val query: PrepQuery = request.query(line.fen)
|
||||
val expected = generation
|
||||
search = viewModelScope.launch {
|
||||
val delayed = launch {
|
||||
delay(300)
|
||||
if (generation == expected) loading = true
|
||||
}
|
||||
try {
|
||||
val answer = withContext(Dispatchers.IO) { backend.position(query) }
|
||||
if (generation == expected && query == request.query(line.fen)) position = answer
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Throwable) {
|
||||
if (generation == expected && query == request.query(line.fen)) failure = e
|
||||
} finally {
|
||||
delayed.cancel()
|
||||
if (generation == expected) loading = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCleared() {
|
||||
generation += 1
|
||||
search?.cancel()
|
||||
session?.close()
|
||||
session = null
|
||||
}
|
||||
}
|
||||
|
|
@ -1,187 +0,0 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import uniffi.mobile_api.GameData
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
internal const val STANDARD_START = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
|
||||
|
||||
/// The position and history of a preparation request. The game document is not part of it.
|
||||
@Serializable
|
||||
data class PrepStart(
|
||||
val db: String,
|
||||
val player: String,
|
||||
val white: Boolean,
|
||||
val startFen: String = STANDARD_START,
|
||||
val moves: List<String> = emptyList(),
|
||||
val fromGame: Boolean = false,
|
||||
)
|
||||
|
||||
/// One move of the temporary line. `node` belongs only to this preparation session.
|
||||
@Serializable
|
||||
data class PrepLineStep(
|
||||
val node: Int,
|
||||
val uci: String,
|
||||
val san: String,
|
||||
val moveNumber: Int,
|
||||
val white: Boolean,
|
||||
val fen: String,
|
||||
val from: String?,
|
||||
val to: String?,
|
||||
) {
|
||||
val label: String get() = "$moveNumber${if (white) "." else "…"}$san"
|
||||
}
|
||||
|
||||
/// A linear, read-only exploration. Going back never chooses a different continuation;
|
||||
/// making a move after going back drops only this temporary future.
|
||||
@Serializable
|
||||
data class PrepLineState(
|
||||
val startFen: String,
|
||||
val rootFen: String,
|
||||
val rootNode: Int = 0,
|
||||
val steps: List<PrepLineStep> = emptyList(),
|
||||
val cursor: Int = 0,
|
||||
) {
|
||||
init {
|
||||
require(cursor in 0..steps.size) { "line cursor is outside the line" }
|
||||
}
|
||||
|
||||
val fen: String get() = steps.getOrNull(cursor - 1)?.fen ?: rootFen
|
||||
val currentNode: Int get() = steps.getOrNull(cursor - 1)?.node ?: rootNode
|
||||
val last: PrepLineStep? get() = steps.getOrNull(cursor - 1)
|
||||
val moves: List<String> get() = steps.map { it.uci }
|
||||
val canBack: Boolean get() = cursor > 0
|
||||
val canForward: Boolean get() = cursor < steps.size
|
||||
|
||||
fun back(): PrepLineState = if (canBack) copy(cursor = cursor - 1) else this
|
||||
fun forward(): PrepLineState = if (canForward) copy(cursor = cursor + 1) else this
|
||||
fun start(): PrepLineState = if (canBack) copy(cursor = 0) else this
|
||||
fun end(): PrepLineState = if (canForward) copy(cursor = steps.size) else this
|
||||
|
||||
fun replaceVisibleLine(visible: List<PrepLineStep>, currentNode: Int): PrepLineState {
|
||||
val at = visible.indexOfLast { it.node == currentNode }
|
||||
require(at >= 0 && at + 1 == visible.size) { "the played move must end the visible line" }
|
||||
return copy(steps = visible, cursor = visible.size)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun prepLine(data: GameData, cursor: Int, startFen: String): PrepLineState {
|
||||
val path = ArrayList<Int>()
|
||||
var at: Int? = cursor
|
||||
while (at != null) {
|
||||
if (at !in data.nodes.indices || at in path) break
|
||||
path += at
|
||||
at = data.nodes[at].parent?.toInt()
|
||||
}
|
||||
path.reverse()
|
||||
val root = path.firstOrNull() ?: 0
|
||||
val steps = path.drop(1).mapNotNull { id ->
|
||||
val n = data.nodes[id]
|
||||
if (n.uci.isEmpty()) return@mapNotNull null
|
||||
PrepLineStep(id, n.uci, n.san, n.moveNumber.toInt(), n.white, n.fen, n.fromSquare, n.toSquare)
|
||||
}
|
||||
return PrepLineState(startFen, data.nodes.getOrNull(root)?.fen ?: startFen, root, steps, steps.size)
|
||||
}
|
||||
|
||||
/// A null move cannot be represented by the normal-move position search.
|
||||
internal fun prepStartFromGame(data: GameData, at: Int, db: String, player: String, white: Boolean): PrepStart? {
|
||||
if (at !in data.nodes.indices) return null
|
||||
val path = ArrayList<Int>()
|
||||
var node: Int? = at
|
||||
while (node != null) {
|
||||
if (node !in data.nodes.indices || node in path) return null
|
||||
path += node
|
||||
node = data.nodes[node].parent?.toInt()
|
||||
}
|
||||
path.reverse()
|
||||
if (path.any { data.nodes[it].nullMove }) return null
|
||||
val moves = path.drop(1).map { data.nodes[it].uci }
|
||||
if (moves.any { it.isEmpty() }) return null
|
||||
return PrepStart(
|
||||
db = db,
|
||||
player = player,
|
||||
white = white,
|
||||
startFen = data.nodes[path.first()].fen,
|
||||
moves = moves,
|
||||
fromGame = true,
|
||||
)
|
||||
}
|
||||
|
||||
/// Preparation shows the user's side at the bottom, opposite to the selected opponent.
|
||||
internal fun prepBoardStartsFlipped(opponentWhite: Boolean): Boolean = opponentWhite
|
||||
|
||||
internal fun prepWhiteToMove(fen: String): Boolean? = fen.split(' ').getOrNull(1)?.let {
|
||||
when (it) {
|
||||
"w" -> true
|
||||
"b" -> false
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
internal fun moveLabel(fen: String, san: String): String {
|
||||
val fields = fen.split(' ')
|
||||
val number = fields.getOrNull(5)?.toIntOrNull()?.coerceAtLeast(0) ?: 1
|
||||
val white = prepWhiteToMove(fen) ?: true
|
||||
return "$number${if (white) "." else "…"}$san"
|
||||
}
|
||||
|
||||
data class PlayerSummary(
|
||||
val id: Int,
|
||||
val name: String,
|
||||
val total: Int,
|
||||
val whiteGames: Int,
|
||||
val blackGames: Int,
|
||||
)
|
||||
|
||||
data class PlayerPage(
|
||||
val players: List<PlayerSummary>,
|
||||
val total: Int,
|
||||
val nextOffset: Int?,
|
||||
)
|
||||
|
||||
data class PrepContinuation(
|
||||
val uci: String,
|
||||
val san: String,
|
||||
val games: Int,
|
||||
val wins: Int,
|
||||
val draws: Int,
|
||||
val losses: Int,
|
||||
val unknown: Int = 0,
|
||||
) {
|
||||
val from: String? get() = uci.takeIf { it.length >= 4 }?.substring(0, 2)
|
||||
val to: String? get() = uci.takeIf { it.length >= 4 }?.substring(2, 4)
|
||||
}
|
||||
|
||||
/// A matching game is part of the result contract even though its list is outside this MVP.
|
||||
data class PrepGameMatch(val index: UInt, val ply: UInt)
|
||||
|
||||
data class PrepPosition(
|
||||
val games: Int,
|
||||
val continuations: List<PrepContinuation>,
|
||||
val endedHere: Int = 0,
|
||||
val noNormalContinuation: Int = 0,
|
||||
val unknownResults: Int = 0,
|
||||
val playerToMove: Boolean? = null,
|
||||
val matches: List<PrepGameMatch> = emptyList(),
|
||||
val matchesTotal: Int = 0,
|
||||
)
|
||||
|
||||
internal fun sortedContinuations(position: PrepPosition): List<PrepContinuation> =
|
||||
position.continuations.sortedWith(compareByDescending<PrepContinuation> { it.games }.thenBy { it.san })
|
||||
|
||||
internal fun frequencyPercent(games: Int, total: Int): String = when {
|
||||
games <= 0 || total <= 0 -> "0"
|
||||
games * 100L < total -> "<1"
|
||||
else -> (games * 100.0 / total).roundToInt().toString()
|
||||
}
|
||||
|
||||
internal fun outcomePercents(move: PrepContinuation): Triple<String, String, String> {
|
||||
val known = move.wins + move.draws + move.losses
|
||||
if (known <= 0) return Triple("—", "—", "—")
|
||||
fun percent(n: Int) = (n * 100.0 / known).roundToInt().toString()
|
||||
return Triple(percent(move.wins), percent(move.draws), percent(move.losses))
|
||||
}
|
||||
|
||||
internal class PrepOutOfMemory : IllegalStateException("Not enough memory for the position index")
|
||||
internal class PrepSearchFailed(message: String) : IllegalStateException(message)
|
||||
internal class PrepPlayerNotFound(name: String) : IllegalStateException("Player is not in this database: $name")
|
||||
|
|
@ -1,469 +0,0 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import android.content.res.Configuration
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
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.Spacer
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.WindowInsetsSides
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.navigationBars
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.only
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.layout.windowInsetsPadding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
|
||||
import androidx.compose.material.icons.rounded.PlayArrow
|
||||
import androidx.compose.material.icons.rounded.SwapVert
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.LiveRegionMode
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.liveRegion
|
||||
import androidx.compose.ui.semantics.onClick
|
||||
import androidx.compose.ui.semantics.role
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import io.github.vrubelroman.chesspenguin.R
|
||||
import io.github.vrubelroman.chesspenguin.data.PrepBackends
|
||||
import io.github.vrubelroman.chesspenguin.theme.Tabular
|
||||
import uniffi.mobile_api.Database
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun PrepScreen(request: PrepStart, onBack: () -> Unit) {
|
||||
val app = app()
|
||||
val context = LocalContext.current
|
||||
val controller: PrepController = viewModel(key = "prep") { PrepController(request) }
|
||||
val entries by app.library.entries.collectAsState()
|
||||
val entry = entries.firstOrNull { it.id == request.db }
|
||||
var database by remember { mutableStateOf<Database?>(null) }
|
||||
var openFailure by remember { mutableStateOf<Throwable?>(null) }
|
||||
var openRetry by rememberSaveable { mutableIntStateOf(0) }
|
||||
LaunchedEffect(request.db, entry?.games, entry?.updated, openRetry) {
|
||||
database = null
|
||||
openFailure = null
|
||||
controller.repeat()
|
||||
app.library.database(request.db).onSuccess { database = it }.onFailure { openFailure = it }
|
||||
}
|
||||
val backend = remember(database) { database?.let(PrepBackends::open) }
|
||||
DisposableEffect(backend) { onDispose { backend?.cancel(); backend?.close() } }
|
||||
LaunchedEffect(controller.retry) { controller.initialise() }
|
||||
LaunchedEffect(backend, controller.initialised, controller.line, controller.retry) {
|
||||
if (backend != null && controller.initialised) controller.search(backend)
|
||||
}
|
||||
|
||||
val prefs by app.settings.prefs.collectAsState()
|
||||
val lang = uiLanguage()
|
||||
val san = remember(prefs.notation, lang) { { value: String -> displaySan(value, prefs.notation, lang) } }
|
||||
val pieces = remember { Pieces(context) }
|
||||
var flipped by rememberSaveable { mutableStateOf(prepBoardStartsFlipped(request.white)) }
|
||||
var conflicts by remember { mutableStateOf<List<String>>(emptyList()) }
|
||||
val list = rememberLazyListState()
|
||||
val contextFocus = remember { FocusRequester() }
|
||||
val snackbar = remember { SnackbarHostState() }
|
||||
val moveFailed = stringResource(R.string.prep_move_failed)
|
||||
LaunchedEffect(controller.moveFailed) {
|
||||
if (controller.moveFailed) {
|
||||
snackbar.showSnackbar(moveFailed)
|
||||
controller.moveFailed = false
|
||||
}
|
||||
}
|
||||
|
||||
fun play(uci: String) {
|
||||
val played = controller.play(uci) ?: return
|
||||
conflicts = emptyList()
|
||||
app.sounds.move(played)
|
||||
contextFocus.requestFocus()
|
||||
}
|
||||
|
||||
fun arrowsChosen(moves: List<String>) {
|
||||
when (moves.size) {
|
||||
0 -> {}
|
||||
1 -> play(moves[0])
|
||||
else -> conflicts = moves
|
||||
}
|
||||
}
|
||||
|
||||
val position = controller.position
|
||||
val continuations = position?.let(::sortedContinuations).orEmpty()
|
||||
val arrowContinuations = continuations.distinctBy { it.from to it.to }.take(3)
|
||||
val arrows = arrowContinuations.mapIndexedNotNull { index, move ->
|
||||
val from = move.from ?: return@mapIndexedNotNull null
|
||||
val to = move.to ?: return@mapIndexedNotNull null
|
||||
val weight = if (index == 0) 1f else if (index == 1) 0.85f else 0.70f
|
||||
val alpha = if (index == 0) 0.63f else if (index == 1) 0.45f else 0.35f
|
||||
BoardArrow(from, to, EngineArrow.copy(alpha = alpha), weight)
|
||||
}
|
||||
val arrowMoves = continuations.filter { move -> arrowContinuations.any { it.from == move.from && it.to == move.to } }
|
||||
.mapNotNull { move ->
|
||||
val from = move.from ?: return@mapNotNull null
|
||||
val to = move.to ?: return@mapNotNull null
|
||||
val label = moveLabel(controller.line.fen, move.san)
|
||||
val games = pluralStringResource(R.plurals.games_count, move.games, groupDigits(move.games))
|
||||
val action = stringResource(R.string.prep_play_continuation, label, games, frequencyPercent(move.games, position?.games ?: 0))
|
||||
BoardArrowMove(move.uci, from, to, action)
|
||||
}
|
||||
val last = controller.line.last
|
||||
val boardDescription = if (last == null) {
|
||||
stringResource(R.string.prep_board_start, if (flipped) stringResource(R.string.color_black) else stringResource(R.string.color_white))
|
||||
} else {
|
||||
stringResource(R.string.prep_board_after, last.label, if (flipped) stringResource(R.string.color_black) else stringResource(R.string.color_white))
|
||||
}
|
||||
val board: @Composable (Modifier) -> Unit = { modifier ->
|
||||
Board(
|
||||
fen = controller.line.fen,
|
||||
flipped = flipped,
|
||||
lastFrom = last?.from,
|
||||
lastTo = last?.to,
|
||||
pieces = pieces,
|
||||
theme = prefs.board,
|
||||
set = prefs.pieces,
|
||||
description = boardDescription,
|
||||
modifier = modifier,
|
||||
arrows = arrows,
|
||||
arrowMoves = arrowMoves,
|
||||
onArrowMoves = ::arrowsChosen,
|
||||
check = last?.san?.let { it.endsWith("+") || it.endsWith("#") } == true,
|
||||
animated = prefs.animation,
|
||||
input = if (controller.initialised && controller.data != null) {
|
||||
BoardInput(controller.legalMoves(), onMove = ::play)
|
||||
} else {
|
||||
null
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
val turnWhite = prepWhiteToMove(controller.line.fen)
|
||||
val opponentPlays = position?.playerToMove ?: (turnWhite == request.white)
|
||||
val sideToMove = when (turnWhite) {
|
||||
true -> stringResource(R.string.turn_white)
|
||||
false -> stringResource(R.string.turn_black)
|
||||
null -> ""
|
||||
}
|
||||
val who = stringResource(if (opponentPlays) R.string.prep_opponent_plays else R.string.prep_opponents_play)
|
||||
val where = last?.let { stringResource(R.string.prep_after, it.label) } ?: stringResource(R.string.prep_beginning)
|
||||
val gamesCount = position?.games
|
||||
val gamesText = if (gamesCount == null) "…" else pluralStringResource(R.plurals.games_count, gamesCount, groupDigits(gamesCount))
|
||||
val contextDescription = stringResource(R.string.prep_context_description, who, sideToMove, where, gamesText)
|
||||
val contextRow: @Composable () -> Unit = {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().heightIn(min = 32.dp).focusRequester(contextFocus).focusable()
|
||||
.semantics(mergeDescendants = true) {
|
||||
contentDescription = contextDescription
|
||||
liveRegion = LiveRegionMode.Polite
|
||||
}
|
||||
.padding(horizontal = 16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"$who · $where",
|
||||
Modifier.weight(1f),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(gamesText, style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
}
|
||||
val results: @Composable (Modifier) -> Unit = { modifier ->
|
||||
Box(modifier) {
|
||||
when {
|
||||
openFailure != null -> PrepMessage(stringResource(R.string.prep_failed), openProblem(openFailure!!)) {
|
||||
TextButton(onClick = { openRetry += 1 }) { Text(stringResource(R.string.retry)) }
|
||||
}
|
||||
controller.failure != null -> {
|
||||
val memory = controller.failure is PrepOutOfMemory
|
||||
val problem = openProblem(controller.failure!!).ifEmpty { controller.failure!!.message ?: "" }
|
||||
PrepMessage(stringResource(if (memory) R.string.prep_no_memory else R.string.prep_failed), problem) {
|
||||
TextButton(onClick = { controller.repeat() }) { Text(stringResource(R.string.retry)) }
|
||||
}
|
||||
}
|
||||
position == null && controller.loading -> {
|
||||
LinearProgressIndicator(Modifier.fillMaxWidth().height(2.dp).align(Alignment.TopStart))
|
||||
Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
|
||||
CircularProgressIndicator()
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Text(stringResource(R.string.prep_calculating), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
position == null -> PrepPlaceholders()
|
||||
position.games == 0 -> PrepMessage(
|
||||
stringResource(R.string.prep_position_absent, request.player),
|
||||
stringResource(R.string.prep_position_absent_hint),
|
||||
)
|
||||
continuations.isEmpty() && position.endedHere == position.games -> PrepMessage(stringResource(R.string.prep_all_ended), "")
|
||||
else -> LazyColumn(Modifier.fillMaxSize(), state = list) {
|
||||
items(continuations.size, key = { continuations[it].uci }) { index ->
|
||||
ContinuationRow(
|
||||
continuation = continuations[index],
|
||||
total = position.games,
|
||||
fen = controller.line.fen,
|
||||
player = request.player,
|
||||
san = san,
|
||||
divider = index < continuations.lastIndex,
|
||||
onClick = { play(continuations[index].uci) },
|
||||
)
|
||||
}
|
||||
if (position.endedHere > 0 && continuations.isNotEmpty()) {
|
||||
item(key = "ended") { PrepDisabledRow(stringResource(R.string.prep_ended_here, groupDigits(position.endedHere))) }
|
||||
}
|
||||
if (position.noNormalContinuation > 0) {
|
||||
item(key = "no-normal") { PrepDisabledRow(stringResource(R.string.prep_no_normal, groupDigits(position.noNormalContinuation))) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val controls: @Composable () -> Unit = {
|
||||
PrepControls(
|
||||
canBack = controller.line.canBack,
|
||||
canForward = controller.line.canForward,
|
||||
onFlip = { flipped = !flipped },
|
||||
onBack = controller::back,
|
||||
onForward = controller::forward,
|
||||
onStart = controller::start,
|
||||
onEnd = controller::end,
|
||||
)
|
||||
}
|
||||
val landscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(if (request.fromGame) R.string.to_game else R.string.to_players))
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Column {
|
||||
PlayerName(request.player, MaterialTheme.typography.titleMedium)
|
||||
Text(
|
||||
stringResource(if (request.white) R.string.prep_as_white else R.string.prep_as_black) + " · " + (entry?.let { displayName(it) } ?: ""),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
snackbarHost = { SnackbarHost(snackbar) },
|
||||
bottomBar = { if (!landscape) controls() },
|
||||
) { padding ->
|
||||
val inner = Modifier.fillMaxSize().padding(padding)
|
||||
if (landscape) {
|
||||
Row(inner.windowInsetsPadding(WindowInsets.navigationBars.only(WindowInsetsSides.Horizontal))) {
|
||||
board(Modifier.fillMaxHeight())
|
||||
Column(Modifier.weight(1f).fillMaxHeight()) {
|
||||
contextRow()
|
||||
results(Modifier.weight(1f).fillMaxWidth())
|
||||
controls()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Column(inner, horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
board(Modifier.widthIn(max = 480.dp).fillMaxWidth())
|
||||
Column(Modifier.widthIn(max = 480.dp).fillMaxWidth().weight(1f)) {
|
||||
contextRow()
|
||||
results(Modifier.weight(1f).fillMaxWidth())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (conflicts.isNotEmpty()) {
|
||||
ModalBottomSheet(onDismissRequest = { conflicts = emptyList() }) {
|
||||
Column(Modifier.fillMaxWidth().padding(bottom = 24.dp)) {
|
||||
Text(stringResource(R.string.prep_choose_move), style = MaterialTheme.typography.titleLarge, modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp))
|
||||
conflicts.mapNotNull { uci -> continuations.firstOrNull { it.uci == uci } }.forEach { move ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().heightIn(min = 56.dp).clickable { play(move.uci) }.padding(horizontal = 24.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(san(moveLabel(controller.line.fen, move.san)), style = MaterialTheme.typography.bodyLarge)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ContinuationRow(
|
||||
continuation: PrepContinuation,
|
||||
total: Int,
|
||||
fen: String,
|
||||
player: String,
|
||||
san: (String) -> AnnotatedString,
|
||||
divider: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val label = moveLabel(fen, continuation.san)
|
||||
val frequency = frequencyPercent(continuation.games, total)
|
||||
val (wins, draws, losses) = outcomePercents(continuation)
|
||||
val games = pluralStringResource(R.plurals.games_count, total, groupDigits(total))
|
||||
val winsText = pluralStringResource(R.plurals.prep_wins, continuation.wins, groupDigits(continuation.wins))
|
||||
val drawsText = pluralStringResource(R.plurals.prep_draws, continuation.draws, groupDigits(continuation.draws))
|
||||
val lossesText = pluralStringResource(R.plurals.prep_losses, continuation.losses, groupDigits(continuation.losses))
|
||||
val unknown = if (continuation.unknown > 0) stringResource(R.string.prep_unknown_accessibility, continuation.unknown) else ""
|
||||
val description = stringResource(
|
||||
R.string.prep_continuation_description,
|
||||
continuation.san,
|
||||
continuation.games,
|
||||
games,
|
||||
frequency,
|
||||
player,
|
||||
winsText,
|
||||
drawsText,
|
||||
lossesText,
|
||||
wins,
|
||||
draws,
|
||||
losses,
|
||||
unknown,
|
||||
)
|
||||
Column(
|
||||
Modifier.fillMaxWidth().heightIn(min = 56.dp).clickable(onClickLabel = stringResource(R.string.prep_play), role = Role.Button, onClick = onClick)
|
||||
.clearAndSetSemantics {
|
||||
contentDescription = description
|
||||
role = Role.Button
|
||||
onClick { onClick(); true }
|
||||
}
|
||||
.padding(start = 16.dp, top = 5.dp, end = 16.dp, bottom = 5.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(san(label), Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge.copy(fontSize = androidx.compose.ui.unit.TextUnit(17f, androidx.compose.ui.unit.TextUnitType.Sp)), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
"${groupDigits(continuation.games)}/${groupDigits(total)} · $frequency %",
|
||||
style = MaterialTheme.typography.bodyMedium.merge(Tabular),
|
||||
maxLines = 1,
|
||||
softWrap = false,
|
||||
)
|
||||
}
|
||||
val raw = buildString {
|
||||
if (continuation.unknown > 0) append(stringResource(R.string.prep_unknown_short, groupDigits(continuation.unknown))).append(' ')
|
||||
append(stringResource(R.string.prep_wdl_counts, groupDigits(continuation.wins), groupDigits(continuation.draws), groupDigits(continuation.losses), wins, draws, losses))
|
||||
}
|
||||
Text(raw, style = MaterialTheme.typography.labelSmall.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
if (divider) HorizontalDivider(Modifier.padding(top = 5.dp), color = MaterialTheme.colorScheme.outlineVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PrepDisabledRow(text: String) {
|
||||
Text(
|
||||
text,
|
||||
Modifier.fillMaxWidth().heightIn(min = 48.dp).padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PrepPlaceholders() {
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
repeat(4) {
|
||||
Column(Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 16.dp, vertical = 8.dp)) {
|
||||
Box(Modifier.fillMaxWidth().height(20.dp).background(MaterialTheme.colorScheme.surfaceContainerLow))
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Box(Modifier.fillMaxWidth().height(16.dp).background(MaterialTheme.colorScheme.surfaceContainerLow))
|
||||
}
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun PrepControls(
|
||||
canBack: Boolean,
|
||||
canForward: Boolean,
|
||||
onFlip: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
onForward: () -> Unit,
|
||||
onStart: () -> Unit,
|
||||
onEnd: () -> Unit,
|
||||
) {
|
||||
Surface(color = MaterialTheme.colorScheme.surfaceContainer) {
|
||||
Row(Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp)) {
|
||||
BarButton(Icons.Rounded.SwapVert, stringResource(R.string.flip), true, Modifier.width(72.dp), onClick = onFlip)
|
||||
BarButton(
|
||||
icon = Icons.Rounded.PlayArrow,
|
||||
label = stringResource(R.string.move_back),
|
||||
description = stringResource(R.string.move_back_hint),
|
||||
enabled = canBack,
|
||||
modifier = Modifier.weight(1f),
|
||||
iconSize = 32,
|
||||
mirrored = true,
|
||||
onLongClickLabel = stringResource(R.string.to_start),
|
||||
onLongClick = onStart,
|
||||
onClick = onBack,
|
||||
)
|
||||
BarButton(
|
||||
icon = Icons.Rounded.PlayArrow,
|
||||
label = stringResource(R.string.move_forward),
|
||||
description = stringResource(R.string.move_forward_hint),
|
||||
enabled = canForward,
|
||||
modifier = Modifier.weight(1f),
|
||||
iconSize = 32,
|
||||
onLongClickLabel = stringResource(R.string.to_end),
|
||||
onLongClick = onEnd,
|
||||
onClick = onForward,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -36,8 +36,6 @@
|
|||
<string name="to_start">Zum Anfang</string>
|
||||
<string name="move_back">Zug zurück</string>
|
||||
<string name="move_forward">Zug vor</string>
|
||||
<string name="move_back_hint">Vorheriger Zug. Gedrückt halten: zum Anfang</string>
|
||||
<string name="move_forward_hint">Nächster Zug. Gedrückt halten: zum Ende der Variante</string>
|
||||
<string name="to_end">Zum Ende der Variante</string>
|
||||
<string name="next_moves">Weiter:</string>
|
||||
<string name="board_description">Brett, Stellung nach %1$s</string>
|
||||
|
|
@ -669,56 +667,4 @@
|
|||
<string name="strength_range">%1$s, von %2$s bis %3$s</string>
|
||||
<string name="strength">Spielstärke</string>
|
||||
<string name="books_delete_cd">Eröffnungsbücher löschen</string>
|
||||
|
||||
<!-- Vorbereitung auf den Gegner (Aufgabe 48). -->
|
||||
<string name="players">Spieler</string>
|
||||
<string name="player_name_hint">Spielername</string>
|
||||
<string name="players_read_failed">Spieler konnten nicht gelesen werden</string>
|
||||
<string name="reading_players">Spieler werden gelesen…</string>
|
||||
<string name="no_named_players">Diese Datenbank enthält keine benannten Spieler</string>
|
||||
<string name="player_not_found">Spieler nicht gefunden</string>
|
||||
<string name="to_games">Zu den Partien</string>
|
||||
<string name="reset_search">Suche zurücksetzen</string>
|
||||
<string name="prepare_action">Vorbereiten</string>
|
||||
<string name="prep_choose_color">Farbe wählen</string>
|
||||
<string name="prep_against_player">Vorbereiten gegen %1$s</string>
|
||||
<string name="prep_against_white">Gegen Weiß</string>
|
||||
<string name="prep_against_black">Gegen Schwarz</string>
|
||||
<string name="prep_opponent">Auf Gegner vorbereiten…</string>
|
||||
<string name="prep_title">Vorbereitung auf den Gegner</string>
|
||||
<string name="prep_close_engine_line">Schließen Sie zuerst die Engine-Variante</string>
|
||||
<!--suppress TypographyDashes: literal PGN null move -->
|
||||
<string name="prep_null_move_unavailable">Suche nach einem Lehrzug -- ist nicht verfügbar</string>
|
||||
<string name="prep_as_white">Weiß</string>
|
||||
<string name="prep_as_black">Schwarz</string>
|
||||
<string name="prep_move_failed">Dieser Zug konnte nicht ausgeführt werden</string>
|
||||
<string name="prep_play_continuation">%1$s spielen, %2$s, %3$s Prozent</string>
|
||||
<string name="prep_board_start">Brett, Ausgangsstellung. %1$s unten.</string>
|
||||
<string name="prep_board_after">Brett, Stellung nach %1$s. %2$s unten.</string>
|
||||
<string name="turn_white">Weiß am Zug</string>
|
||||
<string name="turn_black">Schwarz am Zug</string>
|
||||
<string name="prep_opponent_plays">Gegner spielt</string>
|
||||
<string name="prep_opponents_play">Seine Gegner spielen</string>
|
||||
<string name="prep_after">nach %1$s</string>
|
||||
<string name="prep_beginning">Anfang</string>
|
||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
||||
<string name="prep_failed">Fortsetzungen konnten nicht berechnet werden</string>
|
||||
<string name="prep_no_memory">Nicht genügend Speicher für die Suche in dieser Datenbank</string>
|
||||
<string name="prep_calculating">Fortsetzungen werden berechnet…</string>
|
||||
<string name="prep_position_absent">Diese Stellung kommt in Partien von %1$s nicht vor</string>
|
||||
<string name="prep_position_absent_hint">Sie können auf dem Brett fortsetzen oder zurückgehen</string>
|
||||
<string name="prep_all_ended">Alle Partien endeten hier</string>
|
||||
<string name="prep_ended_here">Hier beendet: %1$s</string>
|
||||
<string name="prep_no_normal">Keine normale Fortsetzung: %1$s</string>
|
||||
<string name="to_game">Zur Partie</string>
|
||||
<string name="to_players">Zu den Spielern</string>
|
||||
<string name="prep_choose_move">Zug auswählen</string>
|
||||
<plurals name="prep_wins"><item quantity="one">%1$s Sieg</item><item quantity="other">%1$s Siege</item></plurals>
|
||||
<plurals name="prep_draws"><item quantity="one">%1$s Remis</item><item quantity="other">%1$s Remis</item></plurals>
|
||||
<plurals name="prep_losses"><item quantity="one">%1$s Niederlage</item><item quantity="other">%1$s Niederlagen</item></plurals>
|
||||
<string name="prep_unknown_accessibility">Unbekannte Ergebnisse: %1$d; nicht in den Prozentwerten enthalten.</string>
|
||||
<string name="prep_continuation_description">%1$s. %2$d von %3$s, %4$s Prozent. Ergebnisse für %5$s: %6$s, %7$s, %8$s; %9$s, %10$s und %11$s Prozent. %12$s Spielen.</string>
|
||||
<string name="prep_play">Spielen</string>
|
||||
<string name="prep_unknown_short">weitere %1$s</string>
|
||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -37,8 +37,6 @@
|
|||
<string name="to_start">Al inicio</string>
|
||||
<string name="move_back">Jugada atrás</string>
|
||||
<string name="move_forward">Jugada adelante</string>
|
||||
<string name="move_back_hint">Jugada anterior. Mantén pulsado para ir al inicio</string>
|
||||
<string name="move_forward_hint">Jugada siguiente. Mantén pulsado para ir al final de la línea</string>
|
||||
<string name="to_end">Al final de la línea</string>
|
||||
<string name="next_moves">Siguiente:</string>
|
||||
<string name="board_description">Tablero, posición tras %1$s</string>
|
||||
|
|
@ -678,56 +676,4 @@
|
|||
<string name="strength_range">%1$s, de %2$s a %3$s</string>
|
||||
<string name="strength">Fuerza</string>
|
||||
<string name="books_delete_cd">Eliminar los libros de aperturas</string>
|
||||
|
||||
<!-- Preparación contra el rival (tarea 48). -->
|
||||
<string name="players">Jugadores</string>
|
||||
<string name="player_name_hint">Nombre del jugador</string>
|
||||
<string name="players_read_failed">No se pudieron leer los jugadores</string>
|
||||
<string name="reading_players">Leyendo jugadores…</string>
|
||||
<string name="no_named_players">No hay jugadores con nombre en esta base</string>
|
||||
<string name="player_not_found">Jugador no encontrado</string>
|
||||
<string name="to_games">Volver a las partidas</string>
|
||||
<string name="reset_search">Borrar búsqueda</string>
|
||||
<string name="prepare_action">Preparar</string>
|
||||
<string name="prep_choose_color">Elige un color</string>
|
||||
<string name="prep_against_player">Prepararse contra %1$s</string>
|
||||
<string name="prep_against_white">Contra las blancas</string>
|
||||
<string name="prep_against_black">Contra las negras</string>
|
||||
<string name="prep_opponent">Prepararse contra el rival…</string>
|
||||
<string name="prep_title">Preparación contra el rival</string>
|
||||
<string name="prep_close_engine_line">Cierra primero la línea del motor</string>
|
||||
<!--suppress TypographyDashes: literal PGN null move -->
|
||||
<string name="prep_null_move_unavailable">La búsqueda después de un -- didáctico no está disponible</string>
|
||||
<string name="prep_as_white">Blancas</string>
|
||||
<string name="prep_as_black">Negras</string>
|
||||
<string name="prep_move_failed">No se pudo jugar este movimiento</string>
|
||||
<string name="prep_play_continuation">Jugar %1$s, %2$s, %3$s por ciento</string>
|
||||
<string name="prep_board_start">Tablero, posición inicial. %1$s abajo.</string>
|
||||
<string name="prep_board_after">Tablero, posición después de %1$s. %2$s abajo.</string>
|
||||
<string name="turn_white">Juegan las blancas</string>
|
||||
<string name="turn_black">Juegan las negras</string>
|
||||
<string name="prep_opponent_plays">Juega el rival</string>
|
||||
<string name="prep_opponents_play">Juegan sus rivales</string>
|
||||
<string name="prep_after">después de %1$s</string>
|
||||
<string name="prep_beginning">inicio</string>
|
||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
||||
<string name="prep_failed">No se pudieron calcular las continuaciones</string>
|
||||
<string name="prep_no_memory">No hay memoria suficiente para buscar en esta base</string>
|
||||
<string name="prep_calculating">Calculando continuaciones…</string>
|
||||
<string name="prep_position_absent">Esta posición no aparece en las partidas de %1$s</string>
|
||||
<string name="prep_position_absent_hint">Puedes continuar en el tablero o retroceder</string>
|
||||
<string name="prep_all_ended">Todas las partidas terminaron aquí</string>
|
||||
<string name="prep_ended_here">Terminaron aquí: %1$s</string>
|
||||
<string name="prep_no_normal">Sin continuación normal: %1$s</string>
|
||||
<string name="to_game">Volver a la partida</string>
|
||||
<string name="to_players">Volver a los jugadores</string>
|
||||
<string name="prep_choose_move">Elige un movimiento</string>
|
||||
<plurals name="prep_wins"><item quantity="one">%1$s victoria</item><item quantity="many">%1$s victorias</item><item quantity="other">%1$s victorias</item></plurals>
|
||||
<plurals name="prep_draws"><item quantity="one">%1$s tabla</item><item quantity="many">%1$s tablas</item><item quantity="other">%1$s tablas</item></plurals>
|
||||
<plurals name="prep_losses"><item quantity="one">%1$s derrota</item><item quantity="many">%1$s derrotas</item><item quantity="other">%1$s derrotas</item></plurals>
|
||||
<string name="prep_unknown_accessibility">Resultados desconocidos: %1$d; excluidos de los porcentajes.</string>
|
||||
<string name="prep_continuation_description">%1$s. %2$d de %3$s, %4$s por ciento. Resultados de %5$s: %6$s, %7$s, %8$s; %9$s, %10$s y %11$s por ciento. %12$s Jugar.</string>
|
||||
<string name="prep_play">Jugar</string>
|
||||
<string name="prep_unknown_short">%1$s más</string>
|
||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -37,8 +37,6 @@
|
|||
<string name="to_start">Au début</string>
|
||||
<string name="move_back">Coup précédent</string>
|
||||
<string name="move_forward">Coup suivant</string>
|
||||
<string name="move_back_hint">Coup précédent. Maintenez pour aller au début</string>
|
||||
<string name="move_forward_hint">Coup suivant. Maintenez pour aller à la fin de la ligne</string>
|
||||
<string name="to_end">À la fin de la ligne</string>
|
||||
<string name="next_moves">Suite :</string>
|
||||
<string name="board_description">Échiquier, position après %1$s</string>
|
||||
|
|
@ -678,56 +676,4 @@
|
|||
<string name="strength_range">%1$s, de %2$s à %3$s</string>
|
||||
<string name="strength">Force</string>
|
||||
<string name="books_delete_cd">Supprimer les livres d’ouvertures</string>
|
||||
|
||||
<!-- Préparation contre l’adversaire (tâche 48). -->
|
||||
<string name="players">Joueurs</string>
|
||||
<string name="player_name_hint">Nom du joueur</string>
|
||||
<string name="players_read_failed">Impossible de lire les joueurs</string>
|
||||
<string name="reading_players">Lecture des joueurs…</string>
|
||||
<string name="no_named_players">Cette base ne contient aucun joueur nommé</string>
|
||||
<string name="player_not_found">Joueur introuvable</string>
|
||||
<string name="to_games">Retour aux parties</string>
|
||||
<string name="reset_search">Effacer la recherche</string>
|
||||
<string name="prepare_action">Préparer</string>
|
||||
<string name="prep_choose_color">Choisissez la couleur</string>
|
||||
<string name="prep_against_player">Préparer contre %1$s</string>
|
||||
<string name="prep_against_white">Contre les Blancs</string>
|
||||
<string name="prep_against_black">Contre les Noirs</string>
|
||||
<string name="prep_opponent">Préparer contre l’adversaire…</string>
|
||||
<string name="prep_title">Préparation contre l’adversaire</string>
|
||||
<string name="prep_close_engine_line">Fermez d’abord la ligne du moteur</string>
|
||||
<!--suppress TypographyDashes: literal PGN null move -->
|
||||
<string name="prep_null_move_unavailable">La recherche après un -- pédagogique est indisponible</string>
|
||||
<string name="prep_as_white">Blancs</string>
|
||||
<string name="prep_as_black">Noirs</string>
|
||||
<string name="prep_move_failed">Impossible de jouer ce coup</string>
|
||||
<string name="prep_play_continuation">Jouer %1$s, %2$s, %3$s pour cent</string>
|
||||
<string name="prep_board_start">Échiquier, position initiale. %1$s en bas.</string>
|
||||
<string name="prep_board_after">Échiquier, position après %1$s. %2$s en bas.</string>
|
||||
<string name="turn_white">Trait aux blancs</string>
|
||||
<string name="turn_black">Trait aux noirs</string>
|
||||
<string name="prep_opponent_plays">L’adversaire joue</string>
|
||||
<string name="prep_opponents_play">Ses adversaires jouent</string>
|
||||
<string name="prep_after">après %1$s</string>
|
||||
<string name="prep_beginning">début</string>
|
||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
||||
<string name="prep_failed">Impossible de calculer les continuations</string>
|
||||
<string name="prep_no_memory">Mémoire insuffisante pour rechercher dans cette base</string>
|
||||
<string name="prep_calculating">Calcul des continuations…</string>
|
||||
<string name="prep_position_absent">Cette position n’apparaît pas dans les parties de %1$s</string>
|
||||
<string name="prep_position_absent_hint">Vous pouvez continuer sur l’échiquier ou revenir en arrière</string>
|
||||
<string name="prep_all_ended">Toutes les parties se terminent ici</string>
|
||||
<string name="prep_ended_here">Terminées ici : %1$s</string>
|
||||
<string name="prep_no_normal">Aucune continuation normale : %1$s</string>
|
||||
<string name="to_game">Retour à la partie</string>
|
||||
<string name="to_players">Retour aux joueurs</string>
|
||||
<string name="prep_choose_move">Choisir un coup</string>
|
||||
<plurals name="prep_wins"><item quantity="one">%1$s victoire</item><item quantity="many">%1$s victoires</item><item quantity="other">%1$s victoires</item></plurals>
|
||||
<plurals name="prep_draws"><item quantity="one">%1$s nulle</item><item quantity="many">%1$s nulles</item><item quantity="other">%1$s nulles</item></plurals>
|
||||
<plurals name="prep_losses"><item quantity="one">%1$s défaite</item><item quantity="many">%1$s défaites</item><item quantity="other">%1$s défaites</item></plurals>
|
||||
<string name="prep_unknown_accessibility">Résultats inconnus : %1$d ; exclus des pourcentages.</string>
|
||||
<string name="prep_continuation_description">%1$s. %2$d sur %3$s, %4$s pour cent. Résultats de %5$s : %6$s, %7$s, %8$s ; %9$s, %10$s et %11$s pour cent. %12$s Jouer.</string>
|
||||
<string name="prep_play">Jouer</string>
|
||||
<string name="prep_unknown_short">plus %1$s</string>
|
||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -37,8 +37,6 @@
|
|||
<string name="to_start">All\'inizio</string>
|
||||
<string name="move_back">Mossa indietro</string>
|
||||
<string name="move_forward">Mossa avanti</string>
|
||||
<string name="move_back_hint">Mossa precedente. Tieni premuto per andare all\'inizio</string>
|
||||
<string name="move_forward_hint">Mossa successiva. Tieni premuto per andare alla fine della linea</string>
|
||||
<string name="to_end">Alla fine della linea</string>
|
||||
<string name="next_moves">Seguito:</string>
|
||||
<string name="board_description">Scacchiera, posizione dopo %1$s</string>
|
||||
|
|
@ -678,56 +676,4 @@
|
|||
<string name="strength_range">%1$s, da %2$s a %3$s</string>
|
||||
<string name="strength">Forza</string>
|
||||
<string name="books_delete_cd">Elimina i libri di aperture</string>
|
||||
|
||||
<!-- Preparazione contro l\'avversario (attività 48). -->
|
||||
<string name="players">Giocatori</string>
|
||||
<string name="player_name_hint">Nome del giocatore</string>
|
||||
<string name="players_read_failed">Impossibile leggere i giocatori</string>
|
||||
<string name="reading_players">Lettura dei giocatori…</string>
|
||||
<string name="no_named_players">Questo database non contiene giocatori con nome</string>
|
||||
<string name="player_not_found">Giocatore non trovato</string>
|
||||
<string name="to_games">Torna alle partite</string>
|
||||
<string name="reset_search">Cancella ricerca</string>
|
||||
<string name="prepare_action">Prepara</string>
|
||||
<string name="prep_choose_color">Scegli un colore</string>
|
||||
<string name="prep_against_player">Preparati contro %1$s</string>
|
||||
<string name="prep_against_white">Contro il Bianco</string>
|
||||
<string name="prep_against_black">Contro il Nero</string>
|
||||
<string name="prep_opponent">Preparati contro l\'avversario…</string>
|
||||
<string name="prep_title">Preparazione contro l\'avversario</string>
|
||||
<string name="prep_close_engine_line">Chiudi prima la linea del motore</string>
|
||||
<!--suppress TypographyDashes: literal PGN null move -->
|
||||
<string name="prep_null_move_unavailable">La ricerca dopo un -- didattico non è disponibile</string>
|
||||
<string name="prep_as_white">Bianco</string>
|
||||
<string name="prep_as_black">Nero</string>
|
||||
<string name="prep_move_failed">Impossibile giocare questa mossa</string>
|
||||
<string name="prep_play_continuation">Gioca %1$s, %2$s, %3$s per cento</string>
|
||||
<string name="prep_board_start">Scacchiera, posizione iniziale. %1$s in basso.</string>
|
||||
<string name="prep_board_after">Scacchiera, posizione dopo %1$s. %2$s in basso.</string>
|
||||
<string name="turn_white">Tocca al bianco</string>
|
||||
<string name="turn_black">Tocca al nero</string>
|
||||
<string name="prep_opponent_plays">Gioca l\'avversario</string>
|
||||
<string name="prep_opponents_play">Giocano i suoi avversari</string>
|
||||
<string name="prep_after">dopo %1$s</string>
|
||||
<string name="prep_beginning">inizio</string>
|
||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
||||
<string name="prep_failed">Impossibile calcolare le continuazioni</string>
|
||||
<string name="prep_no_memory">Memoria insufficiente per cercare in questo database</string>
|
||||
<string name="prep_calculating">Calcolo delle continuazioni…</string>
|
||||
<string name="prep_position_absent">Questa posizione non compare nelle partite di %1$s</string>
|
||||
<string name="prep_position_absent_hint">Puoi continuare sulla scacchiera o tornare indietro</string>
|
||||
<string name="prep_all_ended">Tutte le partite sono terminate qui</string>
|
||||
<string name="prep_ended_here">Terminate qui: %1$s</string>
|
||||
<string name="prep_no_normal">Nessuna continuazione normale: %1$s</string>
|
||||
<string name="to_game">Torna alla partita</string>
|
||||
<string name="to_players">Torna ai giocatori</string>
|
||||
<string name="prep_choose_move">Scegli una mossa</string>
|
||||
<plurals name="prep_wins"><item quantity="one">%1$s vittoria</item><item quantity="many">%1$s vittorie</item><item quantity="other">%1$s vittorie</item></plurals>
|
||||
<plurals name="prep_draws"><item quantity="one">%1$s patta</item><item quantity="many">%1$s patte</item><item quantity="other">%1$s patte</item></plurals>
|
||||
<plurals name="prep_losses"><item quantity="one">%1$s sconfitta</item><item quantity="many">%1$s sconfitte</item><item quantity="other">%1$s sconfitte</item></plurals>
|
||||
<string name="prep_unknown_accessibility">Risultati sconosciuti: %1$d; esclusi dalle percentuali.</string>
|
||||
<string name="prep_continuation_description">%1$s. %2$d di %3$s, %4$s per cento. Risultati di %5$s: %6$s, %7$s, %8$s; %9$s, %10$s e %11$s per cento. %12$s Gioca.</string>
|
||||
<string name="prep_play">Gioca</string>
|
||||
<string name="prep_unknown_short">altri %1$s</string>
|
||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -36,8 +36,6 @@
|
|||
<string name="to_start">Басына</string>
|
||||
<string name="move_back">Бір жүріс артқа</string>
|
||||
<string name="move_forward">Бір жүріс алға</string>
|
||||
<string name="move_back_hint">Алдыңғы жүріс. Басына өту үшін басып тұрыңыз</string>
|
||||
<string name="move_forward_hint">Келесі жүріс. Варианттың соңына өту үшін басып тұрыңыз</string>
|
||||
<string name="to_end">Варианттың соңына</string>
|
||||
<string name="next_moves">Келесі:</string>
|
||||
<string name="board_description">Тақта, %1$s кейінгі позиция</string>
|
||||
|
|
@ -670,56 +668,4 @@
|
|||
<string name="strength_range">%1$s, %2$s-ден %3$s-ге дейін</string>
|
||||
<string name="strength">Күші</string>
|
||||
<string name="books_delete_cd">Дебют кітаптарын жою</string>
|
||||
|
||||
<!-- Қарсыласқа дайындық (48-тапсырма). -->
|
||||
<string name="players">Ойыншылар</string>
|
||||
<string name="player_name_hint">Ойыншының аты</string>
|
||||
<string name="players_read_failed">Ойыншыларды оқу мүмкін болмады</string>
|
||||
<string name="reading_players">Ойыншылар оқылуда…</string>
|
||||
<string name="no_named_players">Бұл базада аты көрсетілген ойыншылар жоқ</string>
|
||||
<string name="player_not_found">Ойыншы табылмады</string>
|
||||
<string name="to_games">Партияларға оралу</string>
|
||||
<string name="reset_search">Іздеуді тазалау</string>
|
||||
<string name="prepare_action">Дайындалу</string>
|
||||
<string name="prep_choose_color">Түсті таңдаңыз</string>
|
||||
<string name="prep_against_player">Қарсыласқа дайындалу %1$s</string>
|
||||
<string name="prep_against_white">Ақтарға қарсы</string>
|
||||
<string name="prep_against_black">Қараларға қарсы</string>
|
||||
<string name="prep_opponent">Қарсыласқа дайындалу…</string>
|
||||
<string name="prep_title">Қарсыласқа дайындық</string>
|
||||
<string name="prep_close_engine_line">Алдымен қозғалтқыш желісін жабыңыз</string>
|
||||
<!--suppress TypographyDashes: literal PGN null move -->
|
||||
<string name="prep_null_move_unavailable">Оқу -- кейін іздеу қолжетімсіз</string>
|
||||
<string name="prep_as_white">Ақтар</string>
|
||||
<string name="prep_as_black">Қаралар</string>
|
||||
<string name="prep_move_failed">Бұл жүрісті жасау мүмкін болмады</string>
|
||||
<string name="prep_play_continuation">%1$s жүру, %2$s, %3$s пайыз</string>
|
||||
<string name="prep_board_start">Тақта, бастапқы позиция. Төменде %1$s.</string>
|
||||
<string name="prep_board_after">Тақта, %1$s кейінгі позиция. Төменде %2$s.</string>
|
||||
<string name="turn_white">Ақтардың жүрісі</string>
|
||||
<string name="turn_black">Қаралардың жүрісі</string>
|
||||
<string name="prep_opponent_plays">Қарсылас жүреді</string>
|
||||
<string name="prep_opponents_play">Оның қарсыластары жүреді</string>
|
||||
<string name="prep_after">%1$s кейін</string>
|
||||
<string name="prep_beginning">басы</string>
|
||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
||||
<string name="prep_failed">Жалғастарды есептеу мүмкін болмады</string>
|
||||
<string name="prep_no_memory">Бұл базадан іздеуге жад жеткіліксіз</string>
|
||||
<string name="prep_calculating">Жалғастар есептелуде…</string>
|
||||
<string name="prep_position_absent">%1$s партияларында бұл позиция жоқ</string>
|
||||
<string name="prep_position_absent_hint">Тақтада жалғастыруға немесе артқа оралуға болады</string>
|
||||
<string name="prep_all_ended">Барлық партия осы жерде аяқталды</string>
|
||||
<string name="prep_ended_here">Осы жерде аяқталды: %1$s</string>
|
||||
<string name="prep_no_normal">Қалыпты жалғас жоқ: %1$s</string>
|
||||
<string name="to_game">Партияға оралу</string>
|
||||
<string name="to_players">Ойыншыларға оралу</string>
|
||||
<string name="prep_choose_move">Жүрісті таңдаңыз</string>
|
||||
<plurals name="prep_wins"><item quantity="one">%1$s жеңіс</item><item quantity="other">%1$s жеңіс</item></plurals>
|
||||
<plurals name="prep_draws"><item quantity="one">%1$s тең ойын</item><item quantity="other">%1$s тең ойын</item></plurals>
|
||||
<plurals name="prep_losses"><item quantity="one">%1$s жеңіліс</item><item quantity="other">%1$s жеңіліс</item></plurals>
|
||||
<string name="prep_unknown_accessibility">Белгісіз нәтижелер: %1$d; олар пайызға кірмейді.</string>
|
||||
<string name="prep_continuation_description">%1$s. %3$s ішінен %2$d, %4$s пайыз. %5$s нәтижелері: %6$s, %7$s, %8$s; %9$s, %10$s және %11$s пайыз. %12$s Жүру.</string>
|
||||
<string name="prep_play">Жүру</string>
|
||||
<string name="prep_unknown_short">тағы %1$s</string>
|
||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -37,8 +37,6 @@
|
|||
<string name="to_start">Ao início</string>
|
||||
<string name="move_back">Voltar um lance</string>
|
||||
<string name="move_forward">Avançar um lance</string>
|
||||
<string name="move_back_hint">Lance anterior. Mantenha premido para ir ao início</string>
|
||||
<string name="move_forward_hint">Lance seguinte. Mantenha premido para ir ao fim da linha</string>
|
||||
<string name="to_end">Ao fim da linha</string>
|
||||
<string name="next_moves">Próximo:</string>
|
||||
<string name="board_description">Tabuleiro, posição após %1$s</string>
|
||||
|
|
@ -679,56 +677,4 @@
|
|||
<string name="strength_range">%1$s, de %2$s a %3$s</string>
|
||||
<string name="strength">Força</string>
|
||||
<string name="books_delete_cd">Excluir os livros de aberturas</string>
|
||||
|
||||
<!-- Preparação contra o adversário (tarefa 48). -->
|
||||
<string name="players">Jogadores</string>
|
||||
<string name="player_name_hint">Nome do jogador</string>
|
||||
<string name="players_read_failed">Não foi possível ler os jogadores</string>
|
||||
<string name="reading_players">A ler jogadores…</string>
|
||||
<string name="no_named_players">Não há jogadores identificados nesta base</string>
|
||||
<string name="player_not_found">Jogador não encontrado</string>
|
||||
<string name="to_games">Voltar às partidas</string>
|
||||
<string name="reset_search">Limpar pesquisa</string>
|
||||
<string name="prepare_action">Preparar</string>
|
||||
<string name="prep_choose_color">Escolha uma cor</string>
|
||||
<string name="prep_against_player">Preparar contra %1$s</string>
|
||||
<string name="prep_against_white">Contra as brancas</string>
|
||||
<string name="prep_against_black">Contra as pretas</string>
|
||||
<string name="prep_opponent">Preparar contra o adversário…</string>
|
||||
<string name="prep_title">Preparação contra o adversário</string>
|
||||
<string name="prep_close_engine_line">Feche primeiro a linha do motor</string>
|
||||
<!--suppress TypographyDashes: literal PGN null move -->
|
||||
<string name="prep_null_move_unavailable">A pesquisa depois de um -- didático não está disponível</string>
|
||||
<string name="prep_as_white">Brancas</string>
|
||||
<string name="prep_as_black">Pretas</string>
|
||||
<string name="prep_move_failed">Não foi possível jogar este lance</string>
|
||||
<string name="prep_play_continuation">Jogar %1$s, %2$s, %3$s por cento</string>
|
||||
<string name="prep_board_start">Tabuleiro, posição inicial. %1$s em baixo.</string>
|
||||
<string name="prep_board_after">Tabuleiro, posição depois de %1$s. %2$s em baixo.</string>
|
||||
<string name="turn_white">Jogam as brancas</string>
|
||||
<string name="turn_black">Jogam as pretas</string>
|
||||
<string name="prep_opponent_plays">O adversário joga</string>
|
||||
<string name="prep_opponents_play">Os seus adversários jogam</string>
|
||||
<string name="prep_after">depois de %1$s</string>
|
||||
<string name="prep_beginning">início</string>
|
||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
||||
<string name="prep_failed">Não foi possível calcular as continuações</string>
|
||||
<string name="prep_no_memory">Memória insuficiente para pesquisar nesta base</string>
|
||||
<string name="prep_calculating">A calcular continuações…</string>
|
||||
<string name="prep_position_absent">Esta posição não ocorre nas partidas de %1$s</string>
|
||||
<string name="prep_position_absent_hint">Pode continuar no tabuleiro ou retroceder</string>
|
||||
<string name="prep_all_ended">Todas as partidas terminaram aqui</string>
|
||||
<string name="prep_ended_here">Terminaram aqui: %1$s</string>
|
||||
<string name="prep_no_normal">Sem continuação normal: %1$s</string>
|
||||
<string name="to_game">Voltar à partida</string>
|
||||
<string name="to_players">Voltar aos jogadores</string>
|
||||
<string name="prep_choose_move">Escolha um lance</string>
|
||||
<plurals name="prep_wins"><item quantity="one">%1$s vitória</item><item quantity="many">%1$s vitórias</item><item quantity="other">%1$s vitórias</item></plurals>
|
||||
<plurals name="prep_draws"><item quantity="one">%1$s empate</item><item quantity="many">%1$s empates</item><item quantity="other">%1$s empates</item></plurals>
|
||||
<plurals name="prep_losses"><item quantity="one">%1$s derrota</item><item quantity="many">%1$s derrotas</item><item quantity="other">%1$s derrotas</item></plurals>
|
||||
<string name="prep_unknown_accessibility">Resultados desconhecidos: %1$d; excluídos das percentagens.</string>
|
||||
<string name="prep_continuation_description">%1$s. %2$d de %3$s, %4$s por cento. Resultados de %5$s: %6$s, %7$s, %8$s; %9$s, %10$s e %11$s por cento. %12$s Jogar.</string>
|
||||
<string name="prep_play">Jogar</string>
|
||||
<string name="prep_unknown_short">mais %1$s</string>
|
||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -38,8 +38,6 @@
|
|||
<string name="to_start">В начало</string>
|
||||
<string name="move_back">Ход назад</string>
|
||||
<string name="move_forward">Ход вперёд</string>
|
||||
<string name="move_back_hint">Предыдущий ход. Удерживайте для перехода в начало</string>
|
||||
<string name="move_forward_hint">Следующий ход. Удерживайте для перехода в конец линии</string>
|
||||
<string name="to_end">В конец линии</string>
|
||||
<string name="next_moves">Дальше:</string>
|
||||
<string name="board_description">Доска, позиция после %1$s</string>
|
||||
|
|
@ -687,71 +685,4 @@
|
|||
<string name="strength_range">%1$s, от %2$s до %3$s</string>
|
||||
<string name="strength">Сила</string>
|
||||
<string name="books_delete_cd">Удалить дебютные книги</string>
|
||||
|
||||
<!-- Подготовка к сопернику (задача 48). -->
|
||||
<string name="players">Игроки</string>
|
||||
<string name="player_name_hint">Имя игрока</string>
|
||||
<string name="players_read_failed">Не удалось прочитать игроков</string>
|
||||
<string name="reading_players">Читаю игроков…</string>
|
||||
<string name="no_named_players">В этой базе нет именованных игроков</string>
|
||||
<string name="player_not_found">Игрок не найден</string>
|
||||
<string name="to_games">К партиям</string>
|
||||
<string name="reset_search">Сбросить поиск</string>
|
||||
<string name="prepare_action">Подготовиться</string>
|
||||
<string name="prep_choose_color">Выберите цвет</string>
|
||||
<string name="prep_against_player">Подготовиться к %1$s</string>
|
||||
<string name="prep_against_white">Против белых</string>
|
||||
<string name="prep_against_black">Против чёрных</string>
|
||||
<string name="prep_opponent">Подготовиться к сопернику…</string>
|
||||
<string name="prep_title">Подготовка к сопернику</string>
|
||||
<string name="prep_close_engine_line">Сначала закройте линию движка</string>
|
||||
<!--suppress TypographyDashes: literal PGN null move -->
|
||||
<string name="prep_null_move_unavailable">Поиск после учебного -- недоступен</string>
|
||||
<string name="prep_as_white">Белыми</string>
|
||||
<string name="prep_as_black">Чёрными</string>
|
||||
<string name="prep_move_failed">Не удалось сделать ход</string>
|
||||
<string name="prep_play_continuation">Сыграть %1$s, %2$s, %3$s процентов</string>
|
||||
<string name="prep_board_start">Доска, начальная позиция. Внизу %1$s.</string>
|
||||
<string name="prep_board_after">Доска, позиция после %1$s. Внизу %2$s.</string>
|
||||
<string name="turn_white">ход белых</string>
|
||||
<string name="turn_black">ход чёрных</string>
|
||||
<string name="prep_opponent_plays">Соперник играет</string>
|
||||
<string name="prep_opponents_play">Его оппоненты играют</string>
|
||||
<string name="prep_after">после %1$s</string>
|
||||
<string name="prep_beginning">начало</string>
|
||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
||||
<string name="prep_failed">Не удалось посчитать продолжения</string>
|
||||
<string name="prep_no_memory">Недостаточно памяти для поиска по этой базе</string>
|
||||
<string name="prep_calculating">Считаю продолжения…</string>
|
||||
<string name="prep_position_absent">В партиях %1$s этой позиции нет</string>
|
||||
<string name="prep_position_absent_hint">Можно продолжить на доске или вернуться назад</string>
|
||||
<string name="prep_all_ended">Все партии здесь закончились</string>
|
||||
<string name="prep_ended_here">Здесь закончились: %1$s</string>
|
||||
<string name="prep_no_normal">Нет обычного продолжения: %1$s</string>
|
||||
<string name="to_game">К партии</string>
|
||||
<string name="to_players">К игрокам</string>
|
||||
<string name="prep_choose_move">Выберите ход</string>
|
||||
<plurals name="prep_wins">
|
||||
<item quantity="one">%1$s победа</item>
|
||||
<item quantity="few">%1$s победы</item>
|
||||
<item quantity="many">%1$s побед</item>
|
||||
<item quantity="other">%1$s победы</item>
|
||||
</plurals>
|
||||
<plurals name="prep_draws">
|
||||
<item quantity="one">%1$s ничья</item>
|
||||
<item quantity="few">%1$s ничьи</item>
|
||||
<item quantity="many">%1$s ничьих</item>
|
||||
<item quantity="other">%1$s ничьи</item>
|
||||
</plurals>
|
||||
<plurals name="prep_losses">
|
||||
<item quantity="one">%1$s поражение</item>
|
||||
<item quantity="few">%1$s поражения</item>
|
||||
<item quantity="many">%1$s поражений</item>
|
||||
<item quantity="other">%1$s поражения</item>
|
||||
</plurals>
|
||||
<string name="prep_unknown_accessibility">Неизвестных исходов: %1$d; они не входят в знаменатель процентов.</string>
|
||||
<string name="prep_continuation_description">%1$s. %2$d из %3$s, %4$s процентов. Результаты %5$s: %6$s, %7$s, %8$s; %9$s, %10$s и %11$s процентов. %12$s Сыграть.</string>
|
||||
<string name="prep_play">Сыграть</string>
|
||||
<string name="prep_unknown_short">ещё %1$s</string>
|
||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -37,8 +37,6 @@
|
|||
<string name="to_start">Boshiga</string>
|
||||
<string name="move_back">Bir yurish orqaga</string>
|
||||
<string name="move_forward">Bir yurish oldinga</string>
|
||||
<string name="move_back_hint">Oldingi yurish. Boshiga oʻtish uchun bosib turing</string>
|
||||
<string name="move_forward_hint">Keyingi yurish. Liniya oxiriga oʻtish uchun bosib turing</string>
|
||||
<string name="to_end">Liniya oxiriga</string>
|
||||
<string name="next_moves">Keyin:</string>
|
||||
<string name="board_description">Taxta, %1$sdan keyingi pozitsiya</string>
|
||||
|
|
@ -668,56 +666,4 @@
|
|||
<string name="strength_range">%1$s, %2$s dan %3$s gacha</string>
|
||||
<string name="strength">Kuch</string>
|
||||
<string name="books_delete_cd">Debyut kitoblarini o‘chirish</string>
|
||||
|
||||
<!-- Raqibga tayyorgarlik (48-vazifa). -->
|
||||
<string name="players">Oʻyinchilar</string>
|
||||
<string name="player_name_hint">Oʻyinchi ismi</string>
|
||||
<string name="players_read_failed">Oʻyinchilarni oʻqib boʻlmadi</string>
|
||||
<string name="reading_players">Oʻyinchilar oʻqilmoqda…</string>
|
||||
<string name="no_named_players">Bu bazada nomi koʻrsatilgan oʻyinchilar yoʻq</string>
|
||||
<string name="player_not_found">Oʻyinchi topilmadi</string>
|
||||
<string name="to_games">Partiyalarga qaytish</string>
|
||||
<string name="reset_search">Qidiruvni tozalash</string>
|
||||
<string name="prepare_action">Tayyorlanish</string>
|
||||
<string name="prep_choose_color">Rangni tanlang</string>
|
||||
<string name="prep_against_player">Raqibga tayyorlanish %1$s</string>
|
||||
<string name="prep_against_white">Oqlarga qarshi</string>
|
||||
<string name="prep_against_black">Qoralarga qarshi</string>
|
||||
<string name="prep_opponent">Raqibga tayyorlanish…</string>
|
||||
<string name="prep_title">Raqibga tayyorgarlik</string>
|
||||
<string name="prep_close_engine_line">Avval dvigatel chizigʻini yoping</string>
|
||||
<!--suppress TypographyDashes: literal PGN null move -->
|
||||
<string name="prep_null_move_unavailable">Oʻquv -- dan keyin qidirish mavjud emas</string>
|
||||
<string name="prep_as_white">Oqlar</string>
|
||||
<string name="prep_as_black">Qoralar</string>
|
||||
<string name="prep_move_failed">Bu yurishni bajarib boʻlmadi</string>
|
||||
<string name="prep_play_continuation">%1$s yurish, %2$s, %3$s foiz</string>
|
||||
<string name="prep_board_start">Doska, boshlangʻich pozitsiya. Pastda %1$s.</string>
|
||||
<string name="prep_board_after">Doska, %1$s dan keyingi pozitsiya. Pastda %2$s.</string>
|
||||
<string name="turn_white">Oqlar yurishi</string>
|
||||
<string name="turn_black">Qoralar yurishi</string>
|
||||
<string name="prep_opponent_plays">Raqib yuradi</string>
|
||||
<string name="prep_opponents_play">Uning raqiblari yuradi</string>
|
||||
<string name="prep_after">%1$s dan keyin</string>
|
||||
<string name="prep_beginning">boshlanishi</string>
|
||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
||||
<string name="prep_failed">Davomlarni hisoblab boʻlmadi</string>
|
||||
<string name="prep_no_memory">Bu bazadan qidirish uchun xotira yetarli emas</string>
|
||||
<string name="prep_calculating">Davomlar hisoblanmoqda…</string>
|
||||
<string name="prep_position_absent">%1$s partiyalarida bu pozitsiya yoʻq</string>
|
||||
<string name="prep_position_absent_hint">Doskada davom etishingiz yoki orqaga qaytishingiz mumkin</string>
|
||||
<string name="prep_all_ended">Barcha partiyalar shu yerda tugagan</string>
|
||||
<string name="prep_ended_here">Shu yerda tugagan: %1$s</string>
|
||||
<string name="prep_no_normal">Oddiy davom yoʻq: %1$s</string>
|
||||
<string name="to_game">Partiyaga qaytish</string>
|
||||
<string name="to_players">Oʻyinchilarga qaytish</string>
|
||||
<string name="prep_choose_move">Yurishni tanlang</string>
|
||||
<plurals name="prep_wins"><item quantity="one">%1$s gʻalaba</item><item quantity="other">%1$s gʻalaba</item></plurals>
|
||||
<plurals name="prep_draws"><item quantity="one">%1$s durang</item><item quantity="other">%1$s durang</item></plurals>
|
||||
<plurals name="prep_losses"><item quantity="one">%1$s magʻlubiyat</item><item quantity="other">%1$s magʻlubiyat</item></plurals>
|
||||
<string name="prep_unknown_accessibility">Nomaʼlum natijalar: %1$d; ular foizlarga kiritilmaydi.</string>
|
||||
<string name="prep_continuation_description">%1$s. %3$s dan %2$d tasi, %4$s foiz. %5$s natijalari: %6$s, %7$s, %8$s; %9$s, %10$s va %11$s foiz. %12$s Yurish.</string>
|
||||
<string name="prep_play">Yurish</string>
|
||||
<string name="prep_unknown_short">yana %1$s</string>
|
||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -37,8 +37,6 @@
|
|||
<string name="to_start">To the start</string>
|
||||
<string name="move_back">Move back</string>
|
||||
<string name="move_forward">Move forward</string>
|
||||
<string name="move_back_hint">Previous move. Hold for the first position</string>
|
||||
<string name="move_forward_hint">Next move. Hold for the end of the line</string>
|
||||
<string name="to_end">To the end of the line</string>
|
||||
<string name="next_moves">Next:</string>
|
||||
<string name="board_description">Board, position after %1$s</string>
|
||||
|
|
@ -673,65 +671,4 @@
|
|||
<string name="strength_range">%1$s, from %2$s to %3$s</string>
|
||||
<string name="strength">Strength</string>
|
||||
<string name="books_delete_cd">Delete the opening books</string>
|
||||
|
||||
<!-- Opponent preparation (task 48). -->
|
||||
<string name="players">Players</string>
|
||||
<string name="player_name_hint">Player name</string>
|
||||
<string name="players_read_failed">Could not read players</string>
|
||||
<string name="reading_players">Reading players…</string>
|
||||
<string name="no_named_players">There are no named players in this database</string>
|
||||
<string name="player_not_found">Player not found</string>
|
||||
<string name="to_games">Back to games</string>
|
||||
<string name="reset_search">Clear search</string>
|
||||
<string name="prepare_action">Prepare</string>
|
||||
<string name="prep_choose_color">Choose a color</string>
|
||||
<string name="prep_against_player">Prepare against %1$s</string>
|
||||
<string name="prep_against_white">Against White</string>
|
||||
<string name="prep_against_black">Against Black</string>
|
||||
<string name="prep_opponent">Prepare for opponent…</string>
|
||||
<string name="prep_title">Opponent preparation</string>
|
||||
<string name="prep_close_engine_line">Close the engine line first</string>
|
||||
<!--suppress TypographyDashes: literal PGN null move -->
|
||||
<string name="prep_null_move_unavailable">Search after a teaching -- is unavailable</string>
|
||||
<string name="prep_as_white">White</string>
|
||||
<string name="prep_as_black">Black</string>
|
||||
<string name="prep_move_failed">Could not play this move</string>
|
||||
<string name="prep_play_continuation">Play %1$s, %2$s, %3$s percent</string>
|
||||
<string name="prep_board_start">Board, starting position. %1$s at the bottom.</string>
|
||||
<string name="prep_board_after">Board, position after %1$s. %2$s at the bottom.</string>
|
||||
<string name="turn_white">White to move</string>
|
||||
<string name="turn_black">Black to move</string>
|
||||
<string name="prep_opponent_plays">Opponent plays</string>
|
||||
<string name="prep_opponents_play">Their opponents play</string>
|
||||
<string name="prep_after">after %1$s</string>
|
||||
<string name="prep_beginning">start</string>
|
||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
||||
<string name="prep_failed">Could not calculate continuations</string>
|
||||
<string name="prep_no_memory">Not enough memory to search this database</string>
|
||||
<string name="prep_calculating">Calculating continuations…</string>
|
||||
<string name="prep_position_absent">This position does not occur in games by %1$s</string>
|
||||
<string name="prep_position_absent_hint">You can continue on the board or go back</string>
|
||||
<string name="prep_all_ended">All games ended here</string>
|
||||
<string name="prep_ended_here">Ended here: %1$s</string>
|
||||
<string name="prep_no_normal">No normal continuation: %1$s</string>
|
||||
<string name="to_game">Back to game</string>
|
||||
<string name="to_players">Back to players</string>
|
||||
<string name="prep_choose_move">Choose a move</string>
|
||||
<plurals name="prep_wins">
|
||||
<item quantity="one">%1$s win</item>
|
||||
<item quantity="other">%1$s wins</item>
|
||||
</plurals>
|
||||
<plurals name="prep_draws">
|
||||
<item quantity="one">%1$s draw</item>
|
||||
<item quantity="other">%1$s draws</item>
|
||||
</plurals>
|
||||
<plurals name="prep_losses">
|
||||
<item quantity="one">%1$s loss</item>
|
||||
<item quantity="other">%1$s losses</item>
|
||||
</plurals>
|
||||
<string name="prep_unknown_accessibility">Unknown results: %1$d; excluded from the percentages.</string>
|
||||
<string name="prep_continuation_description">%1$s. %2$d of %3$s, %4$s percent. Results for %5$s: %6$s, %7$s, %8$s; %9$s, %10$s and %11$s percent. %12$s Play.</string>
|
||||
<string name="prep_play">Play</string>
|
||||
<string name="prep_unknown_short">more %1$s</string>
|
||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -1,41 +0,0 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class BoardArrowHitTest {
|
||||
@Test
|
||||
fun `flip changes the hit point but not UCI`() {
|
||||
val move = BoardArrowMove("e2e4", "e2", "e4", "e4")
|
||||
val square = 40f
|
||||
val center = Offset(square / 2, square / 2)
|
||||
val target = squareIndex("e4")!!
|
||||
val normal = boardCell(target, square, false) + center
|
||||
val flipped = boardCell(target, square, true) + center
|
||||
|
||||
assertEquals(listOf("e2e4"), arrowHits(normal, square, false, listOf(move), 24f).map { it.uci })
|
||||
assertTrue(arrowHits(normal, square, true, listOf(move), 24f).isEmpty())
|
||||
assertEquals(listOf("e2e4"), arrowHits(flipped, square, true, listOf(move), 24f).map { it.uci })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `overlapping targets return every conflicting UCI`() {
|
||||
val square = 35f
|
||||
val center = Offset(square / 2, square / 2)
|
||||
val target = boardCell(squareIndex("e8")!!, square, false) + center
|
||||
val moves = listOf(
|
||||
BoardArrowMove("e7e8q", "e7", "e8", "queen"),
|
||||
BoardArrowMove("e7e8n", "e7", "e8", "knight"),
|
||||
)
|
||||
|
||||
assertEquals(listOf("e7e8q", "e7e8n"), arrowHits(target, square, false, moves, 24f).map { it.uci })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `points outside the board never activate an arrow`() {
|
||||
val move = BoardArrowMove("e2e4", "e2", "e4", "e4")
|
||||
assertTrue(arrowHits(Offset(-1f, 10f), 40f, false, listOf(move), 24f).isEmpty())
|
||||
}
|
||||
}
|
||||
|
|
@ -1,54 +0,0 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class GameBarStateTest {
|
||||
@Test
|
||||
fun `loaded game can start or open its report`() {
|
||||
assertTrue(enabled())
|
||||
assertTrue(enabled(hasData = true, running = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `review is unavailable during computer play and without moves`() {
|
||||
assertFalse(enabled(gameOn = true, sessionGame = true))
|
||||
assertFalse(enabled(hasMoves = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `database game waits for its review state`() {
|
||||
assertFalse(enabled(loaded = false))
|
||||
assertTrue(enabled(sessionGame = true, loaded = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `first running database analysis disables duplicate start`() {
|
||||
assertFalse(enabled(running = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `session game cannot duplicate its first run`() {
|
||||
assertFalse(enabled(sessionGame = true, loaded = true, running = true))
|
||||
assertEquals(ReviewAction.Wait, reviewAction(hasData = false, running = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `report wins over running while an empty run waits`() {
|
||||
assertEquals(ReviewAction.Start, reviewAction(hasData = false, running = false))
|
||||
assertEquals(ReviewAction.Wait, reviewAction(hasData = false, running = true))
|
||||
assertEquals(ReviewAction.Report, reviewAction(hasData = true, running = false))
|
||||
assertEquals(ReviewAction.Report, reviewAction(hasData = true, running = true))
|
||||
}
|
||||
|
||||
private fun enabled(
|
||||
hasMoves: Boolean = true,
|
||||
gameOn: Boolean = false,
|
||||
sessionGame: Boolean = false,
|
||||
loaded: Boolean = true,
|
||||
hasData: Boolean = false,
|
||||
running: Boolean = false,
|
||||
) = reviewEnabled(hasMoves, gameOn, sessionGame, loaded, hasData, running)
|
||||
}
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class PlayersStateTest {
|
||||
@Test
|
||||
fun `two available colors always require an explicit choice`() {
|
||||
val blackMoreOften = player(white = 2, black = 3)
|
||||
val whiteMoreOften = player(white = 9, black = 1)
|
||||
|
||||
assertTrue(playerNeedsColorChoice(blackMoreOften))
|
||||
assertTrue(playerNeedsColorChoice(whiteMoreOften))
|
||||
assertNull(solePlayerColor(blackMoreOften))
|
||||
assertNull(solePlayerColor(whiteMoreOften))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `exactly one available color is the direct action`() {
|
||||
val whiteOnly = player(white = 2, black = 0)
|
||||
val blackOnly = player(white = 0, black = 1)
|
||||
|
||||
assertTrue(solePlayerColor(whiteOnly) == true)
|
||||
assertTrue(solePlayerColor(blackOnly) == false)
|
||||
assertFalse(playerNeedsColorChoice(whiteOnly))
|
||||
assertFalse(playerNeedsColorChoice(blackOnly))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `zero colors do not become an action`() {
|
||||
val empty = player(white = 0, black = 0)
|
||||
|
||||
assertNull(solePlayerColor(empty))
|
||||
assertFalse(playerNeedsColorChoice(empty))
|
||||
}
|
||||
|
||||
private fun player(white: Int, black: Int) = PlayerSummary(
|
||||
id = 1,
|
||||
name = "Player",
|
||||
total = 100,
|
||||
whiteGames = white,
|
||||
blackGames = black,
|
||||
)
|
||||
}
|
||||
|
|
@ -1,101 +0,0 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class PrepLineStateTest {
|
||||
@Test
|
||||
fun `back and forward follow the same continuation`() {
|
||||
val line = line("e2e4", "e7e5", "g1f3")
|
||||
|
||||
val back = line.back().back()
|
||||
assertEquals(1, back.cursor)
|
||||
assertEquals("e2e4", back.last?.uci)
|
||||
assertTrue(back.canForward)
|
||||
|
||||
val forward = back.forward()
|
||||
assertEquals("e7e5", forward.last?.uci)
|
||||
assertEquals("g1f3", forward.forward().last?.uci)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `long actions jump without an extra step`() {
|
||||
val line = line("e2e4", "e7e5", "g1f3")
|
||||
assertEquals(0, line.start().cursor)
|
||||
assertEquals(line.steps.size, line.start().end().cursor)
|
||||
assertEquals(line, line.end())
|
||||
assertEquals(line.start(), line.start().start())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a played line replaces only the temporary future`() {
|
||||
val original = line("e2e4", "e7e5", "g1f3").back().back()
|
||||
val prefix = original.steps.take(original.cursor)
|
||||
val replacement = step("c7c5", 2, "c5")
|
||||
val changed = original.replaceVisibleLine(prefix + replacement, replacement.node)
|
||||
|
||||
assertEquals(listOf("e2e4", "c7c5"), changed.moves)
|
||||
assertEquals(2, changed.cursor)
|
||||
assertFalse(changed.canForward)
|
||||
assertEquals(listOf("e2e4", "e7e5", "g1f3"), original.moves)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `opponent color puts the user at the bottom`() {
|
||||
assertTrue(prepBoardStartsFlipped(opponentWhite = true))
|
||||
assertFalse(prepBoardStartsFlipped(opponentWhite = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `side and number come from FEN rather than parity`() {
|
||||
val black = "8/8/8/8/8/8/4k3/4K3 b - - 0 0"
|
||||
assertEquals(false, prepWhiteToMove(black))
|
||||
assertEquals("0…Kd2", moveLabel(black, "Kd2"))
|
||||
assertEquals("12.Nf3", moveLabel(STANDARD_START.substringBeforeLast(" 1") + " 12", "Nf3"))
|
||||
assertNull(prepWhiteToMove("not a fen"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `frequency and WDL have separate denominators`() {
|
||||
val move = PrepContinuation("e7e5", "e5", games = 4, wins = 2, draws = 0, losses = 1, unknown = 1)
|
||||
assertEquals("40", frequencyPercent(move.games, 10))
|
||||
assertEquals(Triple("67", "0", "33"), outcomePercents(move))
|
||||
assertEquals("<1", frequencyPercent(1, 113))
|
||||
assertEquals("0", frequencyPercent(0, 113))
|
||||
assertEquals(Triple("—", "—", "—"), outcomePercents(move.copy(wins = 0, losses = 0)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `continuations are sorted by games then SAN without hiding rare moves`() {
|
||||
val position = PrepPosition(
|
||||
games = 5,
|
||||
continuations = listOf(
|
||||
PrepContinuation("g1f3", "Nf3", 1, 1, 0, 0),
|
||||
PrepContinuation("e2e4", "e4", 3, 1, 1, 1),
|
||||
PrepContinuation("d2d4", "d4", 1, 0, 1, 0),
|
||||
),
|
||||
)
|
||||
assertEquals(listOf("e4", "Nf3", "d4"), sortedContinuations(position).map { it.san })
|
||||
}
|
||||
|
||||
private fun line(vararg moves: String): PrepLineState = PrepLineState(
|
||||
startFen = STANDARD_START,
|
||||
rootFen = STANDARD_START,
|
||||
steps = moves.mapIndexed { i, uci -> step(uci, i + 1, uci.take(4)) },
|
||||
cursor = moves.size,
|
||||
)
|
||||
|
||||
private fun step(uci: String, node: Int, san: String) = PrepLineStep(
|
||||
node = node,
|
||||
uci = uci,
|
||||
san = san,
|
||||
moveNumber = (node + 1) / 2,
|
||||
white = node % 2 == 1,
|
||||
fen = STANDARD_START,
|
||||
from = uci.take(2),
|
||||
to = uci.substring(2, 4),
|
||||
)
|
||||
}
|
||||
|
|
@ -37,7 +37,6 @@ trainer.workspace = true
|
|||
play.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
thiserror.workspace = true
|
||||
online-games.workspace = true
|
||||
web-time.workspace = true
|
||||
sha2 = "0.11"
|
||||
|
|
|
|||
|
|
@ -1,12 +0,0 @@
|
|||
[Event "ChessPenguin: Queen's Gambit for White"]
|
||||
[White "Repertoire"]
|
||||
[Black "?"]
|
||||
[Result "*"]
|
||||
[ECO "D37"]
|
||||
|
||||
{Queen's Gambit for White: the Queen's Gambit Declined with 5.Bf4, plus answers to the Queen's Gambit Accepted and the Slav Defence.}
|
||||
1. d4 d5 2. c4 {White offers a pawn to deflect Black's d-pawn from the centre.}
|
||||
2... e6 (2... dxc4 {Queen's Gambit Accepted.} 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. dxc5 Bxc5 8. Qxd8+ Kxd8 {White keeps a small, risk-free edge in the endgame.})
|
||||
(2... c6 {Slav Defence.} 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. e3 e6 7. Bxc4 Bb4 8. O-O {White has a central space advantage and easy development.})
|
||||
3. Nc3 Nf6 4. Nf3 Be7 5. Bf4 {The modern main line: the bishop is active and safe from ...h6 and ...Ne4.}
|
||||
5... O-O 6. e3 c5 7. dxc5 Bxc5 8. a3 Nc6 9. Qc2 Qa5 10. Rd1 Re8 11. Nd2 {White plays against the isolated pawn that may appear after ...dxc4 or cxd5.} *
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
[Event "ChessPenguin: Ферзевый гамбит за белых"]
|
||||
[White "Repertoire"]
|
||||
[Black "?"]
|
||||
[Result "*"]
|
||||
[ECO "D37"]
|
||||
|
||||
{Ферзевый гамбит за белых: отказанный ферзевый гамбит с 5.Bf4, а также ответы на принятый ферзевый гамбит и Славянскую защиту.}
|
||||
1. d4 d5 2. c4 {Белые предлагают пешку, чтобы отвлечь пешку d5 из центра.}
|
||||
2... e6 (2... dxc4 {Принятый ферзевый гамбит.} 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. dxc5 Bxc5 8. Qxd8+ Kxd8 {Белые сохраняют небольшой безрисковый перевес в эндшпиле.})
|
||||
(2... c6 {Славянская защита.} 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. e3 e6 7. Bxc4 Bb4 8. O-O {У белых перевес в пространстве в центре и удобное развитие.})
|
||||
3. Nc3 Nf6 4. Nf3 Be7 5. Bf4 {Современная основная система: слон активен и не попадает под ...h6 и ...Ne4.}
|
||||
5... O-O 6. e3 c5 7. dxc5 Bxc5 8. a3 Nc6 9. Qc2 Qa5 10. Rd1 Re8 11. Nd2 {Белые играют против изолированной пешки, которая может возникнуть после ...dxc4 или cxd5.} *
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
[Event "ChessPenguin: Sicilian Najdorf for Black"]
|
||||
[White "?"]
|
||||
[Black "Repertoire"]
|
||||
[Result "*"]
|
||||
[ECO "B90"]
|
||||
|
||||
{Sicilian Defence, Najdorf Variation for Black, with answers to 6.Be3, 6.Bg5 and the Alapin 2.c3.}
|
||||
1. e4 c5 2. Nf3 (2. c3 {Alapin Variation.} 2... Nf6 3. e5 Nd5 4. d4 cxd4 5. Nf3 Nc6 6. cxd4 d6 {Black attacks the e5 pawn at once.})
|
||||
2... d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 {The Najdorf: ...a6 controls b5 and prepares ...e5 or ...b5.}
|
||||
6. Be3 (6. Bg5 e6 7. f4 Be7 8. Qf3 Qc7 9. O-O-O Nbd7 {Black keeps the position solid and prepares ...b5.})
|
||||
6... e5 7. Nb3 Be6 8. f3 Be7 9. Qd2 O-O 10. O-O-O Nbd7 11. g4 b5 {English Attack: both sides race on opposite wings.} *
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
[Event "ChessPenguin: Сицилианская защита, вариант Найдорфа за чёрных"]
|
||||
[White "?"]
|
||||
[Black "Repertoire"]
|
||||
[Result "*"]
|
||||
[ECO "B90"]
|
||||
|
||||
{Сицилианская защита, вариант Найдорфа за чёрных: ответы на 6.Be3, 6.Bg5 и вариант Алапина 2.c3.}
|
||||
1. e4 c5 2. Nf3 (2. c3 {Вариант Алапина.} 2... Nf6 3. e5 Nd5 4. d4 cxd4 5. Nf3 Nc6 6. cxd4 d6 {Чёрные сразу атакуют пешку e5.})
|
||||
2... d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 {Вариант Найдорфа: ...a6 контролирует b5 и готовит ...e5 или ...b5.}
|
||||
6. Be3 (6. Bg5 e6 7. f4 Be7 8. Qf3 Qc7 9. O-O-O Nbd7 {Чёрные сохраняют прочную позицию и готовят ...b5.})
|
||||
6... e5 7. Nb3 Be6 8. f3 Be7 9. Qd2 O-O 10. O-O-O Nbd7 11. g4 b5 {Английская атака: обе стороны наступают на противоположных флангах.} *
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
[Event "ChessPenguin: Spanish Opening for White"]
|
||||
[White "Repertoire"]
|
||||
[Black "?"]
|
||||
[Result "*"]
|
||||
[ECO "C84"]
|
||||
|
||||
{Spanish Opening (Ruy Lopez) for White: the Closed main line, the Marshall Attack and the Berlin Defence.}
|
||||
1. e4 e5 2. Nf3 Nc6 3. Bb5 {The Spanish bishop pressures the knight that defends e5.}
|
||||
3... a6 (3... Nf6 {Berlin Defence.} 4. O-O Nxe4 5. d4 Nd6 6. Bxc6 dxc6 7. dxe5 Nf5
|
||||
8. Qxd8+ Kxd8 {The Berlin endgame: White has the healthier pawn majority.})
|
||||
4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 (7... O-O 8. c3 d5 {Marshall Attack.}
|
||||
9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 c6 12. d4 {White returns material later if needed, but keeps the extra pawn for now.})
|
||||
8. c3 O-O 9. h3 {Stops ...Bg4 and prepares d4.} 9... Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 {Chigorin Variation: the knight heads for f1 and g3.} *
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
[Event "ChessPenguin: Испанская партия за белых"]
|
||||
[White "Repertoire"]
|
||||
[Black "?"]
|
||||
[Result "*"]
|
||||
[ECO "C84"]
|
||||
|
||||
{Испанская партия за белых: закрытая основная система, атака Маршалла и Берлинская защита.}
|
||||
1. e4 e5 2. Nf3 Nc6 3. Bb5 {Испанский слон давит на коня, защищающего e5.}
|
||||
3... a6 (3... Nf6 {Берлинская защита.} 4. O-O Nxe4 5. d4 Nd6 6. Bxc6 dxc6 7. dxe5 Nf5
|
||||
8. Qxd8+ Kxd8 {Берлинский эндшпиль: у белых более здоровое пешечное большинство.})
|
||||
4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 (7... O-O 8. c3 d5 {Атака Маршалла.}
|
||||
9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 c6 12. d4 {Белые пока сохраняют лишнюю пешку, а при необходимости вернут материал позже.})
|
||||
8. c3 O-O 9. h3 {Не допускает ...Bg4 и готовит d4.} 9... Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 {Вариант Чигорина: конь идёт на f1 и g3.} *
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
[Event "ChessPenguin: Semi-Slav Triangle for Black"]
|
||||
[White "?"]
|
||||
[Black "Repertoire"]
|
||||
[Result "*"]
|
||||
[ECO "D47"]
|
||||
|
||||
{Semi-Slav (Triangle) for Black: the Meran main line, with answers to 5.Bg5, the Exchange Variation and the quiet 4.e3.}
|
||||
1. d4 d5 2. c4 c6 3. Nf3 e6 {The triangle c6-d5-e6 makes the centre very solid.}
|
||||
4. Nc3 (4. e3 Nf6 5. Bd3 Nbd7 6. O-O Bd6 7. Nbd2 O-O 8. e4 dxe4 9. Nxe4 Nxe4 10. Bxe4 e5 {Black frees the position with the central break.})
|
||||
(4. cxd5 exd5 5. Nc3 Nf6 6. Bg5 Be7 7. e3 Bf5 {Exchange Variation: the c8-bishop gets outside the pawn chain.})
|
||||
4... Nf6 5. e3 (5. Bg5 h6 6. Bh4 dxc4 7. e4 g5 8. Bg3 b5 {Moscow Variation: Black grabs the pawn and keeps it with ...b5.})
|
||||
5... Nbd7 6. Bd3 dxc4 7. Bxc4 b5 {The Meran: Black gains space on the queenside with tempo.}
|
||||
8. Bd3 Bb7 9. O-O a6 10. e4 c5 11. d5 Qc7 {Black attacks the centre and is ready to castle.} *
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
[Event "ChessPenguin: Полуславянская защита (треугольник) за чёрных"]
|
||||
[White "?"]
|
||||
[Black "Repertoire"]
|
||||
[Result "*"]
|
||||
[ECO "D47"]
|
||||
|
||||
{Полуславянская защита (треугольник) за чёрных: основная система Меран и ответы на 5.Bg5, разменный вариант и спокойное 4.e3.}
|
||||
1. d4 d5 2. c4 c6 3. Nf3 e6 {Треугольник c6-d5-e6 делает центр очень прочным.}
|
||||
4. Nc3 (4. e3 Nf6 5. Bd3 Nbd7 6. O-O Bd6 7. Nbd2 O-O 8. e4 dxe4 9. Nxe4 Nxe4 10. Bxe4 e5 {Чёрные освобождают игру центральным подрывом.})
|
||||
(4. cxd5 exd5 5. Nc3 Nf6 6. Bg5 Be7 7. e3 Bf5 {Разменный вариант: слон c8 выходит за пешечную цепь.})
|
||||
4... Nf6 5. e3 (5. Bg5 h6 6. Bh4 dxc4 7. e4 g5 8. Bg3 b5 {Московский вариант: чёрные берут пешку и удерживают её ходом ...b5.})
|
||||
5... Nbd7 6. Bd3 dxc4 7. Bxc4 b5 {Меран: чёрные с темпом захватывают пространство на ферзевом фланге.}
|
||||
8. Bd3 Bb7 9. O-O a6 10. e4 c5 11. d5 Qc7 {Чёрные атакуют центр и готовы рокироваться.} *
|
||||
|
|
@ -124,7 +124,6 @@ impl Card {
|
|||
circles: &[],
|
||||
badge: None,
|
||||
interactive: false,
|
||||
temporary_shapes: false,
|
||||
show_coords: false,
|
||||
theme: settings.board_theme.theme(),
|
||||
pieces: settings.piece_set,
|
||||
|
|
|
|||
|
|
@ -299,17 +299,6 @@ pub struct App {
|
|||
repertoire: Option<crate::repertoire_ui::RepertoireUi>,
|
||||
#[cfg(not(web))]
|
||||
toast_repertoire: Option<(trainer::repertoire::RepertoireId, String)>,
|
||||
/// The database a copy of chosen games made: the toast's «Open».
|
||||
toast_open_db: Option<PathBuf>,
|
||||
/// The search for great moves (task 27): its question, the list and conditions of
|
||||
/// the pass under way, and its summary.
|
||||
brilliant_start: Option<crate::brilliant_ui::StartDialog>,
|
||||
brilliant_pass: Option<crate::brilliant::PassMeta>,
|
||||
brilliant_summary: Option<crate::brilliant_ui::Summary>,
|
||||
/// A pass asked for while Stockfish 19 is fetched or checked: it starts after.
|
||||
brilliant_waiting: Option<crate::brilliant_ui::StartDialog>,
|
||||
/// The plies of the games the pass under way analyses, for its time left.
|
||||
brilliant_plies: std::collections::HashMap<u32, usize>,
|
||||
applied_dark: Option<bool>,
|
||||
debug: DebugStartup,
|
||||
}
|
||||
|
|
@ -380,9 +369,6 @@ struct DebugStartup {
|
|||
screenshot_delay: f64,
|
||||
screenshot_requested: bool,
|
||||
open_settings: bool,
|
||||
/// `CP_SETTINGS_CLICK=x,y`: one primary click in viewport points, after opening.
|
||||
#[cfg(all(debug_assertions, not(web)))]
|
||||
settings_click: Option<egui::Pos2>,
|
||||
/// `CP_OWN=new|chooser|data|save|delete`: that dialog of the own databases
|
||||
/// (own_db.rs) after a short delay; `delete` and `chooser` without a game: the
|
||||
/// record `CP_OPEN` (default 0) of the first database.
|
||||
|
|
@ -413,11 +399,6 @@ impl DebugStartup {
|
|||
.unwrap_or(4.0),
|
||||
screenshot_requested: false,
|
||||
open_settings: false,
|
||||
#[cfg(all(debug_assertions, not(web)))]
|
||||
settings_click: std::env::var("CP_SETTINGS_CLICK").ok().and_then(|coords| {
|
||||
let (x, y) = coords.split_once(',')?;
|
||||
Some(egui::pos2(x.parse().ok()?, y.parse().ok()?))
|
||||
}),
|
||||
own: std::env::var("CP_OWN").ok(),
|
||||
play: std::env::var("CP_PLAY").ok(),
|
||||
keys: std::env::var("CP_KEYS")
|
||||
|
|
@ -462,32 +443,10 @@ impl App {
|
|||
if let Ok(dark) = std::env::var("CP_DARK") {
|
||||
settings.dark_mode = dark != "0";
|
||||
}
|
||||
// Dev hook (screenshots, tests): `CP_HINT_RESET=1` shows the one-time hints anew.
|
||||
if std::env::var("CP_HINT_RESET").as_deref() == Ok("1") {
|
||||
settings.hints = Default::default();
|
||||
}
|
||||
}
|
||||
// Before the samples, which are named in this language.
|
||||
crate::i18n::set_lang(settings.language);
|
||||
crate::engine_download::clean_leftovers();
|
||||
// Temporary files of copies of chosen games left by a crash: in the folders of the
|
||||
// databases, away from the window's thread (a network drive may be slow).
|
||||
#[cfg(not(web))]
|
||||
{
|
||||
let mut dirs: Vec<PathBuf> = settings
|
||||
.databases
|
||||
.iter()
|
||||
.filter_map(|p| p.parent().map(|d| d.to_path_buf()))
|
||||
.collect();
|
||||
dirs.push(own_db::default_base_dir(
|
||||
settings.new_database_dir.as_deref(),
|
||||
));
|
||||
dirs.sort();
|
||||
dirs.dedup();
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("copy-leftovers".into())
|
||||
.spawn(move || crate::batch_copy::clean_orphans(&dirs));
|
||||
}
|
||||
let current = env!("CARGO_PKG_VERSION");
|
||||
#[cfg(not(web))]
|
||||
let updated_from = {
|
||||
|
|
@ -588,12 +547,6 @@ impl App {
|
|||
repertoire: None,
|
||||
#[cfg(not(web))]
|
||||
toast_repertoire: None,
|
||||
toast_open_db: None,
|
||||
brilliant_start: None,
|
||||
brilliant_pass: None,
|
||||
brilliant_summary: None,
|
||||
brilliant_waiting: None,
|
||||
brilliant_plies: std::collections::HashMap::new(),
|
||||
applied_dark: None,
|
||||
debug: DebugStartup::from_env(),
|
||||
}
|
||||
|
|
@ -987,18 +940,7 @@ impl App {
|
|||
g.debug_show_report();
|
||||
}
|
||||
if let Some(k) = std::env::var("CP_BEST").ok().and_then(|v| v.parse().ok()) {
|
||||
// `CP_BEST_DELAY=<ms>`: the line opens that long after the notation is first
|
||||
// drawn (`CP_BEST_EXIT_AFTER=<ms>`: and closes that long after it opened).
|
||||
let ms = |name| {
|
||||
std::env::var(name)
|
||||
.ok()
|
||||
.and_then(|v| v.parse::<u64>().ok())
|
||||
.map(|ms| ms as f64 / 1000.0)
|
||||
};
|
||||
match ms("CP_BEST_DELAY") {
|
||||
Some(delay) => g.debug_best_line_later(k, delay, ms("CP_BEST_EXIT_AFTER")),
|
||||
None => g.debug_best_line(k),
|
||||
}
|
||||
g.debug_best_line(k);
|
||||
}
|
||||
// CP_REVIEW=ask presses «Analyse», any other value starts the analysis.
|
||||
if let Ok(v) = std::env::var("CP_REVIEW") {
|
||||
|
|
@ -1298,7 +1240,6 @@ impl App {
|
|||
{
|
||||
self.toast_repertoire = None;
|
||||
}
|
||||
self.toast_open_db = None;
|
||||
self.toast = Some(Toast {
|
||||
text: msg.into(),
|
||||
until: ctx.input(|i| i.time) + secs,
|
||||
|
|
@ -1507,7 +1448,10 @@ impl App {
|
|||
/// The PGN text of record `index` of a database, as `current_pgn` would give it.
|
||||
fn record_pgn(&self, from: &std::path::Path, index: usize) -> Option<String> {
|
||||
let db = self.library.database(from)?;
|
||||
crate::batch_copy::record_text(&db, index)
|
||||
match db.as_pgn() {
|
||||
Some(pgn) if !pgn.repair_letters_enabled() => db.raw_text(index),
|
||||
_ => db.load_game(index).map(|p| p.game.to_pgn()),
|
||||
}
|
||||
}
|
||||
|
||||
fn append_current(&mut self, ctx: &egui::Context, target: PathBuf) {
|
||||
|
|
@ -1970,420 +1914,6 @@ impl App {
|
|||
self.own.new_base = Some(own_db::NewBaseDialog::new(dir, after));
|
||||
}
|
||||
|
||||
/// Why the engine cannot take the search for great moves now, if it cannot (one engine
|
||||
/// job in the program, task 27 §4.5).
|
||||
fn engine_job_busy(&self) -> Option<String> {
|
||||
if self.prep.as_ref().is_some_and(|p| p.running()) {
|
||||
return Some(
|
||||
tr("The engine is busy searching opening errors in a preparation: wait or stop it")
|
||||
.to_owned(),
|
||||
);
|
||||
}
|
||||
if let Some(g) = self.game.as_ref().filter(|g| g.review_running()) {
|
||||
return Some(trf(
|
||||
"The engine is busy reviewing {game}",
|
||||
&[("game", &g.title())],
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// While the search for great moves runs, what cannot start says why.
|
||||
fn pass_busy(&self) -> Option<String> {
|
||||
let job = self.library.pass.as_ref()?;
|
||||
Some(trf(
|
||||
"Searching for great moves in «{db}»: {i} of {n}. Stop it in the library",
|
||||
&[
|
||||
("db", &own_db::base_name(&job.source)),
|
||||
("i", &job.done()),
|
||||
("n", &job.records.len()),
|
||||
],
|
||||
))
|
||||
}
|
||||
|
||||
/// «!! Find great moves»: the question first (or the summary, when every game is
|
||||
/// analysed already).
|
||||
fn ask_great_moves(
|
||||
&mut self,
|
||||
ctx: &egui::Context,
|
||||
path: PathBuf,
|
||||
records: Vec<u32>,
|
||||
filter: chess_import::chessbase::base::Filter,
|
||||
about: String,
|
||||
selected: Option<crate::brilliant::SelectedGames>,
|
||||
) {
|
||||
if self.library.pass.is_some() {
|
||||
return;
|
||||
}
|
||||
if let Some(why) = self.engine_job_busy() {
|
||||
self.toast(ctx, why);
|
||||
return;
|
||||
}
|
||||
let (Some(db), Some(cache)) = (self.library.database(&path), crate::review::cache_dir())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let index = self.library.marks(&path);
|
||||
let mut dialog = crate::brilliant_ui::StartDialog::new(
|
||||
ctx, path, db, records, filter, about, selected, cache, index,
|
||||
);
|
||||
// `CP_BRILLIANT_RUN=1`: no question.
|
||||
if std::env::var_os("CP_BRILLIANT_RUN").is_some() {
|
||||
let cancel = std::sync::atomic::AtomicBool::new(false);
|
||||
if let (Some(db), Some(cache)) = (
|
||||
self.library.database(&dialog.source),
|
||||
crate::review::cache_dir(),
|
||||
) {
|
||||
let index = self.library.marks(&dialog.source);
|
||||
dialog.counted = Some(crate::brilliant_ui::count(
|
||||
&db,
|
||||
&dialog.records,
|
||||
&dialog.filter,
|
||||
&cache,
|
||||
&index,
|
||||
&cancel,
|
||||
));
|
||||
}
|
||||
self.start_great_moves(ctx, dialog);
|
||||
return;
|
||||
}
|
||||
self.brilliant_start = Some(dialog);
|
||||
}
|
||||
|
||||
/// Starts the pass of `dialog` over its games not analysed yet (a browser has none:
|
||||
/// `CAPS.great_moves`).
|
||||
#[cfg(web)]
|
||||
fn start_great_moves(
|
||||
&mut self,
|
||||
_ctx: &egui::Context,
|
||||
_dialog: crate::brilliant_ui::StartDialog,
|
||||
) {
|
||||
}
|
||||
|
||||
/// Starts the pass of `dialog` over its games not analysed yet.
|
||||
#[cfg(not(web))]
|
||||
fn start_great_moves(&mut self, ctx: &egui::Context, dialog: crate::brilliant_ui::StartDialog) {
|
||||
let mut dialog = dialog;
|
||||
let Some(counted) = dialog.counted.take() else {
|
||||
return;
|
||||
};
|
||||
let Some(crate::engines::EngineLocation::Program(engine)) = crate::review_engine::engine()
|
||||
else {
|
||||
// The offer of «Analyse game»: download Stockfish 19 (or check the user's);
|
||||
// the pass starts after it.
|
||||
dialog.counted = Some(counted);
|
||||
self.brilliant_waiting = Some(dialog);
|
||||
self.need_review_engine(ctx, crate::engine_offer::Pending::GreatMoves);
|
||||
return;
|
||||
};
|
||||
let (Some(db), Some(cache)) = (
|
||||
self.library.database(&dialog.source),
|
||||
crate::review::cache_dir(),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
// One engine job: the live analysis stops.
|
||||
if self.analysis.is_on() {
|
||||
self.analysis.stop();
|
||||
self.live_paused = false;
|
||||
}
|
||||
let path = engine.clone();
|
||||
let engine = crate::brilliant::Engine {
|
||||
config: crate::review::engine_config(&engine),
|
||||
settings: game_review::JobSettings::new(crate::review::processes(), None),
|
||||
fits: Box::new(move |name| crate::review_engine::name_fits(&path, name)),
|
||||
pause: if std::env::var_os("CP_BRILLIANT_SLOW").is_some() {
|
||||
std::time::Duration::from_millis(1500)
|
||||
} else {
|
||||
std::time::Duration::ZERO
|
||||
},
|
||||
};
|
||||
let index = self.library.marks(&dialog.source);
|
||||
// The list in the table's order: the analysed ones are taken first (at once).
|
||||
let mut list = counted.reviewed.clone();
|
||||
list.extend(&counted.left);
|
||||
self.brilliant_plies = counted
|
||||
.left
|
||||
.iter()
|
||||
.copied()
|
||||
.zip(counted.plies_left.iter().copied())
|
||||
.collect();
|
||||
let order: std::collections::HashMap<u32, usize> = dialog
|
||||
.records
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, r)| (*r, i))
|
||||
.collect();
|
||||
list.sort_by_key(|r| order.get(r).copied().unwrap_or(usize::MAX));
|
||||
match crate::brilliant::PassJob::start(
|
||||
ctx,
|
||||
dialog.source.clone(),
|
||||
db,
|
||||
list,
|
||||
dialog.filter.clone(),
|
||||
dialog.selected,
|
||||
index,
|
||||
cache,
|
||||
engine,
|
||||
) {
|
||||
Ok(job) => {
|
||||
self.library.set_pass_error(&dialog.source, None);
|
||||
self.library.pass = Some(job);
|
||||
self.brilliant_pass = Some((
|
||||
dialog.filter.clone(),
|
||||
dialog.about.clone(),
|
||||
dialog.selected,
|
||||
counted.skipped,
|
||||
));
|
||||
}
|
||||
Err(e) => self.toast(ctx, e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The summary of `records` of `source`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn great_moves_summary(
|
||||
&mut self,
|
||||
source: &std::path::Path,
|
||||
records: &[u32],
|
||||
sides: &crate::brilliant::Sides,
|
||||
filter: &chess_import::chessbase::base::Filter,
|
||||
about: String,
|
||||
selected: Option<crate::brilliant::SelectedGames>,
|
||||
stopped: Option<(usize, usize)>,
|
||||
skipped: Vec<(u32, crate::brilliant::Skip)>,
|
||||
) {
|
||||
let Some(db) = self.library.database(source) else {
|
||||
return;
|
||||
};
|
||||
let index = self.library.marks(source);
|
||||
let Ok(index) = index.lock() else {
|
||||
return;
|
||||
};
|
||||
self.brilliant_summary = Some(crate::brilliant_ui::Summary::new(
|
||||
source, &db, &index, records, sides, filter, about, selected, stopped, skipped,
|
||||
));
|
||||
}
|
||||
|
||||
/// Every frame: the pass's state in the conditions lines, its end, the question and
|
||||
/// the summary; and the engine taken by the pass for everything else.
|
||||
fn great_moves_frame(&mut self, ctx: &egui::Context) {
|
||||
let busy = self.engine_job_busy();
|
||||
self.library.set_engine_busy(busy);
|
||||
let pass_busy = self.pass_busy();
|
||||
if let Some(p) = self.prep.as_mut() {
|
||||
p.engine_blocked = pass_busy;
|
||||
}
|
||||
let plies = &self.brilliant_plies;
|
||||
let estimate = |rest: &[u32]| {
|
||||
crate::brilliant::estimate_secs(
|
||||
rest.iter().filter_map(|r| plies.get(r).copied()),
|
||||
crate::review::processes(),
|
||||
)
|
||||
};
|
||||
self.library.show_pass(estimate);
|
||||
// `CP_BRILLIANT_STOP_AFTER=<ms>`: «Stop» pressed that long after the start.
|
||||
if let Some(ms) = std::env::var("CP_BRILLIANT_STOP_AFTER")
|
||||
.ok()
|
||||
.and_then(|ms| ms.parse::<u64>().ok())
|
||||
&& let Some(job) = self.library.pass.as_mut()
|
||||
&& !job.stopping
|
||||
&& job.started.elapsed() >= std::time::Duration::from_millis(ms)
|
||||
{
|
||||
job.stop();
|
||||
}
|
||||
if let Some(job) = self.library.pass.as_ref()
|
||||
&& let Some((end, sides)) = job.poll()
|
||||
{
|
||||
let job = self.library.pass.take().expect("pass");
|
||||
let (filter, about, selected, mut skipped) =
|
||||
self.brilliant_pass.take().unwrap_or_default();
|
||||
skipped.extend(end.skipped.iter().copied());
|
||||
skipped.sort_unstable_by_key(|(r, _)| *r);
|
||||
skipped.dedup();
|
||||
let reviewed = end.reviewed.len();
|
||||
let total = job.records.len();
|
||||
match &end.outcome {
|
||||
crate::brilliant::Outcome::Finished => self.great_moves_summary(
|
||||
&job.source,
|
||||
&job.records,
|
||||
&sides,
|
||||
&filter,
|
||||
about,
|
||||
selected,
|
||||
None,
|
||||
skipped,
|
||||
),
|
||||
crate::brilliant::Outcome::Stopped if reviewed == 0 => {
|
||||
self.toast(ctx, tr("Search stopped: no game was reviewed"));
|
||||
}
|
||||
crate::brilliant::Outcome::Stopped => self.great_moves_summary(
|
||||
&job.source,
|
||||
&job.records,
|
||||
&sides,
|
||||
&filter,
|
||||
about,
|
||||
selected,
|
||||
Some((reviewed, total)),
|
||||
skipped,
|
||||
),
|
||||
crate::brilliant::Outcome::EngineFailed(why) => {
|
||||
let text = trf(
|
||||
"The engine failed: {reason}. {i} of {n} reviewed",
|
||||
&[("reason", why), ("i", &reviewed), ("n", &total)],
|
||||
);
|
||||
self.library.set_pass_error(&job.source, Some(text));
|
||||
}
|
||||
crate::brilliant::Outcome::SourceChanged => {
|
||||
let text = trf(
|
||||
"«{db}» changed; the search stopped. {i} of {n} reviewed",
|
||||
&[
|
||||
("db", &own_db::base_name(&job.source)),
|
||||
("i", &reviewed),
|
||||
("n", &total),
|
||||
],
|
||||
);
|
||||
self.library.set_pass_error(&job.source, Some(text));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(dialog) = self.brilliant_start.as_mut()
|
||||
&& let Some(outcome) = dialog.show(ctx)
|
||||
{
|
||||
let dialog = self.brilliant_start.take().expect("dialog");
|
||||
match outcome {
|
||||
crate::brilliant_ui::StartOutcome::Cancel => {}
|
||||
crate::brilliant_ui::StartOutcome::Start => self.start_great_moves(ctx, dialog),
|
||||
crate::brilliant_ui::StartOutcome::Summary => {
|
||||
if let Some(c) = &dialog.counted {
|
||||
let reviewed = c.reviewed.clone();
|
||||
self.great_moves_summary(
|
||||
&dialog.source,
|
||||
&reviewed,
|
||||
&c.sides,
|
||||
&dialog.filter,
|
||||
dialog.about.clone(),
|
||||
dialog.selected,
|
||||
None,
|
||||
c.skipped.clone(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.game.is_none()
|
||||
&& let Some(summary) = self.brilliant_summary.as_mut()
|
||||
&& let Some(action) = summary.show(ctx)
|
||||
{
|
||||
let source = summary.source.clone();
|
||||
let summary_about = summary.about.clone();
|
||||
let summary_selected = summary.selected_games;
|
||||
use crate::brilliant_ui::SummaryAction;
|
||||
match action {
|
||||
SummaryAction::Close => self.brilliant_summary = None,
|
||||
SummaryAction::Select(record) => {
|
||||
self.library.choose_only(&source, record as usize);
|
||||
}
|
||||
SummaryAction::Sort => self.library.sort_by_marks(&source),
|
||||
SummaryAction::Continue { records, filter } => {
|
||||
self.brilliant_summary = None;
|
||||
let about = summary_about.clone();
|
||||
self.ask_great_moves(ctx, source, records, *filter, about, summary_selected);
|
||||
}
|
||||
SummaryAction::Open { record, ply } => {
|
||||
self.brilliant_summary = None;
|
||||
let at = self.library.database(&source).and_then(|db| {
|
||||
let game = db.load_game(record as usize)?.game;
|
||||
let node = *game.mainline().get(ply as usize)?;
|
||||
Some(game.node(node)?.position().clone())
|
||||
});
|
||||
self.library.choose_only(&source, record as usize);
|
||||
self.open_game(ctx, source, record as usize, at);
|
||||
if let Some(g) = self.game.as_mut() {
|
||||
g.show_report();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the copy of the chosen records of the new-database dialog into `path`
|
||||
/// (task 42): the file appears only when the copy is whole; the user stays in the
|
||||
/// source database.
|
||||
fn start_copy(&mut self, ctx: &egui::Context, path: PathBuf) -> Result<(), String> {
|
||||
let Some(own_db::AfterCreate::CopySelection {
|
||||
path: from,
|
||||
records,
|
||||
sort,
|
||||
ascending,
|
||||
..
|
||||
}) = self.own.new_base.as_ref().map(|d| d.after.clone())
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
if path.exists() {
|
||||
return Err(tr("A file with this name is already there.").to_owned());
|
||||
}
|
||||
if self
|
||||
.library
|
||||
.start_batch(ctx, &from, records, sort, ascending, path)
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(tr("Another copy is being written: wait until it finishes").to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
/// The end of a copy of chosen records: a toast, and the new database on the shelf.
|
||||
fn batch_ended(&mut self, ctx: &egui::Context, end: crate::library::BatchEnd) {
|
||||
use crate::library::BatchEnd;
|
||||
match end {
|
||||
BatchEnd::Done { target, report } => {
|
||||
let name = own_db::base_name(&target);
|
||||
// At the end of the shelf: the cards stay where they are; «Open» brings it
|
||||
// to the front.
|
||||
self.settings.add_database_last(&target);
|
||||
self.settings_dirty = true;
|
||||
self.toast_for(ctx, crate::batch_copy::summary(&name, &report), 8.0);
|
||||
self.toast_open_db = Some(target);
|
||||
}
|
||||
BatchEnd::Cancelled { target } => {
|
||||
let name = own_db::base_name(&target);
|
||||
self.toast(
|
||||
ctx,
|
||||
trf(
|
||||
"Copying cancelled: «{name}» was not created",
|
||||
&[("name", &name)],
|
||||
),
|
||||
);
|
||||
}
|
||||
BatchEnd::Failed {
|
||||
source,
|
||||
target,
|
||||
error,
|
||||
} => {
|
||||
let text = match error {
|
||||
crate::batch_copy::CopyError::SourceChanged => {
|
||||
self.library.clear_selection(&source);
|
||||
trf(
|
||||
"«{src}» changed while copying. Nothing was written",
|
||||
&[("src", &own_db::base_name(&source))],
|
||||
)
|
||||
}
|
||||
e => trf(
|
||||
"Could not write «{name}»: {reason}. Nothing was written",
|
||||
&[
|
||||
("name", &own_db::base_name(&target)),
|
||||
("reason", &e.reason()),
|
||||
],
|
||||
),
|
||||
};
|
||||
self.library.set_batch_error(&source, text.clone());
|
||||
self.toast_for(ctx, text, 8.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes the empty file and puts it on the shelf, selected and as the database the
|
||||
/// next game goes to.
|
||||
fn create_base(&mut self, ctx: &egui::Context, path: PathBuf) -> Result<(), String> {
|
||||
|
|
@ -2510,10 +2040,6 @@ impl App {
|
|||
/// Goes on with the game put aside: its record on the screen, the opponent started
|
||||
/// again with its moves, the clocks where they stopped.
|
||||
fn resume_aside(&mut self, ctx: &egui::Context) {
|
||||
if let Some(why) = engine_game_refused(self.pass_busy()) {
|
||||
self.toast(ctx, why);
|
||||
return;
|
||||
}
|
||||
let Some(aside) = self.put_aside.as_ref() else {
|
||||
return;
|
||||
};
|
||||
|
|
@ -2839,12 +2365,6 @@ impl App {
|
|||
/// A new game against Maia. Her model missing (a rematch, a game from a position):
|
||||
/// the dialog with the same choices, to download it.
|
||||
fn start_play(&mut self, ctx: &egui::Context, start: crate::play::Start) {
|
||||
// No game against the engine while the search for great moves runs (the owner's
|
||||
// decision, task 27).
|
||||
if let Some(why) = engine_game_refused(self.pass_busy()) {
|
||||
self.toast(ctx, why);
|
||||
return;
|
||||
}
|
||||
let Some(maia) = crate::play::engine_for(&start) else {
|
||||
self.play_dialog = Some(crate::play::Dialog::for_start(&self.settings, &start));
|
||||
return;
|
||||
|
|
@ -3140,13 +2660,7 @@ impl App {
|
|||
NewBaseOutcome::AddExisting(p) => (false, p),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let copy = matches!(
|
||||
self.own.new_base.as_ref().map(|d| &d.after),
|
||||
Some(own_db::AfterCreate::CopySelection { .. })
|
||||
);
|
||||
let made = if copy {
|
||||
self.start_copy(ctx, path.clone())
|
||||
} else if create {
|
||||
let made = if create {
|
||||
self.create_base(ctx, path.clone())
|
||||
} else {
|
||||
self.settings.touch_database(&path);
|
||||
|
|
@ -3178,8 +2692,6 @@ impl App {
|
|||
};
|
||||
self.wait_for(ctx, &path, step)
|
||||
}
|
||||
// Started by `start_copy`; its end is a toast.
|
||||
own_db::AfterCreate::CopySelection { .. } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -3569,13 +3081,6 @@ impl App {
|
|||
|
||||
fn toggle_engine(&mut self, ctx: &egui::Context) {
|
||||
self.live_paused = false;
|
||||
// The search for great moves has the engine (task 27 §4.5).
|
||||
if !self.analysis.is_on()
|
||||
&& let Some(why) = self.pass_busy()
|
||||
{
|
||||
self.toast(ctx, why);
|
||||
return;
|
||||
}
|
||||
if self.prep.as_ref().is_some_and(|p| p.running()) && !self.analysis.is_on() {
|
||||
self.toast(
|
||||
ctx,
|
||||
|
|
@ -3619,7 +3124,6 @@ impl App {
|
|||
Some(
|
||||
crate::engine_offer::Pending::GameAnalysis { .. }
|
||||
| crate::engine_offer::Pending::OpeningErrors { .. }
|
||||
| crate::engine_offer::Pending::GreatMoves
|
||||
)
|
||||
);
|
||||
if !own_search || self.settings.active_engine().is_none() {
|
||||
|
|
@ -3719,11 +3223,6 @@ impl App {
|
|||
}
|
||||
}
|
||||
}
|
||||
Some(crate::engine_offer::Pending::GreatMoves) => {
|
||||
if let Some(dialog) = self.brilliant_waiting.take() {
|
||||
self.start_great_moves(ctx, dialog);
|
||||
}
|
||||
}
|
||||
Some(crate::engine_offer::Pending::OpeningErrors { prep }) => {
|
||||
let actions = match self.prep.as_mut().filter(|p| p.serial == prep) {
|
||||
Some(p) => p.start_after_engine(ctx),
|
||||
|
|
@ -4274,24 +3773,6 @@ impl App {
|
|||
}
|
||||
|
||||
impl eframe::App for App {
|
||||
#[cfg(all(debug_assertions, not(web)))]
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, input: &mut egui::RawInput) {
|
||||
if self.settings_ui.open
|
||||
&& ctx.input(|i| i.time) >= 3.0
|
||||
&& let Some(pos) = self.debug.settings_click.take()
|
||||
{
|
||||
input.events.push(egui::Event::PointerMoved(pos));
|
||||
for pressed in [true, false] {
|
||||
input.events.push(egui::Event::PointerButton {
|
||||
pos,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: Modifiers::NONE,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
crate::san::set(self.settings.move_notation);
|
||||
// The window has shown its first frame: this graphics mode works.
|
||||
|
|
@ -4308,22 +3789,6 @@ impl eframe::App for App {
|
|||
});
|
||||
self.applied_dark = Some(self.settings.dark_mode);
|
||||
}
|
||||
// The opening panel's dragged width: given to the panel, saved when dragged anew.
|
||||
#[cfg(not(web))]
|
||||
let side_width = egui::Id::new(crate::opening_layout::SIDE_WIDTH_ID);
|
||||
#[cfg(not(web))]
|
||||
match ctx.data(|d| d.get_temp::<f32>(side_width)) {
|
||||
None => {
|
||||
if let Some(width) = self.settings.opening_side_width {
|
||||
ctx.data_mut(|d| d.insert_temp(side_width, width));
|
||||
}
|
||||
}
|
||||
Some(width) if self.settings.opening_side_width != Some(width) => {
|
||||
self.settings.opening_side_width = Some(width);
|
||||
let _ = self.settings.save();
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
// Quitting while the opening errors are searched: asked first (what was found
|
||||
// is kept either way).
|
||||
if ctx.input(|i| i.viewport().close_requested())
|
||||
|
|
@ -4470,7 +3935,6 @@ impl eframe::App for App {
|
|||
// dropped before the game is drawn (its header names the target).
|
||||
let _ = self.current_target();
|
||||
let shelf = self.shelf_dbs();
|
||||
let pass_busy = self.pass_busy();
|
||||
if repertoire_visible {
|
||||
#[cfg(not(web))]
|
||||
self.show_repertoire(ui, &ctx);
|
||||
|
|
@ -4481,9 +3945,7 @@ impl eframe::App for App {
|
|||
self.library.poll();
|
||||
self.reference.dbs = shelf;
|
||||
// The preparation's engine goes on under the game; no game analysis meanwhile.
|
||||
game.engine_busy =
|
||||
self.prep.as_ref().is_some_and(|p| p.running()) || self.library.pass.is_some();
|
||||
game.engine_busy_why = pass_busy.clone();
|
||||
game.engine_busy = self.prep.as_ref().is_some_and(|p| p.running());
|
||||
if let Some(p) = self.prep.as_mut() {
|
||||
p.poll_quietly(&ctx, &self.settings);
|
||||
}
|
||||
|
|
@ -4670,16 +4132,6 @@ impl eframe::App for App {
|
|||
self.settings_ui.tab = Tab::Translation;
|
||||
}
|
||||
GameAction::Toast(m) => self.toast(&ctx, m),
|
||||
GameAction::Reviewed { path, index, entry } => {
|
||||
let marks = self.library.marks(&path);
|
||||
if let Ok(mut marks) = marks.lock() {
|
||||
marks.set(index as u32, entry);
|
||||
if let Err(e) = marks.save() {
|
||||
eprintln!("marks: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
GameAction::HintsChanged => self.settings_dirty = true,
|
||||
GameAction::PauseLive => {
|
||||
if self.analysis.is_on() {
|
||||
self.analysis.stop();
|
||||
|
|
@ -4733,12 +4185,6 @@ impl eframe::App for App {
|
|||
LibraryAction::OpenGame { path, index, at } => {
|
||||
self.open_game(&ctx, path, index, at)
|
||||
}
|
||||
LibraryAction::OpenGameReport { path, index, at } => {
|
||||
self.open_game(&ctx, path, index, at);
|
||||
if let Some(g) = self.game.as_mut() {
|
||||
g.show_report();
|
||||
}
|
||||
}
|
||||
LibraryAction::Sound(s) => self.play(s),
|
||||
LibraryAction::CopyText(text, msg) => {
|
||||
ctx.copy_text(text);
|
||||
|
|
@ -4817,47 +4263,6 @@ impl eframe::App for App {
|
|||
self.own.then_close = None;
|
||||
self.open_chooser(&ctx, ChooserFor::Record { path, index });
|
||||
}
|
||||
LibraryAction::CopySelection {
|
||||
path,
|
||||
records,
|
||||
sort,
|
||||
ascending,
|
||||
hidden,
|
||||
} => {
|
||||
self.own.then_close = None;
|
||||
self.new_base_dialog(own_db::AfterCreate::CopySelection {
|
||||
path,
|
||||
records,
|
||||
sort,
|
||||
ascending,
|
||||
hidden,
|
||||
});
|
||||
// `CP_BATCH=new:<name>`: the dialog answered at once.
|
||||
if let Some(name) = std::env::var("CP_BATCH")
|
||||
.ok()
|
||||
.and_then(|b| b.strip_prefix("new:").map(str::to_owned))
|
||||
&& let Some(d) = self.own.new_base.as_mut()
|
||||
{
|
||||
d.name = name;
|
||||
let target = d.path();
|
||||
match self.start_copy(&ctx, target) {
|
||||
Ok(()) => self.own.new_base = None,
|
||||
Err(e) => {
|
||||
if let Some(d) = self.own.new_base.as_mut() {
|
||||
d.error = Some(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
LibraryAction::Notice(text) => self.toast(&ctx, text),
|
||||
LibraryAction::FindGreatMoves {
|
||||
path,
|
||||
records,
|
||||
filter,
|
||||
about,
|
||||
selected,
|
||||
} => self.ask_great_moves(&ctx, path, records, filter, about, selected),
|
||||
LibraryAction::EditGameData { path, index } => {
|
||||
self.open_game(&ctx, path, index, None);
|
||||
self.edit_game_data();
|
||||
|
|
@ -4985,11 +4390,6 @@ impl eframe::App for App {
|
|||
self.start_play(&ctx, start);
|
||||
}
|
||||
}
|
||||
// A copy of chosen games ends whatever is on the screen.
|
||||
self.great_moves_frame(&ctx);
|
||||
if let Some(end) = self.library.poll_batch(&ctx) {
|
||||
self.batch_ended(&ctx, end);
|
||||
}
|
||||
// Ctrl+Z on the library while the deleted game can still come back.
|
||||
if self.game.is_none()
|
||||
&& self.own.undo.is_some()
|
||||
|
|
@ -5002,7 +4402,6 @@ impl eframe::App for App {
|
|||
}
|
||||
|
||||
let mut undo_clicked = false;
|
||||
let mut open_copy: Option<PathBuf> = None;
|
||||
#[cfg(not(web))]
|
||||
let mut open_repertoire = None;
|
||||
if let Some(t) = &self.toast {
|
||||
|
|
@ -5018,11 +4417,10 @@ impl eframe::App for App {
|
|||
let (msg, undo) = (t.text.clone(), t.undo && self.own.undo.is_some());
|
||||
#[cfg(not(web))]
|
||||
let repertoire_link = self.toast_repertoire.clone();
|
||||
let open_db = self.toast_open_db.clone();
|
||||
#[cfg(not(web))]
|
||||
let has_action = undo || repertoire_link.is_some() || open_db.is_some();
|
||||
let has_action = undo || repertoire_link.is_some();
|
||||
#[cfg(web)]
|
||||
let has_action = undo || open_db.is_some();
|
||||
let has_action = undo;
|
||||
let area = egui::Area::new(egui::Id::new(TOAST))
|
||||
.anchor(egui::Align2::CENTER_BOTTOM, egui::vec2(0.0, -24.0))
|
||||
.order(egui::Order::Foreground)
|
||||
|
|
@ -5041,9 +4439,6 @@ impl eframe::App for App {
|
|||
if repertoire_link.is_some() && ui.button(tr("Open")).clicked() {
|
||||
open_repertoire = repertoire_link.clone();
|
||||
}
|
||||
if open_db.is_some() && ui.button(tr("Open")).clicked() {
|
||||
open_copy = open_db.clone();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -5061,13 +4456,6 @@ impl eframe::App for App {
|
|||
self.toast = None;
|
||||
self.undo_delete(&ctx);
|
||||
}
|
||||
if let Some(path) = open_copy {
|
||||
self.toast = None;
|
||||
self.toast_open_db = None;
|
||||
self.settings.touch_database(&path);
|
||||
self.settings_dirty = true;
|
||||
self.library.select_db(&path, &ctx);
|
||||
}
|
||||
#[cfg(not(web))]
|
||||
if let Some((id, title)) = open_repertoire {
|
||||
self.toast = None;
|
||||
|
|
@ -5088,10 +4476,6 @@ impl eframe::App for App {
|
|||
}
|
||||
|
||||
fn on_exit(&mut self) {
|
||||
self.library.stop_batch();
|
||||
if let Some(job) = self.library.pass.as_mut() {
|
||||
job.shutdown(std::time::Duration::from_secs(3));
|
||||
}
|
||||
self.analysis.stop();
|
||||
crate::review_engine::shutdown();
|
||||
if let Some(p) = self.prep.as_mut() {
|
||||
|
|
@ -5152,8 +4536,6 @@ fn still_waiting(
|
|||
Pending::GameAnalysis { game: g, .. } => Some(*g) == game,
|
||||
Pending::OpeningErrors { prep: p } => Some(*p) == prep,
|
||||
Pending::LiveAnalysis => false,
|
||||
// The app keeps its question (`brilliant_waiting`) until it starts.
|
||||
Pending::GreatMoves => true,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -5181,18 +4563,6 @@ fn sanitize(s: &str) -> String {
|
|||
.collect::<String>()
|
||||
}
|
||||
|
||||
/// Why a game against the engine (Maia, a rematch, the game put aside) may not start:
|
||||
/// the search for great moves has the engine (`pass`: its message while it runs).
|
||||
fn engine_game_refused(pass: Option<String>) -> Option<String> {
|
||||
pass.map(|why| {
|
||||
format!(
|
||||
"{} {}",
|
||||
tr("A game against the engine waits until the search for great moves ends."),
|
||||
why
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod waiting_tests {
|
||||
use super::{names_text, still_waiting};
|
||||
|
|
@ -5215,22 +4585,6 @@ mod waiting_tests {
|
|||
assert!(!still_waiting(&Pending::LiveAnalysis, Some(7), Some(3)));
|
||||
}
|
||||
|
||||
/// Every way to a game against the engine asks the same guard: refused while the
|
||||
/// search for great moves runs, allowed otherwise.
|
||||
#[test]
|
||||
fn a_game_against_the_engine_waits_for_the_search() {
|
||||
assert!(super::engine_game_refused(None).is_none());
|
||||
let why = super::engine_game_refused(Some("x".into())).unwrap();
|
||||
assert!(why.ends_with('x'));
|
||||
let src = include_str!("app.rs");
|
||||
for f in ["fn resume_aside(", "fn start_play("] {
|
||||
let body = &src[src.find(f).unwrap()..];
|
||||
let guard = body.find("engine_game_refused(self.pass_busy())").unwrap();
|
||||
let first_return = body.find("return").unwrap();
|
||||
assert!(guard < first_return + 40, "{f} checks the search first");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_in_messages_are_short() {
|
||||
let names: Vec<String> = ["a.pgn", "b.pgn", "c.pgn", "d.pgn"]
|
||||
|
|
|
|||
|
|
@ -131,11 +131,6 @@ impl PieceSet {
|
|||
format!("bytes://pieces/{}/{}.svg", self.name(), Self::index(piece))
|
||||
}
|
||||
|
||||
/// The piece's picture, to put in a widget.
|
||||
pub fn image(self, piece: Piece) -> egui::Image<'static> {
|
||||
egui::Image::new(self.uri(piece))
|
||||
}
|
||||
|
||||
pub fn paint(self, ui: &egui::Ui, piece: Piece, rect: Rect) {
|
||||
egui::Image::new(self.uri(piece)).paint_at(ui, rect);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,442 +0,0 @@
|
|||
//! Several records of a database copied into a new database (task 42,
|
||||
//! docs/design/tasks-42-43-2026-11-27.md): the records chosen in the table, a set of
|
||||
//! record numbers that keeps a bit per record, and the copy itself, written in the
|
||||
//! background into a temporary file beside the new one and published only when whole.
|
||||
//! The source database is only read.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::io::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
|
||||
use chess_core::pgn::store;
|
||||
use chess_import::Database;
|
||||
use chess_import::chessbase::base::SortKey;
|
||||
|
||||
use crate::i18n::{tr, trf};
|
||||
|
||||
/// Records chosen in a table: one bit per record number. Membership is one lookup, and
|
||||
/// choosing all the records of a list of millions is one pass over it.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Selection {
|
||||
words: Vec<u64>,
|
||||
count: usize,
|
||||
}
|
||||
|
||||
impl Selection {
|
||||
pub fn contains(&self, index: usize) -> bool {
|
||||
self.words
|
||||
.get(index / 64)
|
||||
.is_some_and(|w| w & (1 << (index % 64)) != 0)
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.count
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.count == 0
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, index: usize) {
|
||||
let word = index / 64;
|
||||
if word >= self.words.len() {
|
||||
self.words.resize(word + 1, 0);
|
||||
}
|
||||
let bit = 1 << (index % 64);
|
||||
if self.words[word] & bit == 0 {
|
||||
self.words[word] |= bit;
|
||||
self.count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, index: usize) {
|
||||
if let Some(w) = self.words.get_mut(index / 64) {
|
||||
let bit = 1 << (index % 64);
|
||||
if *w & bit != 0 {
|
||||
*w &= !bit;
|
||||
self.count -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn toggle(&mut self, index: usize) {
|
||||
if self.contains(index) {
|
||||
self.remove(index);
|
||||
} else {
|
||||
self.insert(index);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.words.clear();
|
||||
self.count = 0;
|
||||
}
|
||||
|
||||
/// Only `index` chosen.
|
||||
pub fn only(&mut self, index: usize) {
|
||||
self.clear();
|
||||
self.insert(index);
|
||||
}
|
||||
|
||||
/// Adds every record of `records` (a list of the table).
|
||||
pub fn extend(&mut self, records: &[u32]) {
|
||||
if let Some(&most) = records.iter().max() {
|
||||
let words = most as usize / 64 + 1;
|
||||
if words > self.words.len() {
|
||||
self.words.resize(words, 0);
|
||||
}
|
||||
}
|
||||
for &r in records {
|
||||
let (word, bit) = (r as usize / 64, 1u64 << (r % 64));
|
||||
if self.words[word] & bit == 0 {
|
||||
self.words[word] |= bit;
|
||||
self.count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The chosen records, in the order of their numbers.
|
||||
pub fn records(&self) -> Vec<u32> {
|
||||
let mut out = Vec::with_capacity(self.count);
|
||||
for (n, &w) in self.words.iter().enumerate() {
|
||||
let mut w = w;
|
||||
while w != 0 {
|
||||
let bit = w.trailing_zeros();
|
||||
out.push((n * 64) as u32 + bit);
|
||||
w &= w - 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The highest chosen record.
|
||||
pub fn last(&self) -> Option<usize> {
|
||||
let (n, w) = self
|
||||
.words
|
||||
.iter()
|
||||
.enumerate()
|
||||
.rev()
|
||||
.find(|(_, w)| **w != 0)?;
|
||||
Some(n * 64 + 63 - w.leading_zeros() as usize)
|
||||
}
|
||||
|
||||
/// Records from `len` on let go (a database with fewer records now).
|
||||
pub fn retain_below(&mut self, len: usize) {
|
||||
while let Some(last) = self.last().filter(|&l| l >= len) {
|
||||
self.remove(last);
|
||||
}
|
||||
}
|
||||
|
||||
/// How many of `records` are chosen.
|
||||
pub fn count_in(&self, records: &[u32]) -> usize {
|
||||
if self.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
records
|
||||
.iter()
|
||||
.filter(|&&r| self.contains(r as usize))
|
||||
.count()
|
||||
}
|
||||
}
|
||||
|
||||
/// The PGN text of record `index` as «Add to database» copies it: the record's own
|
||||
/// text when the file is PGN read without restoring letters, otherwise the game written
|
||||
/// anew (a ChessBase database has no PGN; restored letters are in the copy).
|
||||
pub fn record_text(db: &Database, index: usize) -> Option<String> {
|
||||
match db.as_pgn() {
|
||||
Some(pgn) if !pgn.repair_letters_enabled() => db.raw_text(index),
|
||||
_ => db.load_game(index).map(|p| p.game.to_pgn()),
|
||||
}
|
||||
}
|
||||
|
||||
/// What to copy: the chosen records (by number), the table's order and the new file.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CopyRequest {
|
||||
pub records: Vec<u32>,
|
||||
pub sort: SortKey,
|
||||
pub ascending: bool,
|
||||
pub target: PathBuf,
|
||||
/// A pause per record (`CP_BATCH_SLOW`): the progress can be seen and photographed.
|
||||
pub slow: bool,
|
||||
}
|
||||
|
||||
/// How a copy went.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct CopyReport {
|
||||
pub copied: usize,
|
||||
/// Record numbers (from 0) skipped as a copy of a record already copied: the same
|
||||
/// PGN text, white space aside.
|
||||
pub duplicates: Vec<usize>,
|
||||
/// Record numbers (from 0) that could not be read.
|
||||
pub unreadable: Vec<usize>,
|
||||
}
|
||||
|
||||
impl CopyReport {
|
||||
pub fn skipped(&self) -> usize {
|
||||
self.duplicates.len() + self.unreadable.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Why nothing was written.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum CopyError {
|
||||
/// A file of that name appeared meanwhile: it is not touched.
|
||||
#[error("a file with this name is already there")]
|
||||
Exists,
|
||||
/// The source file changed on disk: the record numbers no longer mean the same games.
|
||||
#[error("the source changed")]
|
||||
SourceChanged,
|
||||
#[error("{0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
impl CopyError {
|
||||
/// The reason in the user's words.
|
||||
pub fn reason(&self) -> String {
|
||||
match self {
|
||||
CopyError::Exists => tr("a file with this name is already there").to_owned(),
|
||||
CopyError::SourceChanged => tr("the source changed").to_owned(),
|
||||
CopyError::Io(e) => match e.kind() {
|
||||
std::io::ErrorKind::StorageFull => tr("no space left on the disk").to_owned(),
|
||||
std::io::ErrorKind::PermissionDenied => tr("no permission to write").to_owned(),
|
||||
_ => e.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The temporary file of a copy; removed unless published.
|
||||
struct Partial {
|
||||
path: PathBuf,
|
||||
published: bool,
|
||||
}
|
||||
|
||||
impl Drop for Partial {
|
||||
fn drop(&mut self) {
|
||||
if !self.published {
|
||||
let _ = std::fs::remove_file(&self.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The temporary file of a copy into `target`: `.<name>.part-<pid>-<random>`, the
|
||||
/// process that writes it in its name (`clean_orphans` knows from it whether its writer
|
||||
/// is gone).
|
||||
fn partial_path(target: &Path) -> PathBuf {
|
||||
let name = target
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
std::time::SystemTime::now().hash(&mut h);
|
||||
std::thread::current().id().hash(&mut h);
|
||||
target.hash(&mut h);
|
||||
target.with_file_name(format!(
|
||||
".{name}{PART}{}-{:016x}",
|
||||
std::process::id(),
|
||||
h.finish()
|
||||
))
|
||||
}
|
||||
|
||||
const PART: &str = ".part-";
|
||||
|
||||
/// Temporary files of copies whose process is gone (a crash, a power cut), in `dirs`:
|
||||
/// removed. Only names this program gives (`.<name>.pgn.part-<pid>-<hex>`) and only when
|
||||
/// no process `<pid>` runs; anything else is left alone.
|
||||
pub fn clean_orphans(dirs: &[PathBuf]) {
|
||||
for dir in dirs {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
if let Some(pid) = orphan_pid(&name)
|
||||
&& pid != std::process::id()
|
||||
&& !Path::new(&format!("/proc/{pid}")).exists()
|
||||
&& entry.file_type().is_ok_and(|t| t.is_file())
|
||||
{
|
||||
let _ = std::fs::remove_file(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The writer's process of a temporary copy file named so, if the name is one.
|
||||
fn orphan_pid(name: &str) -> Option<u32> {
|
||||
let rest = name.strip_prefix('.')?;
|
||||
let (stem, tail) = rest.rsplit_once(PART)?;
|
||||
if !stem.to_lowercase().ends_with(".pgn") {
|
||||
return None;
|
||||
}
|
||||
let (pid, hex) = tail.split_once('-')?;
|
||||
(hex.len() == 16 && hex.chars().all(|c| c.is_ascii_hexdigit()))
|
||||
.then(|| pid.parse().ok())
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// A record's PGN text with every run of white space as one space: what makes two
|
||||
/// records the same for a copy (the owner's rule: tags, moves, variations, comments and
|
||||
/// NAG all equal; line breaks and spaces aside).
|
||||
fn normalized(text: &str) -> String {
|
||||
text.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// 128 bits of a normalized record text: millions of copied records are told apart
|
||||
/// without keeping their texts; equal keys are compared again in full.
|
||||
fn key_of(normalized: &str) -> u128 {
|
||||
let half = |salt: u64| {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
salt.hash(&mut h);
|
||||
normalized.hash(&mut h);
|
||||
h.finish()
|
||||
};
|
||||
(u128::from(half(0x9e37_79b9_7f4a_7c15)) << 64) | u128::from(half(0x6a09_e667_f3bc_c909))
|
||||
}
|
||||
|
||||
/// Copies the records of `req` from `db` into the new file `req.target`, in the table's
|
||||
/// order (records of equal value by number). Each record has the bytes «Add to
|
||||
/// database» would append to it; a record whose text was already copied is skipped, a
|
||||
/// record that cannot be read too. Written into a temporary file beside the target and published by a hard
|
||||
/// link, which fails rather than replace a file of that name. `None`: cancelled, nothing
|
||||
/// is left on disk.
|
||||
pub fn copy_into_new(
|
||||
db: &Database,
|
||||
req: &CopyRequest,
|
||||
progress: &AtomicUsize,
|
||||
cancel: &AtomicBool,
|
||||
) -> Option<Result<CopyReport, CopyError>> {
|
||||
let mut order = req.records.clone();
|
||||
order.sort_unstable();
|
||||
db.sort_records(&mut order, req.sort, req.ascending);
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return None;
|
||||
}
|
||||
let partial = Partial {
|
||||
path: partial_path(&req.target),
|
||||
published: false,
|
||||
};
|
||||
let run = || -> Result<Option<CopyReport>, CopyError> {
|
||||
if let Some(dir) = req.target.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
if req.target.exists() {
|
||||
return Err(CopyError::Exists);
|
||||
}
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&partial.path)?;
|
||||
let mut out = std::io::BufWriter::new(file);
|
||||
let mut report = CopyReport::default();
|
||||
// Copied records by the key of their text; equal keys of different texts (all
|
||||
// but impossible) in `more`.
|
||||
let mut seen: HashMap<u128, u32> = HashMap::new();
|
||||
let mut more: Vec<u32> = Vec::new();
|
||||
for (n, &record) in order.iter().enumerate() {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return Ok(None);
|
||||
}
|
||||
if req.slow {
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
let index = record as usize;
|
||||
let text = db
|
||||
.load_game(index)
|
||||
.and_then(|parsed| Some((parsed, record_text(db, index)?)));
|
||||
match text {
|
||||
None => report.unreadable.push(index),
|
||||
Some((_, text)) => {
|
||||
let flat = normalized(&text);
|
||||
let key = key_of(&flat);
|
||||
let same = |other: u32| {
|
||||
record_text(db, other as usize).is_some_and(|t| normalized(&t) == flat)
|
||||
};
|
||||
let duplicate = match seen.get(&key) {
|
||||
None => {
|
||||
seen.insert(key, record);
|
||||
false
|
||||
}
|
||||
Some(&first) => {
|
||||
let dup = same(first) || more.iter().any(|&o| same(o));
|
||||
if !dup {
|
||||
more.push(record);
|
||||
}
|
||||
dup
|
||||
}
|
||||
};
|
||||
if duplicate {
|
||||
report.duplicates.push(index);
|
||||
} else {
|
||||
out.write_all(&store::record_for_new_file(&text))?;
|
||||
report.copied += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
progress.store(n + 1, Ordering::Relaxed);
|
||||
}
|
||||
let file = out.into_inner().map_err(|e| e.into_error())?;
|
||||
file.sync_all()?;
|
||||
if let Some(pgn) = db.as_pgn()
|
||||
&& pgn.source_changed().unwrap_or(true)
|
||||
{
|
||||
return Err(CopyError::SourceChanged);
|
||||
}
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return Ok(None);
|
||||
}
|
||||
match std::fs::hard_link(&partial.path, &req.target) {
|
||||
Ok(()) => Ok(Some(report)),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Err(CopyError::Exists),
|
||||
Err(e) => Err(e.into()),
|
||||
}
|
||||
};
|
||||
match run() {
|
||||
Ok(None) => None,
|
||||
Ok(Some(report)) => Some(Ok(report)),
|
||||
Err(e) => Some(Err(e)),
|
||||
}
|
||||
}
|
||||
|
||||
/// « (No. 3, 4 and 2 more)» for up to `most` record numbers, nothing for none.
|
||||
fn numbers(records: &[usize], most: usize) -> String {
|
||||
if records.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let mut list: Vec<String> = records
|
||||
.iter()
|
||||
.take(most)
|
||||
.map(|i| (i + 1).to_string())
|
||||
.collect();
|
||||
if records.len() > most {
|
||||
list.push(trf("and {n} more", &[("n", &(records.len() - most))]));
|
||||
}
|
||||
format!(" ({})", trf("No. {list}", &[("list", &list.join(", "))]))
|
||||
}
|
||||
|
||||
/// «Name: copied 3, skipped 1 — duplicates 1 (No. 9), unreadable 0».
|
||||
pub fn summary(name: &str, report: &CopyReport) -> String {
|
||||
if report.skipped() == 0 {
|
||||
return trf(
|
||||
"{name}: copied {n}, skipped {m}",
|
||||
&[("name", &name), ("n", &report.copied), ("m", &0)],
|
||||
);
|
||||
}
|
||||
trf(
|
||||
"{name}: copied {n}, skipped {m} — duplicates {d}{dl}, unreadable {u}{ul}",
|
||||
&[
|
||||
("name", &name),
|
||||
("n", &report.copied),
|
||||
("m", &report.skipped()),
|
||||
("d", &report.duplicates.len()),
|
||||
("dl", &numbers(&report.duplicates, 10)),
|
||||
("u", &report.unreadable.len()),
|
||||
("ul", &numbers(&report.unreadable, 5)),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "batch_copy_tests.rs"]
|
||||
mod tests;
|
||||
|
|
@ -1,554 +0,0 @@
|
|||
use std::sync::atomic::{AtomicBool, AtomicUsize};
|
||||
|
||||
use chess_core::PgnDatabase;
|
||||
use chess_core::pgn::store;
|
||||
|
||||
use super::*;
|
||||
|
||||
struct Dir(PathBuf);
|
||||
|
||||
impl Dir {
|
||||
fn new(name: &str) -> Dir {
|
||||
let path = std::env::temp_dir().join(format!("cp-batch-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
Dir(path)
|
||||
}
|
||||
|
||||
fn file(&self, name: &str, bytes: &[u8]) -> PathBuf {
|
||||
let path = self.0.join(name);
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
/// Files of the folder besides `keep` (a temporary file left behind shows here).
|
||||
fn others(&self, keep: &[&Path]) -> Vec<PathBuf> {
|
||||
std::fs::read_dir(&self.0)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().path())
|
||||
.filter(|p| !keep.contains(&p.as_path()))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Dir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn open(path: &Path) -> Database {
|
||||
chess_import::open(path, &mut |_| {}, &AtomicBool::new(false))
|
||||
.unwrap()
|
||||
.db
|
||||
}
|
||||
|
||||
/// Games with what a copy must keep: a start position with fullmove 0, variations three
|
||||
/// deep, comments at the root and after moves, NAG, arrows, a tag of its own, and the
|
||||
/// first game once more (a duplicate).
|
||||
const SOURCE: &str = r#"[Event "Club"]
|
||||
[Site "?"]
|
||||
[Date "2020.01.02"]
|
||||
[Round "1"]
|
||||
[White "Alpha"]
|
||||
[Black "Beta"]
|
||||
[Result "1-0"]
|
||||
[MyTag "kept"]
|
||||
|
||||
{A comment at the root} 1. e4 $1 {[%cal Ge2e4]} e5 (1... c5 2. Nf3 (2. c3 d5 (2... Nf6 3. e5)) d6) 2. Nf3 $14 Nc6 1-0
|
||||
|
||||
[Event "Study"]
|
||||
[Site "?"]
|
||||
[Date "2021.??.??"]
|
||||
[Round "?"]
|
||||
[White "Gamma"]
|
||||
[Black "Delta"]
|
||||
[Result "*"]
|
||||
[SetUp "1"]
|
||||
[FEN "4k3/8/8/8/8/8/4P3/4K3 w - - 0 0"]
|
||||
|
||||
1. e4 Kd7 {the king} 2. Kf2 *
|
||||
|
||||
[Event "Club"]
|
||||
[Site "?"]
|
||||
[Date "2019.05.05"]
|
||||
[Round "2"]
|
||||
[White "Beta"]
|
||||
[Black "Alpha"]
|
||||
[Result "0-1"]
|
||||
|
||||
1. d4 d5 2. c4 $2 dxc4 0-1
|
||||
|
||||
[Event "Club again"]
|
||||
[Site "?"]
|
||||
[Date "2020.01.02"]
|
||||
[Round "1"]
|
||||
[White "alpha"]
|
||||
[Black "BETA"]
|
||||
[Result "1-0"]
|
||||
|
||||
1. e4 e5 2. Nf3 Nc6 1-0
|
||||
|
||||
[Event "Club"]
|
||||
[Site "?"]
|
||||
[Date "2020.01.02"]
|
||||
[Round "1"]
|
||||
[White "Alpha"]
|
||||
[Black "Beta"]
|
||||
[Result "1-0"]
|
||||
[MyTag "kept"]
|
||||
|
||||
{A comment at the root} 1. e4 $1 {[%cal Ge2e4]}
|
||||
e5 (1... c5 2. Nf3 (2. c3 d5 (2... Nf6 3. e5)) d6) 2. Nf3 $14 Nc6 1-0
|
||||
"#;
|
||||
|
||||
fn request(records: &[u32], target: &Path) -> CopyRequest {
|
||||
CopyRequest {
|
||||
records: records.to_vec(),
|
||||
sort: SortKey::Number,
|
||||
ascending: true,
|
||||
target: target.to_path_buf(),
|
||||
slow: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn copy(db: &Database, req: &CopyRequest) -> Option<Result<CopyReport, CopyError>> {
|
||||
copy_into_new(db, req, &AtomicUsize::new(0), &AtomicBool::new(false))
|
||||
}
|
||||
|
||||
/// The new database as «Add to database» would make it: an empty file, then each record
|
||||
/// appended in turn, a game already there skipped.
|
||||
fn one_by_one(db: &Database, order: &[usize], target: &Path) {
|
||||
std::fs::write(target, b"").unwrap();
|
||||
let mut written: Vec<String> = Vec::new();
|
||||
for &i in order {
|
||||
let into = PgnDatabase::open(target, &mut |_| {}, &AtomicBool::new(false)).unwrap();
|
||||
let text = record_text(db, i).unwrap();
|
||||
if !written.contains(&normalized(&text)) {
|
||||
store::append(&into, &text).unwrap();
|
||||
written.push(normalized(&text));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_keeps_a_bit_per_record() {
|
||||
let mut s = Selection::default();
|
||||
assert!(s.is_empty() && !s.contains(5));
|
||||
s.insert(5);
|
||||
s.insert(5);
|
||||
s.insert(200);
|
||||
assert_eq!((s.len(), s.records()), (2, vec![5, 200]));
|
||||
s.toggle(5);
|
||||
s.toggle(7);
|
||||
assert_eq!(s.records(), vec![7, 200]);
|
||||
s.extend(&[1, 7, 300]);
|
||||
assert_eq!((s.len(), s.records()), (4, vec![1, 7, 200, 300]));
|
||||
assert_eq!(s.count_in(&[0, 1, 2, 300]), 2);
|
||||
s.remove(1000);
|
||||
s.remove(7);
|
||||
assert_eq!(s.len(), 3);
|
||||
assert_eq!(s.last(), Some(300));
|
||||
s.retain_below(201);
|
||||
assert_eq!(s.records(), vec![1, 200]);
|
||||
s.only(42);
|
||||
assert_eq!(s.records(), vec![42]);
|
||||
s.clear();
|
||||
assert!(s.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_has_the_bytes_of_adding_the_games_one_by_one() {
|
||||
let dir = Dir::new("same");
|
||||
let source = dir.file("source.pgn", SOURCE.as_bytes());
|
||||
let before = std::fs::read(&source).unwrap();
|
||||
let db = open(&source);
|
||||
assert_eq!(db.len(), 5);
|
||||
let target = dir.0.join("copy.pgn");
|
||||
let report = copy(&db, &request(&[3, 0, 4, 2, 1], &target))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
// Record 5 is record 1 again with other line breaks: skipped; record 4 is the same
|
||||
// game with other tags: copied.
|
||||
assert_eq!(
|
||||
report,
|
||||
CopyReport {
|
||||
copied: 4,
|
||||
duplicates: vec![4],
|
||||
unreadable: Vec::new()
|
||||
}
|
||||
);
|
||||
let expected = dir.0.join("expected.pgn");
|
||||
one_by_one(&db, &[0, 1, 2, 3, 4], &expected);
|
||||
assert_eq!(
|
||||
std::fs::read(&target).unwrap(),
|
||||
std::fs::read(&expected).unwrap()
|
||||
);
|
||||
// The source is only read; no temporary file is left.
|
||||
assert_eq!(std::fs::read(&source).unwrap(), before);
|
||||
assert!(dir.others(&[&source, &target, &expected]).is_empty());
|
||||
// Every game whole: tags, start position, variations, comments, NAG, arrows.
|
||||
let copied = open(&target);
|
||||
for (i, j) in [(0, 0), (1, 1), (2, 2)] {
|
||||
assert_eq!(
|
||||
copied.load_game(j).unwrap().game.to_pgn(),
|
||||
db.load_game(i).unwrap().game.to_pgn()
|
||||
);
|
||||
}
|
||||
let text = std::fs::read_to_string(&target).unwrap();
|
||||
for kept in [
|
||||
"[MyTag \"kept\"]",
|
||||
"{A comment at the root}",
|
||||
"$1",
|
||||
"[%cal Ge2e4]",
|
||||
"(2... Nf6 3. e5)",
|
||||
"4k3/8/8/8/8/8/4P3/4K3 w - - 0 0",
|
||||
] {
|
||||
assert!(text.contains(kept), "{kept}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The owner's example: in Dvoretsky's endgame manual records 719 and 728 are one game
|
||||
/// with other comments; both are copied (the user's file, read only, when it is there).
|
||||
#[test]
|
||||
fn records_with_other_comments_are_both_copied() {
|
||||
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../pgnFilesforExample/Дворецкий. Учебник жндшпиля.pgn");
|
||||
if !path.exists() {
|
||||
return;
|
||||
}
|
||||
let db = open(&path);
|
||||
let dir = Dir::new("dvoretsky");
|
||||
let target = dir.0.join("copy.pgn");
|
||||
let report = copy(&db, &request(&[718, 727], &target)).unwrap().unwrap();
|
||||
assert_eq!((report.copied, report.duplicates.len()), (2, 0));
|
||||
// The same record twice in a source: the second is skipped.
|
||||
let one = record_text(&db, 718).unwrap();
|
||||
let source = dir.file("twice.pgn", format!("{one}\n\n{one}\n").as_bytes());
|
||||
let twice = open(&source);
|
||||
let target = dir.0.join("twice-copy.pgn");
|
||||
let report = copy(&twice, &request(&[0, 1], &target)).unwrap().unwrap();
|
||||
assert_eq!((report.copied, report.duplicates), (1, vec![1]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_summary_names_the_skipped_records() {
|
||||
let report = CopyReport {
|
||||
copied: 5,
|
||||
duplicates: (0..12).collect(),
|
||||
unreadable: vec![39],
|
||||
};
|
||||
assert_eq!(
|
||||
summary("Pick", &report),
|
||||
"Pick: copied 5, skipped 13 — duplicates 12 (No. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, and 2 more), unreadable 1 (No. 40)"
|
||||
);
|
||||
let clean = CopyReport {
|
||||
copied: 3,
|
||||
..CopyReport::default()
|
||||
};
|
||||
assert_eq!(summary("Pick", &clean), "Pick: copied 3, skipped 0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_orphans_of_this_program_are_removed() {
|
||||
let dir = Dir::new("orphans");
|
||||
let mine_live = format!(".a.pgn.part-{}-0123456789abcdef", std::process::id());
|
||||
// No process has a number that high on Linux (pid_max is at most 4194304).
|
||||
let dead = ".a.pgn.part-999999999-0123456789abcdef";
|
||||
let others = [
|
||||
".a.pgn.part-999999999",
|
||||
".a.txt.part-999999999-0123456789abcdef",
|
||||
"a.pgn.part-999999999-0123456789abcdef",
|
||||
".a.pgn.part-999999999-xyz",
|
||||
];
|
||||
for name in [mine_live.as_str(), dead].iter().chain(others.iter()) {
|
||||
dir.file(name, b"x");
|
||||
}
|
||||
clean_orphans(std::slice::from_ref(&dir.0));
|
||||
assert!(!dir.0.join(dead).exists());
|
||||
assert!(dir.0.join(&mine_live).exists());
|
||||
for name in others {
|
||||
assert!(dir.0.join(name).exists(), "{name}");
|
||||
}
|
||||
// Each copy has a name of its own.
|
||||
let target = dir.0.join("t.pgn");
|
||||
assert_ne!(partial_path(&target), partial_path(&target));
|
||||
let name = partial_path(&target);
|
||||
assert!(orphan_pid(&name.file_name().unwrap().to_string_lossy()).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_follows_the_tables_order() {
|
||||
let dir = Dir::new("order");
|
||||
let source = dir.file("source.pgn", SOURCE.as_bytes());
|
||||
let db = open(&source);
|
||||
let target = dir.0.join("copy.pgn");
|
||||
let req = CopyRequest {
|
||||
sort: SortKey::White,
|
||||
ascending: false,
|
||||
..request(&[0, 1, 2], &target)
|
||||
};
|
||||
copy(&db, &req).unwrap().unwrap();
|
||||
let mut table = vec![0, 1, 2];
|
||||
db.sort_records(&mut table, SortKey::White, false);
|
||||
let whites: Vec<String> = (0..3)
|
||||
.map(|i| {
|
||||
open(&target)
|
||||
.load_game(i)
|
||||
.unwrap()
|
||||
.game
|
||||
.tag("White")
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
})
|
||||
.collect();
|
||||
let wanted: Vec<String> = table
|
||||
.iter()
|
||||
.map(|&i| {
|
||||
db.load_game(i as usize)
|
||||
.unwrap()
|
||||
.game
|
||||
.tag("White")
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(whites, wanted);
|
||||
assert_eq!(whites, ["Gamma", "Beta", "Alpha"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_copy_leaves_nothing() {
|
||||
let dir = Dir::new("cancel");
|
||||
let source = dir.file("source.pgn", SOURCE.as_bytes());
|
||||
let db = open(&source);
|
||||
let target = dir.0.join("copy.pgn");
|
||||
let cancel = AtomicBool::new(true);
|
||||
let got = copy_into_new(
|
||||
&db,
|
||||
&request(&[0, 1], &target),
|
||||
&AtomicUsize::new(0),
|
||||
&cancel,
|
||||
);
|
||||
assert!(got.is_none());
|
||||
assert!(!target.exists());
|
||||
assert!(dir.others(&[&source]).is_empty());
|
||||
|
||||
// Cancelled while writing (another thread, a slow copy).
|
||||
let cancel = std::sync::Arc::new(AtomicBool::new(false));
|
||||
let progress = std::sync::Arc::new(AtomicUsize::new(0));
|
||||
let (c, p) = (cancel.clone(), progress.clone());
|
||||
let req = CopyRequest {
|
||||
slow: true,
|
||||
..request(&[0, 1, 2, 3], &target)
|
||||
};
|
||||
let worker = std::thread::spawn(move || copy_into_new(&db, &req, &p, &c));
|
||||
while progress.load(std::sync::atomic::Ordering::Relaxed) == 0 {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
cancel.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
assert!(worker.join().unwrap().is_none());
|
||||
assert!(!target.exists());
|
||||
assert!(dir.others(&[&source]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_never_replaces_a_file() {
|
||||
let dir = Dir::new("exists");
|
||||
let source = dir.file("source.pgn", SOURCE.as_bytes());
|
||||
let db = open(&source);
|
||||
let target = dir.file("copy.pgn", b"mine");
|
||||
let got = copy(&db, &request(&[0], &target)).unwrap();
|
||||
assert!(matches!(got, Err(CopyError::Exists)));
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"mine");
|
||||
assert!(dir.others(&[&source, &target]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_source_changed_while_copying_writes_nothing() {
|
||||
let dir = Dir::new("changed");
|
||||
let source = dir.file("source.pgn", SOURCE.as_bytes());
|
||||
let db = open(&source);
|
||||
std::fs::write(&source, format!("{SOURCE}\n[White \"x\"]\n\n1. e4 *\n")).unwrap();
|
||||
let target = dir.0.join("copy.pgn");
|
||||
let got = copy(&db, &request(&[0], &target)).unwrap();
|
||||
assert!(matches!(got, Err(CopyError::SourceChanged)));
|
||||
assert!(!target.exists());
|
||||
assert!(dir.others(&[&source]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legacy_source_is_copied_as_its_text_reads() {
|
||||
let dir = Dir::new("legacy");
|
||||
// windows-1252: «é», «ü» and «—» are one byte each.
|
||||
let mut bytes = b"[Event \"Caf\xe9\"]\n[White \"M\xfcller\"]\n[Black \"Ren\xe9\"]\n[Result \"1-0\"]\n\n{Le d\xe9but \x97 bien} 1. e4 e5 1-0\n".to_vec();
|
||||
bytes.extend_from_slice(b"\n[White \"B\"]\n[Black \"C\"]\n[Result \"*\"]\n\n1. d4 *\n");
|
||||
let source = dir.file("legacy.pgn", &bytes);
|
||||
let db = open(&source);
|
||||
let target = dir.0.join("copy.pgn");
|
||||
copy(&db, &request(&[0, 1], &target)).unwrap().unwrap();
|
||||
let expected = dir.0.join("expected.pgn");
|
||||
one_by_one(&db, &[0, 1], &expected);
|
||||
assert_eq!(
|
||||
std::fs::read(&target).unwrap(),
|
||||
std::fs::read(&expected).unwrap()
|
||||
);
|
||||
let copied = open(&target);
|
||||
let (a, b) = (
|
||||
db.load_game(0).unwrap().game,
|
||||
copied.load_game(0).unwrap().game,
|
||||
);
|
||||
assert_eq!(a.tag("White"), b.tag("White"));
|
||||
assert_eq!(a.to_pgn(), b.to_pgn());
|
||||
assert!(String::from_utf8(std::fs::read(&target).unwrap()).is_ok());
|
||||
assert_eq!(std::fs::read(&source).unwrap(), bytes);
|
||||
}
|
||||
|
||||
/// windows-1251 bytes of `text` (ASCII and the Russian letters without «ё»).
|
||||
fn cp1251(text: &str) -> Vec<u8> {
|
||||
text.chars()
|
||||
.map(|c| match c {
|
||||
'А'..='я' => (c as u32 - 'А' as u32 + 0xC0) as u8,
|
||||
c => c as u8,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_source_with_restored_letters_is_copied_as_adding_one_game() {
|
||||
let dir = Dir::new("repair");
|
||||
// `~~`, `o^` and `><` stand for ч, ю and Ч in old Russian files; restored on reading
|
||||
// (a copy has the restored text, as a game added alone; tasks.md, task 42, Д1).
|
||||
let comment = "{Клo^~~евые поля, ><ерные играo^т, ~~ерные} ".repeat(12);
|
||||
let text = format!(
|
||||
"[White \"Петров\"]\n[Black \"Иванов\"]\n[Result \"*\"]\n\n{comment}1. e4 *\n\n[White \"Б\"]\n[Black \"В\"]\n[Result \"*\"]\n\n{{~~ерные}} 1. d4 *\n"
|
||||
);
|
||||
let bytes = cp1251(&text);
|
||||
let source = dir.file("repair.pgn", &bytes);
|
||||
let db = open(&source);
|
||||
assert!(db.as_pgn().is_some_and(|p| p.repair_letters_enabled()));
|
||||
let target = dir.0.join("copy.pgn");
|
||||
copy(&db, &request(&[0, 1], &target)).unwrap().unwrap();
|
||||
let expected = dir.0.join("expected.pgn");
|
||||
one_by_one(&db, &[0, 1], &expected);
|
||||
assert_eq!(
|
||||
std::fs::read(&target).unwrap(),
|
||||
std::fs::read(&expected).unwrap()
|
||||
);
|
||||
assert!(std::fs::read_to_string(&target).unwrap().contains("ерные"));
|
||||
assert_eq!(std::fs::read(&source).unwrap(), bytes);
|
||||
}
|
||||
|
||||
/// Copying 1000 games and choosing 4 million rows: timed (`cargo test -- --ignored
|
||||
/// --nocapture`, release for figures).
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn timing() {
|
||||
let dir = Dir::new("timing");
|
||||
let mut text = String::new();
|
||||
for i in 0..1000 {
|
||||
text.push_str(&format!(
|
||||
"[Event \"E\"]\n[White \"W{i}\"]\n[Black \"B{i}\"]\n[Result \"*\"]\n\n1. e4 e5 2. Nf3 (2. f4 exf4 {{gambit}}) Nc6 3. Bb5 $1 a6 4. Ba4 Nf6 5. O-O Be7 *\n\n"
|
||||
));
|
||||
}
|
||||
let source = dir.file("source.pgn", text.as_bytes());
|
||||
let db = open(&source);
|
||||
let target = dir.0.join("copy.pgn");
|
||||
let records: Vec<u32> = (0..1000).collect();
|
||||
let t = std::time::Instant::now();
|
||||
let report = copy(&db, &request(&records, &target)).unwrap().unwrap();
|
||||
println!(
|
||||
"copy 1000 games: {:?} ({} copied)",
|
||||
t.elapsed(),
|
||||
report.copied
|
||||
);
|
||||
let view: Vec<u32> = (0..4_000_000).collect();
|
||||
let t = std::time::Instant::now();
|
||||
let mut s = Selection::default();
|
||||
s.extend(&view);
|
||||
println!("select all of 4 000 000: {:?}", t.elapsed());
|
||||
let t = std::time::Instant::now();
|
||||
let n = s.count_in(&view);
|
||||
println!("count chosen in 4 000 000: {:?} ({n})", t.elapsed());
|
||||
}
|
||||
|
||||
fn rss_anon_kb() -> u64 {
|
||||
std::fs::read_to_string("/proc/self/status")
|
||||
.ok()
|
||||
.and_then(|s| {
|
||||
s.lines()
|
||||
.find(|l| l.starts_with("RssAnon:"))
|
||||
.and_then(|l| l.split_whitespace().nth(1)?.parse().ok())
|
||||
})
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The memory a copy takes beyond the open database: the peak of `RssAnon` while it runs
|
||||
/// less the value before. `CP_PROBE_DB=<file>` and `CP_PROBE_N=<records>` (release:
|
||||
/// `cargo test --release -- --ignored --nocapture copy_memory`); without them, synthetic
|
||||
/// PGN of 1 000 000 games in a temporary folder.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn copy_memory() {
|
||||
let dir = Dir::new("memory");
|
||||
let (db, n) = match std::env::var("CP_PROBE_DB") {
|
||||
Ok(path) => {
|
||||
let n = std::env::var("CP_PROBE_N")
|
||||
.ok()
|
||||
.and_then(|n| n.parse().ok())
|
||||
.unwrap_or(200_000);
|
||||
(open(Path::new(&path)), n)
|
||||
}
|
||||
Err(_) => {
|
||||
let n: usize = std::env::var("CP_PROBE_N")
|
||||
.ok()
|
||||
.and_then(|n| n.parse().ok())
|
||||
.unwrap_or(1_000_000);
|
||||
let path = dir.0.join("big.pgn");
|
||||
let mut out = std::io::BufWriter::new(std::fs::File::create(&path).unwrap());
|
||||
for i in 0..n {
|
||||
write!(
|
||||
out,
|
||||
"[White \"W{i}\"]\n[Black \"B{}\"]\n[Result \"*\"]\n\n1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O *\n\n",
|
||||
i % 977
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
drop(out);
|
||||
(open(&path), n)
|
||||
}
|
||||
};
|
||||
let records: Vec<u32> = (0..n.min(db.len()) as u32).collect();
|
||||
// The database's own index for sorting is built once, by the table: not the copy's.
|
||||
db.sort_records(&mut records.clone(), SortKey::Number, true);
|
||||
let before = rss_anon_kb();
|
||||
let done = std::sync::Arc::new(AtomicBool::new(false));
|
||||
let peak = {
|
||||
let done = done.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut peak = 0;
|
||||
while !done.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
peak = peak.max(rss_anon_kb());
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
peak
|
||||
})
|
||||
};
|
||||
let target = dir.0.join("copy.pgn");
|
||||
let t = std::time::Instant::now();
|
||||
let report = copy(&db, &request(&records, &target)).unwrap().unwrap();
|
||||
let took = t.elapsed();
|
||||
done.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
let peak = peak.join().unwrap();
|
||||
println!(
|
||||
"records {}: copied {}, duplicates {}, {:?}; RssAnon before {} KB, peak {} KB, +{} KB ({:.0} B per record)",
|
||||
records.len(),
|
||||
report.copied,
|
||||
report.duplicates.len(),
|
||||
took,
|
||||
before,
|
||||
peak,
|
||||
peak.saturating_sub(before),
|
||||
peak.saturating_sub(before) as f64 * 1024.0 / records.len().max(1) as f64
|
||||
);
|
||||
}
|
||||
|
|
@ -44,9 +44,6 @@ pub struct BoardState {
|
|||
shape_from: Option<Square>,
|
||||
/// A shape drawn this frame, for the game to take (`take_shape`).
|
||||
shape: Option<Drawn>,
|
||||
/// Temporary shapes in play and training; never written to the PGN.
|
||||
temporary_shapes: Vec<Drawn>,
|
||||
temporary_position: Option<Chess>,
|
||||
/// The position drawn last: a different one next frame is animated from it.
|
||||
shown: Option<Board>,
|
||||
anim: Option<Anim>,
|
||||
|
|
@ -95,32 +92,6 @@ impl BoardState {
|
|||
self.shape.take()
|
||||
}
|
||||
|
||||
pub fn draw_temporary(&mut self, drawn: Drawn, pos: &Chess) {
|
||||
self.shape = None;
|
||||
self.sync_temporary_position(pos);
|
||||
let same = |shape: &Drawn| match (*shape, drawn) {
|
||||
(Drawn::Arrow(_, af, at), Drawn::Arrow(_, bf, bt)) => af == bf && at == bt,
|
||||
(Drawn::Circle(_, a), Drawn::Circle(_, b)) => a == b,
|
||||
_ => false,
|
||||
};
|
||||
if let Some(index) = self.temporary_shapes.iter().position(same) {
|
||||
if self.temporary_shapes[index] == drawn {
|
||||
self.temporary_shapes.remove(index);
|
||||
} else {
|
||||
self.temporary_shapes[index] = drawn;
|
||||
}
|
||||
} else {
|
||||
self.temporary_shapes.push(drawn);
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_temporary_position(&mut self, pos: &Chess) {
|
||||
if self.temporary_position.as_ref() != Some(pos) {
|
||||
self.temporary_shapes.clear();
|
||||
self.temporary_position = Some(pos.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// A piece is selected or dragged, or a promotion is being chosen.
|
||||
pub fn is_busy(&self) -> bool {
|
||||
self.selected.is_some() || self.drag.is_some() || self.promotion.is_some()
|
||||
|
|
@ -205,8 +176,6 @@ pub struct BoardView<'a> {
|
|||
/// Move assessment shown on the destination square of the last move ("??" in red, …).
|
||||
pub badge: Option<Badge>,
|
||||
pub interactive: bool,
|
||||
/// Right-button shapes stay until the position changes instead of becoming PGN comments.
|
||||
pub temporary_shapes: bool,
|
||||
pub show_coords: bool,
|
||||
pub theme: BoardTheme,
|
||||
pub pieces: PieceSet,
|
||||
|
|
@ -247,11 +216,6 @@ impl BoardView<'_> {
|
|||
state.selected = None;
|
||||
state.drag = None;
|
||||
}
|
||||
if self.temporary_shapes {
|
||||
state.sync_temporary_position(self.pos);
|
||||
} else {
|
||||
state.temporary_shapes.clear();
|
||||
}
|
||||
|
||||
// --- input -----------------------------------------------------------------------
|
||||
if (self.interactive || premoving) && state.promotion.is_none() {
|
||||
|
|
@ -310,11 +274,10 @@ impl BoardView<'_> {
|
|||
.and_then(|p| geo.square_at(p));
|
||||
let color = shape_color_for(ui.input(|i| i.modifiers));
|
||||
if let Some(from) = state.shape_from.take() {
|
||||
let drawn = match to {
|
||||
state.shape = Some(match to {
|
||||
Some(to) if to != from => Drawn::Arrow(color, from, to),
|
||||
_ => Drawn::Circle(color, from),
|
||||
};
|
||||
self.record_shape(state, drawn);
|
||||
});
|
||||
}
|
||||
}
|
||||
if response.secondary_clicked() {
|
||||
|
|
@ -322,7 +285,7 @@ impl BoardView<'_> {
|
|||
state.premove = None;
|
||||
if let Some(sq) = pointer.and_then(|p| geo.square_at(p)) {
|
||||
let color = shape_color_for(ui.input(|i| i.modifiers));
|
||||
self.record_shape(state, Drawn::Circle(color, sq));
|
||||
state.shape = Some(Drawn::Circle(color, sq));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -476,31 +439,6 @@ impl BoardView<'_> {
|
|||
for a in self.arrows {
|
||||
draw_arrow(&painter, &geo, a);
|
||||
}
|
||||
for drawn in &state.temporary_shapes {
|
||||
let color = shape_preview_color(match *drawn {
|
||||
Drawn::Arrow(color, _, _) | Drawn::Circle(color, _) => color,
|
||||
});
|
||||
match *drawn {
|
||||
Drawn::Arrow(_, from, to) => draw_arrow(
|
||||
&painter,
|
||||
&geo,
|
||||
&Arrow {
|
||||
from,
|
||||
to,
|
||||
color,
|
||||
weight: 0.9,
|
||||
},
|
||||
),
|
||||
Drawn::Circle(_, square) => {
|
||||
let r = geo.square_rect(square);
|
||||
painter.circle_stroke(
|
||||
r.center(),
|
||||
sq_size * 0.46,
|
||||
Stroke::new(sq_size * 0.07, color),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(from) = state.shape_from
|
||||
&& response.dragged_by(egui::PointerButton::Secondary)
|
||||
{
|
||||
|
|
@ -613,14 +551,6 @@ impl BoardView<'_> {
|
|||
result
|
||||
}
|
||||
|
||||
fn record_shape(&self, state: &mut BoardState, drawn: Drawn) {
|
||||
if self.temporary_shapes {
|
||||
state.draw_temporary(drawn, self.pos);
|
||||
} else {
|
||||
state.shape = Some(drawn);
|
||||
}
|
||||
}
|
||||
|
||||
/// The side that moves on this board now: the side to move, or the premoving one.
|
||||
fn mover(&self) -> Color {
|
||||
match self.premove {
|
||||
|
|
@ -1014,252 +944,4 @@ mod tests {
|
|||
);
|
||||
assert!(fadings.is_empty());
|
||||
}
|
||||
|
||||
fn board_frame(
|
||||
ctx: &egui::Context,
|
||||
state: &mut BoardState,
|
||||
pos: &Chess,
|
||||
time: f64,
|
||||
events: Vec<egui::Event>,
|
||||
temporary_shapes: bool,
|
||||
) {
|
||||
let mut view = Some(BoardView {
|
||||
pos,
|
||||
orientation: Color::White,
|
||||
last_move: None,
|
||||
arrows: &[],
|
||||
circles: &[],
|
||||
badge: None,
|
||||
interactive: true,
|
||||
temporary_shapes,
|
||||
show_coords: false,
|
||||
theme: crate::assets::BoardThemeId::Brown.theme(),
|
||||
pieces: PieceSet::Cburnett,
|
||||
animation: 0.0,
|
||||
premove: None,
|
||||
auto_queen: false,
|
||||
alert: None,
|
||||
});
|
||||
ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(400.0, 400.0),
|
||||
)),
|
||||
time: Some(time),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
view.take().unwrap().show(ui, state);
|
||||
},
|
||||
)
|
||||
.drop_without_applying_deltas();
|
||||
}
|
||||
|
||||
fn right_click(at: egui::Pos2, modifiers: egui::Modifiers) -> Vec<egui::Event> {
|
||||
vec![
|
||||
egui::Event::ModifiersChanged(modifiers),
|
||||
egui::Event::PointerMoved(at),
|
||||
egui::Event::PointerButton {
|
||||
pos: at,
|
||||
button: egui::PointerButton::Secondary,
|
||||
pressed: true,
|
||||
modifiers,
|
||||
},
|
||||
egui::Event::PointerButton {
|
||||
pos: at,
|
||||
button: egui::PointerButton::Secondary,
|
||||
pressed: false,
|
||||
modifiers,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temporary_shapes_accept_mouse_input_toggle_and_clear() {
|
||||
let ctx = egui::Context::default();
|
||||
let pos = Chess::default();
|
||||
let mut state = BoardState::default();
|
||||
let sq = |s: &str| s.parse::<Square>().unwrap();
|
||||
let from = egui::pos2(225.0, 325.0);
|
||||
let to = egui::pos2(225.0, 225.0);
|
||||
board_frame(&ctx, &mut state, &pos, 0.0, Vec::new(), true);
|
||||
board_frame(
|
||||
&ctx,
|
||||
&mut state,
|
||||
&pos,
|
||||
0.1,
|
||||
vec![
|
||||
egui::Event::PointerMoved(from),
|
||||
egui::Event::PointerButton {
|
||||
pos: from,
|
||||
button: egui::PointerButton::Secondary,
|
||||
pressed: true,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
},
|
||||
],
|
||||
true,
|
||||
);
|
||||
board_frame(
|
||||
&ctx,
|
||||
&mut state,
|
||||
&pos,
|
||||
0.2,
|
||||
vec![egui::Event::PointerMoved(to)],
|
||||
true,
|
||||
);
|
||||
board_frame(
|
||||
&ctx,
|
||||
&mut state,
|
||||
&pos,
|
||||
0.3,
|
||||
vec![egui::Event::PointerButton {
|
||||
pos: to,
|
||||
button: egui::PointerButton::Secondary,
|
||||
pressed: false,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
}],
|
||||
true,
|
||||
);
|
||||
assert_eq!(
|
||||
state.temporary_shapes,
|
||||
vec![Drawn::Arrow(
|
||||
chess_core::ShapeColor::Green,
|
||||
sq("e2"),
|
||||
sq("e4")
|
||||
)]
|
||||
);
|
||||
assert!(state.shape.is_none());
|
||||
|
||||
let d5 = egui::pos2(175.0, 175.0);
|
||||
board_frame(
|
||||
&ctx,
|
||||
&mut state,
|
||||
&pos,
|
||||
0.4,
|
||||
right_click(d5, egui::Modifiers::NONE),
|
||||
true,
|
||||
);
|
||||
assert_eq!(state.temporary_shapes.len(), 2);
|
||||
board_frame(
|
||||
&ctx,
|
||||
&mut state,
|
||||
&pos,
|
||||
0.5,
|
||||
right_click(d5, egui::Modifiers::SHIFT),
|
||||
true,
|
||||
);
|
||||
assert_eq!(
|
||||
state.temporary_shapes[1],
|
||||
Drawn::Circle(chess_core::ShapeColor::Red, sq("d5"))
|
||||
);
|
||||
board_frame(
|
||||
&ctx,
|
||||
&mut state,
|
||||
&pos,
|
||||
0.6,
|
||||
right_click(d5, egui::Modifiers::SHIFT),
|
||||
true,
|
||||
);
|
||||
assert_eq!(state.temporary_shapes.len(), 1);
|
||||
|
||||
let mut next = pos.clone();
|
||||
next.play_unchecked("e4".parse::<San>().unwrap().to_move(&pos).unwrap());
|
||||
board_frame(&ctx, &mut state, &next, 0.7, Vec::new(), true);
|
||||
assert!(state.temporary_shapes.is_empty());
|
||||
}
|
||||
|
||||
/// A right-button drag in the analysis of a game: one arrow, handed over once, in
|
||||
/// the colour of the modifiers held as the button is let go.
|
||||
#[test]
|
||||
fn analysis_arrow_is_drawn_by_a_right_drag() {
|
||||
let ctx = egui::Context::default();
|
||||
let pos = Chess::default();
|
||||
let mut state = BoardState::default();
|
||||
let from = egui::pos2(225.0, 325.0);
|
||||
let to = egui::pos2(225.0, 225.0);
|
||||
let shift_alt = egui::Modifiers::SHIFT | egui::Modifiers::ALT;
|
||||
board_frame(&ctx, &mut state, &pos, 0.0, Vec::new(), false);
|
||||
board_frame(
|
||||
&ctx,
|
||||
&mut state,
|
||||
&pos,
|
||||
0.1,
|
||||
vec![
|
||||
egui::Event::PointerMoved(from),
|
||||
egui::Event::PointerButton {
|
||||
pos: from,
|
||||
button: egui::PointerButton::Secondary,
|
||||
pressed: true,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
},
|
||||
],
|
||||
false,
|
||||
);
|
||||
board_frame(
|
||||
&ctx,
|
||||
&mut state,
|
||||
&pos,
|
||||
0.2,
|
||||
vec![egui::Event::PointerMoved(to)],
|
||||
false,
|
||||
);
|
||||
assert!(
|
||||
state.take_shape().is_none(),
|
||||
"nothing before the button is let go"
|
||||
);
|
||||
board_frame(
|
||||
&ctx,
|
||||
&mut state,
|
||||
&pos,
|
||||
0.3,
|
||||
vec![
|
||||
egui::Event::ModifiersChanged(shift_alt),
|
||||
egui::Event::PointerButton {
|
||||
pos: to,
|
||||
button: egui::PointerButton::Secondary,
|
||||
pressed: false,
|
||||
modifiers: shift_alt,
|
||||
},
|
||||
],
|
||||
false,
|
||||
);
|
||||
assert!(state.temporary_shapes.is_empty());
|
||||
assert_eq!(
|
||||
state.take_shape(),
|
||||
Some(Drawn::Arrow(
|
||||
chess_core::ShapeColor::Yellow,
|
||||
"e2".parse().unwrap(),
|
||||
"e4".parse().unwrap()
|
||||
))
|
||||
);
|
||||
assert!(state.take_shape().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analysis_shapes_remain_one_shot_events() {
|
||||
let ctx = egui::Context::default();
|
||||
let pos = Chess::default();
|
||||
let mut state = BoardState::default();
|
||||
let at = egui::pos2(175.0, 175.0);
|
||||
board_frame(&ctx, &mut state, &pos, 0.0, Vec::new(), false);
|
||||
board_frame(
|
||||
&ctx,
|
||||
&mut state,
|
||||
&pos,
|
||||
0.1,
|
||||
right_click(at, egui::Modifiers::NONE),
|
||||
false,
|
||||
);
|
||||
assert!(state.temporary_shapes.is_empty());
|
||||
assert_eq!(
|
||||
state.take_shape(),
|
||||
Some(Drawn::Circle(
|
||||
chess_core::ShapeColor::Green,
|
||||
"d5".parse().unwrap()
|
||||
))
|
||||
);
|
||||
assert!(state.take_shape().is_none());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -519,7 +519,6 @@ impl SearchBoard {
|
|||
circles: &[],
|
||||
badge: None,
|
||||
interactive: true,
|
||||
temporary_shapes: false,
|
||||
show_coords: settings.show_coords,
|
||||
theme: settings.board_theme.theme(),
|
||||
pieces: settings.piece_set,
|
||||
|
|
@ -930,11 +929,6 @@ impl<T: Send + 'static> Background<T> {
|
|||
pub fn cancel(&self) {
|
||||
self.cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Waits up to `timeout` for the result (the work cleans up after itself).
|
||||
pub fn wait(&self, timeout: std::time::Duration) -> Option<Option<T>> {
|
||||
self.rx.recv_timeout(timeout).ok()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for Background<T> {
|
||||
|
|
|
|||
|
|
@ -1,862 +0,0 @@
|
|||
//! The search for brilliant and great moves (!!, !) in the games of a filtered list
|
||||
//! or a manual selection (tasks 27 and 42): a background pass of
|
||||
//! the game analysis's engine over at most [`LIMIT`] games, the index of what each
|
||||
//! analysed record holds (kept beside the analysis cache, one file per database), and
|
||||
//! the totals of a pass by category. Games already analysed come from the analysis
|
||||
//! cache, the engine is not asked again; the source database is only read.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
|
||||
use chess_core::Game;
|
||||
use chess_import::Database;
|
||||
use game_review::{CacheStore, GameAnalysis, JobEvent, JobFailure, JobSettings, Judgement};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// A pass takes at most this many games (the owner's limit, inclusive).
|
||||
pub const LIMIT: usize = 100;
|
||||
|
||||
/// Why a pass over `n` listed games cannot start (the button is disabled with this).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Blocked {
|
||||
NoGames,
|
||||
TooMany,
|
||||
}
|
||||
|
||||
/// Whether a pass over a list of `n` games may start: 1 to [`LIMIT`] inclusive.
|
||||
pub fn can_start(n: usize) -> Result<(), Blocked> {
|
||||
match n {
|
||||
0 => Err(Blocked::NoGames),
|
||||
n if n > LIMIT => Err(Blocked::TooMany),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The manual source of a pass: its size before cached or unsupported games are taken
|
||||
/// out, and how many of those records the current filter hid when the request was made.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct SelectedGames {
|
||||
pub games: usize,
|
||||
pub hidden: usize,
|
||||
}
|
||||
|
||||
/// Engine judgements of one side of a game.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Counts {
|
||||
pub brilliant: u32,
|
||||
pub great: u32,
|
||||
pub inaccuracies: u32,
|
||||
pub mistakes: u32,
|
||||
pub blunders: u32,
|
||||
}
|
||||
|
||||
/// One side of an analysed game: its judgements, average centipawn loss and accuracy.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SideMarks {
|
||||
#[serde(flatten)]
|
||||
pub counts: Counts,
|
||||
#[serde(default)]
|
||||
pub acpl: Option<u32>,
|
||||
#[serde(default)]
|
||||
pub accuracy: Option<f64>,
|
||||
}
|
||||
|
||||
impl SideMarks {
|
||||
fn of(s: &game_review::SideStats) -> SideMarks {
|
||||
SideMarks {
|
||||
counts: Counts {
|
||||
brilliant: s.brilliant,
|
||||
great: s.great,
|
||||
inaccuracies: s.inaccuracies,
|
||||
mistakes: s.mistakes,
|
||||
blunders: s.blunders,
|
||||
},
|
||||
acpl: s.acpl,
|
||||
accuracy: s.accuracy,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Counts {
|
||||
pub fn add(&mut self, o: &Counts) {
|
||||
self.brilliant += o.brilliant;
|
||||
self.great += o.great;
|
||||
self.inaccuracies += o.inaccuracies;
|
||||
self.mistakes += o.mistakes;
|
||||
self.blunders += o.blunders;
|
||||
}
|
||||
}
|
||||
|
||||
/// A move of note: its ply in the main line (0: the first move), who made it, its
|
||||
/// number and SAN (Latin letters, as in PGN), and whether it is brilliant (else great).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Found {
|
||||
pub ply: u16,
|
||||
pub white: bool,
|
||||
pub number: u32,
|
||||
pub san: String,
|
||||
pub brilliant: bool,
|
||||
}
|
||||
|
||||
impl Found {
|
||||
/// «21.Rxf7!!», «34…Nf3+!!» in the notation of the settings.
|
||||
pub fn label(&self) -> String {
|
||||
let dots = if self.white { "." } else { "…" };
|
||||
let mark = if self.brilliant { "!!" } else { "!" };
|
||||
format!("{}{dots}{}{mark}", self.number, crate::san::show(&self.san))
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a game is not analysed.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Skip {
|
||||
NoMoves,
|
||||
Chess960,
|
||||
/// A training null move (`--`) in the main line.
|
||||
NullMove,
|
||||
Unreadable,
|
||||
}
|
||||
|
||||
impl Skip {
|
||||
pub fn reason(self) -> &'static str {
|
||||
crate::i18n::tr(match self {
|
||||
Skip::NoMoves => "no moves",
|
||||
Skip::Chess960 => "Chess960",
|
||||
Skip::NullMove => "a null move in the main line",
|
||||
Skip::Unreadable => "the game cannot be read",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// What the index knows of a record.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Entry {
|
||||
/// The main line's name in the analysis cache: the entry holds only while the record
|
||||
/// still has this main line.
|
||||
pub line: String,
|
||||
#[serde(default)]
|
||||
pub white: SideMarks,
|
||||
#[serde(default)]
|
||||
pub black: SideMarks,
|
||||
/// Every !! and the first three !.
|
||||
#[serde(default)]
|
||||
pub found: Vec<Found>,
|
||||
/// Analysed with the engine settings of before (counted as analysed).
|
||||
#[serde(default)]
|
||||
pub stale: bool,
|
||||
#[serde(default)]
|
||||
pub skip: Option<Skip>,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
/// The entry with only the marks of the sides that count (the filter's player): the
|
||||
/// row's sign and hint show only them.
|
||||
pub fn for_sides(&self, white: bool, black: bool) -> Entry {
|
||||
let keep = |on: bool, s: &SideMarks| if on { *s } else { SideMarks::default() };
|
||||
Entry {
|
||||
white: keep(white, &self.white),
|
||||
black: keep(black, &self.black),
|
||||
found: self
|
||||
.found
|
||||
.iter()
|
||||
.filter(|f| if f.white { white } else { black })
|
||||
.cloned()
|
||||
.collect(),
|
||||
..self.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The !! and ! of the sides that count.
|
||||
pub fn of_sides(&self, white: bool, black: bool) -> Counts {
|
||||
let mut c = Counts::default();
|
||||
if white {
|
||||
c.add(&self.white.counts);
|
||||
}
|
||||
if black {
|
||||
c.add(&self.black.counts);
|
||||
}
|
||||
c
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry of `record` if it still belongs to the game the database has there now (its
|
||||
/// main line is the one analysed): a deleted or changed game never lends its marks to
|
||||
/// the record that took its number.
|
||||
pub fn current_entry(index: &Index, db: &Database, record: u32) -> Option<Entry> {
|
||||
let entry = index.get(record)?;
|
||||
let game = db.load_game(record as usize)?.game;
|
||||
(GameAnalysis::new(&game, None).cache_key() == entry.line).then(|| entry.clone())
|
||||
}
|
||||
|
||||
/// The record of an analysis of `game`: its marks per side and its moves of note.
|
||||
pub fn entry_of(analysis: &GameAnalysis, game: &Game) -> Entry {
|
||||
let report = &analysis.report;
|
||||
let line = analysis.line();
|
||||
let mut found = Vec::new();
|
||||
let mut great = 0;
|
||||
for (ply, j) in report.judgements.iter().enumerate() {
|
||||
let brilliant = match j {
|
||||
Some(Judgement::Brilliant) => true,
|
||||
Some(Judgement::Great) if great < 3 => {
|
||||
great += 1;
|
||||
false
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
let Some(&node) = line.get(ply + 1) else {
|
||||
continue;
|
||||
};
|
||||
let (Some(m), Some((number, color))) = (game.game_move(node), game.move_number(node))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
found.push(Found {
|
||||
ply: ply as u16,
|
||||
white: color == chess_core::shakmaty::Color::White,
|
||||
number,
|
||||
san: m.san.clone(),
|
||||
brilliant,
|
||||
});
|
||||
}
|
||||
Entry {
|
||||
line: analysis.cache_key(),
|
||||
white: SideMarks::of(&report.white),
|
||||
black: SideMarks::of(&report.black),
|
||||
found,
|
||||
stale: analysis.stale(),
|
||||
skip: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry of a game that is not analysed, and why («—» in the column).
|
||||
pub fn skipped_entry(line: String, skip: Skip) -> Entry {
|
||||
Entry {
|
||||
line,
|
||||
white: SideMarks::default(),
|
||||
black: SideMarks::default(),
|
||||
found: Vec::new(),
|
||||
stale: false,
|
||||
skip: Some(skip),
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `game` is not analysed, if it is not.
|
||||
pub fn skip_of(game: &Game, chess960: bool) -> Option<Skip> {
|
||||
if chess960 {
|
||||
return Some(Skip::Chess960);
|
||||
}
|
||||
let line = game.mainline();
|
||||
if line.is_empty() {
|
||||
return Some(Skip::NoMoves);
|
||||
}
|
||||
if line
|
||||
.iter()
|
||||
.any(|id| game.game_move(*id).is_none_or(|m| m.is_null()))
|
||||
{
|
||||
return Some(Skip::NullMove);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct IndexFile {
|
||||
version: u32,
|
||||
records: Vec<(u32, Entry)>,
|
||||
}
|
||||
|
||||
const INDEX_VERSION: u32 = 1;
|
||||
|
||||
/// The marks of a database's records, by record number, in a file of their own. No
|
||||
/// file (or one of another version) is an empty index: nothing found yet.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Index {
|
||||
file: Option<PathBuf>,
|
||||
records: BTreeMap<u32, Entry>,
|
||||
/// Changes since it was read (the table re-checks what it shows).
|
||||
pub generation: u64,
|
||||
}
|
||||
|
||||
/// The folder of the indexes: beside the analysis cache.
|
||||
fn index_dir() -> Option<PathBuf> {
|
||||
crate::settings::Settings::cache_dir().map(|d| d.join("marks"))
|
||||
}
|
||||
|
||||
/// The index file of the database at `db`: named by a hash of its real path.
|
||||
pub fn index_file(dir: &Path, db: &Path) -> PathBuf {
|
||||
let real = std::fs::canonicalize(db).unwrap_or_else(|_| db.to_path_buf());
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
real.hash(&mut h);
|
||||
dir.join(format!("{:016x}.json", h.finish()))
|
||||
}
|
||||
|
||||
impl Index {
|
||||
/// The index of the database at `db`, from the program's cache.
|
||||
pub fn of(db: &Path) -> Index {
|
||||
match index_dir() {
|
||||
Some(dir) => Index::load(index_file(&dir, db)),
|
||||
None => Index::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The index kept in `file`.
|
||||
pub fn load(file: PathBuf) -> Index {
|
||||
let records = match crate::platform::fs::read(&file) {
|
||||
Ok(bytes) => match serde_json::from_slice::<IndexFile>(&bytes) {
|
||||
Ok(f) if f.version == INDEX_VERSION => f.records.into_iter().collect(),
|
||||
Ok(f) => {
|
||||
eprintln!("marks: {}: version {}", file.display(), f.version);
|
||||
BTreeMap::new()
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("marks: {}: {e}", file.display());
|
||||
BTreeMap::new()
|
||||
}
|
||||
},
|
||||
Err(_) => BTreeMap::new(),
|
||||
};
|
||||
Index {
|
||||
file: Some(file),
|
||||
records,
|
||||
generation: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The records with an entry.
|
||||
pub fn records(&self) -> impl Iterator<Item = u32> + '_ {
|
||||
self.records.keys().copied()
|
||||
}
|
||||
|
||||
pub fn get(&self, record: u32) -> Option<&Entry> {
|
||||
self.records.get(&record)
|
||||
}
|
||||
|
||||
pub fn set(&mut self, record: u32, entry: Entry) {
|
||||
self.records.insert(record, entry);
|
||||
self.generation += 1;
|
||||
}
|
||||
|
||||
/// Where a record goes when the table is sorted by its marks: !! first, then !,
|
||||
/// analysed without them, not analysable, not analysed.
|
||||
pub fn rank(&self, record: u32, sides: &Sides, current: &dyn Fn(u32) -> bool) -> u8 {
|
||||
match self.records.get(&record).filter(|_| current(record)) {
|
||||
None => 4,
|
||||
Some(e) if e.skip.is_some() => 3,
|
||||
Some(e) => {
|
||||
let (w, b) = sides.of(record);
|
||||
let c = e.of_sides(w, b);
|
||||
if c.brilliant > 0 {
|
||||
0
|
||||
} else if c.great > 0 {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn len(&self) -> usize {
|
||||
self.records.len()
|
||||
}
|
||||
|
||||
/// Written whole into a temporary file and renamed over the old one.
|
||||
pub fn save(&self) -> std::io::Result<()> {
|
||||
let Some(file) = &self.file else {
|
||||
return Ok(());
|
||||
};
|
||||
let out = IndexFile {
|
||||
version: INDEX_VERSION,
|
||||
records: self.records.iter().map(|(r, e)| (*r, e.clone())).collect(),
|
||||
};
|
||||
let bytes = serde_json::to_vec(&out).map_err(std::io::Error::other)?;
|
||||
if let Some(dir) = file.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
crate::platform::fs::write_atomic(file, &bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a pass is: games done, and the record being analysed (its number + 1; 0:
|
||||
/// none).
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Progress {
|
||||
pub done: AtomicUsize,
|
||||
pub current: AtomicUsize,
|
||||
}
|
||||
|
||||
/// How a pass ended.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Outcome {
|
||||
Finished,
|
||||
Stopped,
|
||||
EngineFailed(String),
|
||||
SourceChanged,
|
||||
}
|
||||
|
||||
/// What a pass did.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PassEnd {
|
||||
pub outcome: Outcome,
|
||||
/// Records analysed (by the engine now, or from the cache), in the pass's order.
|
||||
pub reviewed: Vec<u32>,
|
||||
/// Of them, taken from the cache without the engine.
|
||||
pub from_cache: usize,
|
||||
pub skipped: Vec<(u32, Skip)>,
|
||||
}
|
||||
|
||||
/// The engine of a pass: started for each game that needs it.
|
||||
pub struct Engine {
|
||||
#[cfg(not(web))]
|
||||
pub config: uci::EngineConfig,
|
||||
pub settings: JobSettings,
|
||||
/// Whether the engine, by the name it gives, is still the one checked.
|
||||
pub fits: Box<dyn Fn(&str) -> bool + Send + Sync>,
|
||||
/// A pause before each game (`CP_BRILLIANT_SLOW`: the progress can be photographed).
|
||||
pub pause: std::time::Duration,
|
||||
}
|
||||
|
||||
/// The engine job over `targets` (on a computer; a browser has no pass, `CAPS`).
|
||||
#[cfg(not(web))]
|
||||
fn engine_run(
|
||||
engine: &Engine,
|
||||
targets: Vec<game_review::Target>,
|
||||
cancel: &AtomicBool,
|
||||
on_event: &mut dyn FnMut(JobEvent),
|
||||
) -> Result<(), JobFailure> {
|
||||
game_review::run(
|
||||
engine.config.clone(),
|
||||
&engine.settings,
|
||||
targets,
|
||||
cancel,
|
||||
on_event,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(web)]
|
||||
fn engine_run(
|
||||
_engine: &Engine,
|
||||
_targets: Vec<game_review::Target>,
|
||||
_cancel: &AtomicBool,
|
||||
_on_event: &mut dyn FnMut(JobEvent),
|
||||
) -> Result<(), JobFailure> {
|
||||
Err(JobFailure::Start(
|
||||
crate::i18n::tr("the engine did not start").to_owned(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Analyses `records` of `db` in this order: each from the analysis cache in `cache`
|
||||
/// when it is there (also one made with the engine settings of before), else with
|
||||
/// `engine`; after each game the cache and `index` are saved, so a stop or a crash
|
||||
/// keeps what was done. `cancel` stops it within the current search.
|
||||
pub fn run_pass(
|
||||
db: &Database,
|
||||
records: &[u32],
|
||||
index: &Mutex<Index>,
|
||||
cache: &dyn CacheStore,
|
||||
engine: &Engine,
|
||||
progress: &Progress,
|
||||
cancel: &AtomicBool,
|
||||
) -> PassEnd {
|
||||
let mut end = PassEnd {
|
||||
outcome: Outcome::Finished,
|
||||
reviewed: Vec::new(),
|
||||
from_cache: 0,
|
||||
skipped: Vec::new(),
|
||||
};
|
||||
for &record in records {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
end.outcome = Outcome::Stopped;
|
||||
break;
|
||||
}
|
||||
if let Some(pgn) = db.as_pgn()
|
||||
&& pgn.source_changed().unwrap_or(true)
|
||||
{
|
||||
end.outcome = Outcome::SourceChanged;
|
||||
break;
|
||||
}
|
||||
progress
|
||||
.current
|
||||
.store(record as usize + 1, Ordering::Relaxed);
|
||||
if !engine.pause.is_zero() {
|
||||
std::thread::sleep(engine.pause);
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
end.outcome = Outcome::Stopped;
|
||||
break;
|
||||
}
|
||||
}
|
||||
let index_skip = |skip: Skip, line: String| {
|
||||
if let Ok(mut i) = index.lock() {
|
||||
i.set(
|
||||
record,
|
||||
Entry {
|
||||
line,
|
||||
white: SideMarks::default(),
|
||||
black: SideMarks::default(),
|
||||
found: Vec::new(),
|
||||
stale: false,
|
||||
skip: Some(skip),
|
||||
},
|
||||
);
|
||||
let _ = i.save();
|
||||
}
|
||||
};
|
||||
let Some(parsed) = db.load_game(record as usize) else {
|
||||
end.skipped.push((record, Skip::Unreadable));
|
||||
index_skip(Skip::Unreadable, String::new());
|
||||
progress.done.fetch_add(1, Ordering::Relaxed);
|
||||
continue;
|
||||
};
|
||||
let game = parsed.game;
|
||||
let chess960 = db.row(record as usize).chess960;
|
||||
let mut analysis = GameAnalysis::with_store(&game, Some(cache));
|
||||
if let Some(skip) = skip_of(&game, chess960) {
|
||||
end.skipped.push((record, skip));
|
||||
index_skip(skip, analysis.cache_key());
|
||||
progress.done.fetch_add(1, Ordering::Relaxed);
|
||||
continue;
|
||||
}
|
||||
let by_engine = analysis.has_data() && analysis.meta.as_ref().is_some_and(|m| m.nodes > 0);
|
||||
// An analysis with every position evaluated is one, also of the engine settings
|
||||
// of before (the owner's decision; `begin` would drop that one): it is taken as
|
||||
// it is, the engine is not asked.
|
||||
let targets = if by_engine && (analysis.stale() || analysis.missing() == 0) {
|
||||
Vec::new()
|
||||
} else {
|
||||
analysis.begin(&game, !by_engine)
|
||||
};
|
||||
if targets.is_empty() && by_engine {
|
||||
end.from_cache += 1;
|
||||
} else {
|
||||
let mut changed = false;
|
||||
let result = engine_run(engine, targets, cancel, &mut |e| {
|
||||
if changed {
|
||||
return;
|
||||
}
|
||||
if let JobEvent::Engine(name) = &e
|
||||
&& !(engine.fits)(name)
|
||||
{
|
||||
changed = true;
|
||||
return;
|
||||
}
|
||||
analysis.apply(e);
|
||||
});
|
||||
if changed {
|
||||
end.outcome = Outcome::EngineFailed(
|
||||
crate::i18n::tr("the engine is no longer the Stockfish 19 that was checked")
|
||||
.to_owned(),
|
||||
);
|
||||
break;
|
||||
}
|
||||
if let Err(e) = result {
|
||||
end.outcome = Outcome::EngineFailed(match e {
|
||||
JobFailure::Start(e) => {
|
||||
eprintln!("great moves: {e}");
|
||||
crate::i18n::tr("the engine did not start").to_owned()
|
||||
}
|
||||
JobFailure::Engine(e) => {
|
||||
eprintln!("great moves: {e}");
|
||||
crate::i18n::tr("the engine stopped answering").to_owned()
|
||||
}
|
||||
JobFailure::Terminated(r) => crate::analysis::termination_message(&r),
|
||||
});
|
||||
break;
|
||||
}
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
// The evaluations made are kept for later; the game is not counted.
|
||||
let _ = analysis.save_to(cache);
|
||||
end.outcome = Outcome::Stopped;
|
||||
break;
|
||||
}
|
||||
if let Err(e) = analysis.save_to(cache) {
|
||||
eprintln!("review cache: {e}");
|
||||
}
|
||||
}
|
||||
analysis.refresh(&game);
|
||||
if let Ok(mut i) = index.lock() {
|
||||
i.set(record, entry_of(&analysis, &game));
|
||||
if let Err(e) = i.save() {
|
||||
eprintln!("marks: {e}");
|
||||
}
|
||||
}
|
||||
end.reviewed.push(record);
|
||||
progress.done.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
progress.current.store(0, Ordering::Relaxed);
|
||||
end
|
||||
}
|
||||
|
||||
/// Whose moves count in the totals of each record: the player of the filter's sides
|
||||
/// (`white`, `black`), or both when the filter names no player.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Sides {
|
||||
/// Records where the filter's player has White, and Black; `None`: no player.
|
||||
pub player: Option<(Vec<u32>, Vec<u32>)>,
|
||||
}
|
||||
|
||||
impl Sides {
|
||||
/// Whether White's and Black's moves of `record` count.
|
||||
pub fn of(&self, record: u32) -> (bool, bool) {
|
||||
match &self.player {
|
||||
None => (true, true),
|
||||
Some((w, b)) => (
|
||||
w.binary_search(&record).is_ok(),
|
||||
b.binary_search(&record).is_ok(),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The totals of a pass: games analysed, those with !! and with !, every category
|
||||
/// summed over the sides that count, the averages over those sides, and the !! moves.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Totals {
|
||||
pub games: usize,
|
||||
pub with_brilliant: usize,
|
||||
pub with_great: usize,
|
||||
pub counts: Counts,
|
||||
/// Sides counted (a game counts twice when both of its sides do).
|
||||
pub sides: usize,
|
||||
/// Average over the sides of their average centipawn loss, and of their accuracy,
|
||||
/// with the least and the greatest accuracy.
|
||||
pub acpl: Option<f64>,
|
||||
pub accuracy: Option<f64>,
|
||||
pub accuracy_range: Option<(f64, f64)>,
|
||||
/// Of them, analysed with the engine settings of before.
|
||||
pub stale: usize,
|
||||
/// Records where the filter's player was found on neither side.
|
||||
pub player_missing: Vec<u32>,
|
||||
/// Every !! of the sides that count: record and move, in the records' order.
|
||||
pub brilliant: Vec<(u32, Found)>,
|
||||
}
|
||||
|
||||
/// Sums the index's entries of `records` over the sides that count (`sides`).
|
||||
pub fn totals(index: &Index, db: &Database, records: &[u32], sides: &Sides) -> Totals {
|
||||
let mut t = Totals::default();
|
||||
let (mut acpl, mut acc) = (Vec::new(), Vec::new());
|
||||
for &r in records {
|
||||
let Some(e) = current_entry(index, db, r).filter(|e| e.skip.is_none()) else {
|
||||
continue;
|
||||
};
|
||||
let e = &e;
|
||||
let (white, black) = sides.of(r);
|
||||
if !white && !black {
|
||||
t.player_missing.push(r);
|
||||
}
|
||||
let c = e.of_sides(white, black);
|
||||
t.games += 1;
|
||||
t.stale += usize::from(e.stale);
|
||||
t.with_brilliant += usize::from(c.brilliant > 0);
|
||||
t.with_great += usize::from(c.great > 0);
|
||||
t.counts.add(&c);
|
||||
for (counted, side) in [(white, &e.white), (black, &e.black)] {
|
||||
if counted {
|
||||
t.sides += 1;
|
||||
acpl.extend(side.acpl.map(f64::from));
|
||||
acc.extend(side.accuracy);
|
||||
}
|
||||
}
|
||||
t.brilliant.extend(
|
||||
e.found
|
||||
.iter()
|
||||
.filter(|f| f.brilliant && if f.white { white } else { black })
|
||||
.map(|f| (r, f.clone())),
|
||||
);
|
||||
}
|
||||
let mean = |v: &[f64]| (!v.is_empty()).then(|| v.iter().sum::<f64>() / v.len() as f64);
|
||||
t.acpl = mean(&acpl);
|
||||
t.accuracy = mean(&acc);
|
||||
t.accuracy_range = acc.iter().copied().fold(None, |r: Option<(f64, f64)>, a| {
|
||||
Some(r.map_or((a, a), |(lo, hi)| (lo.min(a), hi.max(a))))
|
||||
});
|
||||
t
|
||||
}
|
||||
|
||||
/// The records where the filter's player has White and Black: the player condition
|
||||
/// with the side fixed, without the other conditions. A selected game hidden by those
|
||||
/// other conditions still keeps its player's side; a game of another player has neither.
|
||||
pub fn player_sides(
|
||||
db: &Database,
|
||||
filter: &chess_import::chessbase::base::Filter,
|
||||
cancel: &AtomicBool,
|
||||
) -> Sides {
|
||||
use chess_import::chessbase::base::{Side, SortKey};
|
||||
if !filter.player.is_set() {
|
||||
return Sides::default();
|
||||
}
|
||||
let player = chess_import::chessbase::base::Filter {
|
||||
player: filter.player.clone(),
|
||||
side: filter.side,
|
||||
..Default::default()
|
||||
};
|
||||
let side = |s: Side| {
|
||||
let f = chess_import::chessbase::base::Filter {
|
||||
side: s,
|
||||
..player.clone()
|
||||
};
|
||||
let mut v = db
|
||||
.query(&f, SortKey::Number, true, &AtomicUsize::new(0), cancel)
|
||||
.unwrap_or_default();
|
||||
v.sort_unstable();
|
||||
v
|
||||
};
|
||||
let (w, b) = match filter.side {
|
||||
Side::White => (side(Side::White), Vec::new()),
|
||||
Side::Black => (Vec::new(), side(Side::Black)),
|
||||
_ => (side(Side::White), side(Side::Black)),
|
||||
};
|
||||
Sides {
|
||||
player: Some((w, b)),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the app keeps of a pass for its summary: the filter, the words for its
|
||||
/// conditions (or the manual source), and the games that could not be analysed.
|
||||
pub type PassMeta = (
|
||||
chess_import::chessbase::base::Filter,
|
||||
String,
|
||||
Option<SelectedGames>,
|
||||
Vec<(u32, Skip)>,
|
||||
);
|
||||
|
||||
/// A pass under way, on a thread of its own: its source, its list, how far it is, and
|
||||
/// how it ended once it did.
|
||||
pub struct PassJob {
|
||||
pub source: PathBuf,
|
||||
pub records: Vec<u32>,
|
||||
pub selected: Option<SelectedGames>,
|
||||
progress: std::sync::Arc<Progress>,
|
||||
cancel: std::sync::Arc<AtomicBool>,
|
||||
rx: std::sync::mpsc::Receiver<(PassEnd, Sides)>,
|
||||
pub stopping: bool,
|
||||
pub started: std::time::Instant,
|
||||
}
|
||||
|
||||
impl PassJob {
|
||||
/// Starts the pass over `records` of `db` (the database at `source`); the sides of
|
||||
/// the filter's player are found first, in the same thread.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn start(
|
||||
ctx: &egui::Context,
|
||||
source: PathBuf,
|
||||
db: std::sync::Arc<Database>,
|
||||
records: Vec<u32>,
|
||||
filter: chess_import::chessbase::base::Filter,
|
||||
selected: Option<SelectedGames>,
|
||||
index: std::sync::Arc<Mutex<Index>>,
|
||||
cache: PathBuf,
|
||||
engine: Engine,
|
||||
) -> std::io::Result<PassJob> {
|
||||
let progress = std::sync::Arc::new(Progress::default());
|
||||
let cancel = std::sync::Arc::new(AtomicBool::new(false));
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let (p, c, list, ctx) = (
|
||||
progress.clone(),
|
||||
cancel.clone(),
|
||||
records.clone(),
|
||||
ctx.clone(),
|
||||
);
|
||||
std::thread::Builder::new()
|
||||
.name("brilliant-search".into())
|
||||
.spawn(move || {
|
||||
let sides = player_sides(&db, &filter, &c);
|
||||
let store = crate::review::Cache(cache);
|
||||
let end = run_pass(&db, &list, &index, &store, &engine, &p, &c);
|
||||
let _ = tx.send((end, sides));
|
||||
ctx.request_repaint();
|
||||
})?;
|
||||
Ok(PassJob {
|
||||
source,
|
||||
records,
|
||||
selected,
|
||||
progress,
|
||||
cancel,
|
||||
rx,
|
||||
stopping: false,
|
||||
started: std::time::Instant::now(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn done(&self) -> usize {
|
||||
self.progress.done.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The record being analysed.
|
||||
pub fn current(&self) -> Option<u32> {
|
||||
match self.progress.current.load(Ordering::Relaxed) {
|
||||
0 => None,
|
||||
n => Some(n as u32 - 1),
|
||||
}
|
||||
}
|
||||
|
||||
/// «Stop»: the engines stop within their search; what was analysed stays.
|
||||
pub fn stop(&mut self) {
|
||||
self.cancel.store(true, Ordering::Relaxed);
|
||||
self.stopping = true;
|
||||
}
|
||||
|
||||
/// How it ended, once it did.
|
||||
pub fn poll(&self) -> Option<(PassEnd, Sides)> {
|
||||
self.rx.try_recv().ok()
|
||||
}
|
||||
|
||||
/// Stops and waits up to `timeout` (closing the program).
|
||||
pub fn shutdown(&mut self, timeout: std::time::Duration) {
|
||||
self.stop();
|
||||
let _ = self.rx.recv_timeout(timeout);
|
||||
}
|
||||
|
||||
/// The time left, from the pace so far after three games, else from the moves.
|
||||
pub fn left_secs(&self, estimate: impl Fn(&[u32]) -> f64) -> f64 {
|
||||
let done = self.done();
|
||||
let rest = &self.records[done.min(self.records.len())..];
|
||||
if done >= 3 {
|
||||
self.started.elapsed().as_secs_f64() / done as f64 * rest.len() as f64
|
||||
} else {
|
||||
estimate(rest)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PassJob {
|
||||
fn drop(&mut self) {
|
||||
self.cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Seconds per position of one engine process, with the second search of !! and !:
|
||||
/// measured, 3 games of 170 plies in 44 s in 8 processes (i7-13700KF,
|
||||
/// docs/qa/task-27-functional-2026-11-27.md).
|
||||
const SECS_PER_POSITION: f64 = 2.0;
|
||||
|
||||
/// Seconds an engine takes for games of these many plies over `processes`: the same in
|
||||
/// the question and in the progress until three games are done.
|
||||
pub fn estimate_secs(plies: impl Iterator<Item = usize>, processes: usize) -> f64 {
|
||||
plies
|
||||
.map(|p| (p + 1) as f64 * SECS_PER_POSITION)
|
||||
.sum::<f64>()
|
||||
/ processes.max(1) as f64
|
||||
}
|
||||
|
||||
/// «less than a minute», «about 14 min», «about 1 h 20 min».
|
||||
pub fn format_estimate(secs: f64) -> String {
|
||||
if secs < 60.0 {
|
||||
return crate::i18n::tr("less than a minute").to_owned();
|
||||
}
|
||||
let min = (secs / 60.0).round() as u64;
|
||||
if min < 60 {
|
||||
crate::i18n::trf("about {n} min", &[("n", &min)])
|
||||
} else {
|
||||
crate::i18n::trf(
|
||||
"about {h} h {m} min",
|
||||
&[("h", &(min / 60)), ("m", &(min % 60))],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "brilliant_tests.rs"]
|
||||
mod tests;
|
||||
|
|
@ -1,617 +0,0 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use game_review::CacheDir;
|
||||
|
||||
use super::*;
|
||||
|
||||
struct Dir(PathBuf);
|
||||
|
||||
impl Dir {
|
||||
fn new(name: &str) -> Dir {
|
||||
let path = std::env::temp_dir().join(format!("cp-brilliant-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(path.join("cache")).unwrap();
|
||||
Dir(path)
|
||||
}
|
||||
|
||||
fn cache(&self) -> PathBuf {
|
||||
self.0.join("cache")
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Dir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`).
|
||||
fn fake() -> PathBuf {
|
||||
let fake = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/debug/fake_uci");
|
||||
assert!(
|
||||
fake.exists(),
|
||||
"build the fake engine first: cargo build -p uci --bin fake_uci"
|
||||
);
|
||||
fake
|
||||
}
|
||||
|
||||
fn engine_at(path: &Path) -> Engine {
|
||||
Engine {
|
||||
config: uci::EngineConfig {
|
||||
// The second search of !! and ! (`searchmoves`), as Stockfish makes it.
|
||||
args: vec!["--searchmoves".into()],
|
||||
..uci::EngineConfig::new(path)
|
||||
},
|
||||
settings: JobSettings::new(2, None),
|
||||
fits: Box::new(|_| true),
|
||||
pause: std::time::Duration::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
/// An engine that cannot start: a pass that asks for it fails.
|
||||
fn no_engine(dir: &Dir) -> Engine {
|
||||
engine_at(&dir.0.join("no-such-engine"))
|
||||
}
|
||||
|
||||
const GAMES: &str = "[White \"Carlsen\"]\n[Black \"Kasparov\"]\n[Result \"*\"]\n\n1. e4 e5 2. Nf3 Nc6 *\n\n\
|
||||
[White \"Kasparov\"]\n[Black \"Carlsen\"]\n[Result \"*\"]\n\n1. d4 d5 2. c4 *\n\n\
|
||||
[White \"Anand\"]\n[Black \"Topalov\"]\n[Result \"*\"]\n\n1. e4 -- 2. d4 *\n\n\
|
||||
[White \"Anand\"]\n[Black \"Kramnik\"]\n[Result \"*\"]\n\n*\n";
|
||||
|
||||
fn source(dir: &Dir) -> (PathBuf, Database) {
|
||||
let path = dir.0.join("games.pgn");
|
||||
std::fs::write(&path, GAMES).unwrap();
|
||||
let db = chess_import::open(&path, &mut |_| {}, &AtomicBool::new(false))
|
||||
.unwrap()
|
||||
.db;
|
||||
(path, db)
|
||||
}
|
||||
|
||||
fn pass(
|
||||
db: &Database,
|
||||
records: &[u32],
|
||||
index: &Mutex<Index>,
|
||||
dir: &Dir,
|
||||
engine: &Engine,
|
||||
) -> PassEnd {
|
||||
let cache = dir.cache();
|
||||
run_pass(
|
||||
db,
|
||||
records,
|
||||
index,
|
||||
&CacheDir(&cache),
|
||||
engine,
|
||||
&Progress::default(),
|
||||
&AtomicBool::new(false),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_limit_is_one_hundred_games_inclusive() {
|
||||
assert_eq!(can_start(0), Err(Blocked::NoGames));
|
||||
assert_eq!(can_start(1), Ok(()));
|
||||
assert_eq!(can_start(LIMIT), Ok(()));
|
||||
assert_eq!(LIMIT, 100);
|
||||
assert_eq!(can_start(101), Err(Blocked::TooMany));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pass_analyses_keeps_the_index_and_takes_the_cache_next_time() {
|
||||
let dir = Dir::new("pass");
|
||||
let (path, db) = source(&dir);
|
||||
let before = std::fs::read(&path).unwrap();
|
||||
let file = dir.0.join("marks.json");
|
||||
let index = Mutex::new(Index::load(file.clone()));
|
||||
let end = pass(&db, &[0, 1, 2, 3], &index, &dir, &engine_at(&fake()));
|
||||
assert_eq!(end.outcome, Outcome::Finished);
|
||||
assert_eq!(end.reviewed, vec![0, 1]);
|
||||
assert_eq!(end.from_cache, 0);
|
||||
assert_eq!(end.skipped, vec![(2, Skip::NullMove), (3, Skip::NoMoves)]);
|
||||
// The index lives on: read anew (as after a restart) it has every record.
|
||||
let again = Index::load(file.clone());
|
||||
assert_eq!(again.len(), 4);
|
||||
let entry = again.get(0).unwrap();
|
||||
let game = db.load_game(0).unwrap().game;
|
||||
assert_eq!(entry.line, GameAnalysis::new(&game, None).cache_key());
|
||||
assert_eq!(again.get(2).unwrap().skip, Some(Skip::NullMove));
|
||||
// Again: from the cache, the engine is not asked (there is none now).
|
||||
let index = Mutex::new(again);
|
||||
let end = pass(&db, &[1, 0], &index, &dir, &no_engine(&dir));
|
||||
assert_eq!(end.outcome, Outcome::Finished);
|
||||
assert_eq!((end.reviewed, end.from_cache), (vec![1, 0], 2));
|
||||
// The source is only read.
|
||||
assert_eq!(std::fs::read(&path).unwrap(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_analysis_of_the_settings_of_before_counts_as_made() {
|
||||
let dir = Dir::new("stale");
|
||||
let (_, db) = source(&dir);
|
||||
let index = Mutex::new(Index::load(dir.0.join("marks.json")));
|
||||
pass(&db, &[0], &index, &dir, &engine_at(&fake()));
|
||||
// The cached analysis made «before the fixed search».
|
||||
for f in std::fs::read_dir(dir.cache()).unwrap() {
|
||||
let f = f.unwrap().path();
|
||||
let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(&f).unwrap()).unwrap();
|
||||
v["meta"]["search"] = serde_json::json!(0);
|
||||
std::fs::write(&f, serde_json::to_vec(&v).unwrap()).unwrap();
|
||||
}
|
||||
let end = pass(&db, &[0], &index, &dir, &no_engine(&dir));
|
||||
assert_eq!((end.outcome, end.from_cache), (Outcome::Finished, 1));
|
||||
assert!(index.lock().unwrap().get(0).unwrap().stale);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stopped_pass_keeps_what_it_analysed() {
|
||||
let dir = Dir::new("stop");
|
||||
let (_, db) = source(&dir);
|
||||
let file = dir.0.join("marks.json");
|
||||
let index = Mutex::new(Index::load(file.clone()));
|
||||
// Stopped when the second game's engine starts: the first one is kept.
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let starts = Arc::new(AtomicUsize::new(0));
|
||||
let (c, s) = (cancel.clone(), starts.clone());
|
||||
let engine = Engine {
|
||||
fits: Box::new(move |_| {
|
||||
if s.fetch_add(1, Ordering::Relaxed) >= 1 {
|
||||
c.store(true, Ordering::Relaxed);
|
||||
}
|
||||
true
|
||||
}),
|
||||
..engine_at(&fake())
|
||||
};
|
||||
let cache = dir.cache();
|
||||
let end = run_pass(
|
||||
&db,
|
||||
&[0, 1],
|
||||
&index,
|
||||
&CacheDir(&cache),
|
||||
&engine,
|
||||
&Progress::default(),
|
||||
&cancel,
|
||||
);
|
||||
assert_eq!(end.outcome, Outcome::Stopped);
|
||||
assert_eq!(end.reviewed, vec![0]);
|
||||
let kept = Index::load(file);
|
||||
assert!(kept.get(0).is_some() && kept.get(1).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starting_and_stopping_at_once_never_breaks_the_index() {
|
||||
let dir = Dir::new("race");
|
||||
let (_, db) = source(&dir);
|
||||
let db = Arc::new(db);
|
||||
let file = dir.0.join("marks.json");
|
||||
for round in 0..10 {
|
||||
let index = Arc::new(Mutex::new(Index::load(file.clone())));
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let (d, i, c, cache) = (db.clone(), index.clone(), cancel.clone(), dir.cache());
|
||||
let worker = std::thread::spawn(move || {
|
||||
run_pass(
|
||||
&d,
|
||||
&[0, 1, 2, 3],
|
||||
&i,
|
||||
&CacheDir(&cache),
|
||||
&engine_at(&fake()),
|
||||
&Progress::default(),
|
||||
&c,
|
||||
)
|
||||
});
|
||||
if round % 2 == 0 {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
cancel.store(true, Ordering::Relaxed);
|
||||
let end = worker.join().unwrap();
|
||||
assert!(matches!(end.outcome, Outcome::Stopped | Outcome::Finished));
|
||||
// The file is whole: it reads.
|
||||
if file.exists() {
|
||||
let bytes = std::fs::read(&file).unwrap();
|
||||
assert!(serde_json::from_slice::<serde_json::Value>(&bytes).is_ok());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_index_is_an_empty_one() {
|
||||
let dir = Dir::new("broken");
|
||||
let file = dir.0.join("marks.json");
|
||||
std::fs::write(&file, b"{not json").unwrap();
|
||||
assert_eq!(Index::load(file.clone()).len(), 0);
|
||||
std::fs::write(&file, br#"{"version":99,"records":[]}"#).unwrap();
|
||||
assert_eq!(Index::load(file).len(), 0);
|
||||
assert_eq!(Index::load(dir.0.join("none.json")).len(), 0);
|
||||
}
|
||||
|
||||
/// The entries of `index` made the database's own: their main lines are those of its
|
||||
/// games (as a pass writes them).
|
||||
fn fit(index: &mut Index, db: &Database) {
|
||||
let records: Vec<u32> = index.records().collect();
|
||||
for r in records {
|
||||
let mut e = index.get(r).unwrap().clone();
|
||||
e.line = GameAnalysis::new(&db.load_game(r as usize).unwrap().game, None).cache_key();
|
||||
index.set(r, e);
|
||||
}
|
||||
}
|
||||
|
||||
fn side(brilliant: u32, great: u32, blunders: u32, acpl: u32, accuracy: f64) -> SideMarks {
|
||||
SideMarks {
|
||||
counts: Counts {
|
||||
brilliant,
|
||||
great,
|
||||
blunders,
|
||||
..Counts::default()
|
||||
},
|
||||
acpl: Some(acpl),
|
||||
accuracy: Some(accuracy),
|
||||
}
|
||||
}
|
||||
|
||||
fn found(ply: u16, white: bool, number: u32, san: &str, brilliant: bool) -> Found {
|
||||
Found {
|
||||
ply,
|
||||
white,
|
||||
number,
|
||||
san: san.into(),
|
||||
brilliant,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn totals_count_only_the_filters_players_moves() {
|
||||
let mut index = Index::default();
|
||||
let entry = |white, black, found| Entry {
|
||||
line: String::new(),
|
||||
white,
|
||||
black,
|
||||
found,
|
||||
stale: false,
|
||||
skip: None,
|
||||
};
|
||||
index.set(
|
||||
0,
|
||||
entry(
|
||||
side(1, 0, 0, 20, 90.0),
|
||||
side(0, 2, 1, 40, 70.0),
|
||||
vec![
|
||||
found(40, true, 21, "Rxf7", true),
|
||||
found(13, false, 7, "Nd5", false),
|
||||
],
|
||||
),
|
||||
);
|
||||
index.set(
|
||||
1,
|
||||
entry(
|
||||
side(0, 0, 3, 60, 60.0),
|
||||
side(1, 1, 0, 10, 96.0),
|
||||
vec![found(67, false, 34, "Nf3+", true)],
|
||||
),
|
||||
);
|
||||
index.set(
|
||||
2,
|
||||
Entry {
|
||||
skip: Some(Skip::Chess960),
|
||||
..entry(SideMarks::default(), SideMarks::default(), Vec::new())
|
||||
},
|
||||
);
|
||||
let dir = Dir::new("totals");
|
||||
let (_, db) = source(&dir);
|
||||
fit(&mut index, &db);
|
||||
let all = totals(&index, &db, &[0, 1, 2], &Sides::default());
|
||||
assert_eq!(
|
||||
(all.games, all.sides, all.with_brilliant, all.with_great),
|
||||
(2, 4, 2, 2)
|
||||
);
|
||||
assert_eq!(
|
||||
all.counts,
|
||||
Counts {
|
||||
brilliant: 2,
|
||||
great: 3,
|
||||
blunders: 4,
|
||||
..Counts::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(all.acpl, Some(32.5));
|
||||
assert_eq!(all.accuracy_range, Some((60.0, 96.0)));
|
||||
assert_eq!(all.brilliant.len(), 2);
|
||||
// The player had White in game 0 and Black in game 1: only those sides count.
|
||||
let player = Sides {
|
||||
player: Some((vec![0], vec![1])),
|
||||
};
|
||||
let t = totals(&index, &db, &[0, 1, 2], &player);
|
||||
assert_eq!(
|
||||
(t.games, t.sides, t.with_brilliant, t.with_great),
|
||||
(2, 2, 2, 1)
|
||||
);
|
||||
assert_eq!(t.counts.blunders, 0);
|
||||
assert_eq!(t.acpl, Some(15.0));
|
||||
assert_eq!(t.accuracy, Some(93.0));
|
||||
assert_eq!(
|
||||
t.brilliant
|
||||
.iter()
|
||||
.map(|(r, f)| (*r, f.label()))
|
||||
.collect::<Vec<_>>(),
|
||||
[(0, "21.Rxf7!!".to_owned()), (1, "34…Nf3+!!".to_owned())]
|
||||
);
|
||||
// A player found on neither side is said.
|
||||
let nobody = Sides {
|
||||
player: Some((Vec::new(), Vec::new())),
|
||||
};
|
||||
assert_eq!(
|
||||
totals(&index, &db, &[0, 1], &nobody).player_missing,
|
||||
vec![0, 1]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_players_sides_come_from_the_filter() {
|
||||
let dir = Dir::new("sides");
|
||||
let (_, db) = source(&dir);
|
||||
let filter = chess_import::chessbase::base::Filter {
|
||||
player: chess_import::chessbase::base::NameFilter {
|
||||
text: "carlsen".into(),
|
||||
exact: None,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let sides = player_sides(&db, &filter, &AtomicBool::new(false));
|
||||
assert_eq!(sides.player, Some((vec![0], vec![1])));
|
||||
assert!(
|
||||
player_sides(&db, &Default::default(), &AtomicBool::new(false))
|
||||
.player
|
||||
.is_none()
|
||||
);
|
||||
let quick_search = chess_import::chessbase::base::Filter {
|
||||
text: "carlsen".into(),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(
|
||||
player_sides(&db, &quick_search, &AtomicBool::new(false))
|
||||
.player
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_game_hidden_by_another_condition_keeps_its_players_side() {
|
||||
let dir = Dir::new("hidden-sides");
|
||||
let (_, db) = source(&dir);
|
||||
let filter = chess_import::chessbase::base::Filter {
|
||||
player: chess_import::chessbase::base::NameFilter {
|
||||
text: "carlsen".into(),
|
||||
exact: None,
|
||||
},
|
||||
// None of the sample games has a year, so the filtered table is empty. The
|
||||
// manually selected Carlsen games nevertheless retain White and Black.
|
||||
year_from: Some(2020),
|
||||
..Default::default()
|
||||
};
|
||||
let sides = player_sides(&db, &filter, &AtomicBool::new(false));
|
||||
assert_eq!(sides.player, Some((vec![0], vec![1])));
|
||||
assert_eq!(sides.of(0), (true, false));
|
||||
assert_eq!(sides.of(1), (false, true));
|
||||
assert_eq!(sides.of(2), (false, false));
|
||||
|
||||
let mut white = filter.clone();
|
||||
white.side = chess_import::chessbase::base::Side::White;
|
||||
assert_eq!(
|
||||
player_sides(&db, &white, &AtomicBool::new(false)).player,
|
||||
Some((vec![0], Vec::new()))
|
||||
);
|
||||
let mut black = filter;
|
||||
black.side = chess_import::chessbase::base::Side::Black;
|
||||
assert_eq!(
|
||||
player_sides(&db, &black, &AtomicBool::new(false)).player,
|
||||
Some((Vec::new(), vec![1]))
|
||||
);
|
||||
}
|
||||
|
||||
/// White found a !! and Black a !: the row of a filter on the Black player shows !.
|
||||
fn two_sided() -> Index {
|
||||
let mut index = Index::default();
|
||||
index.set(
|
||||
0,
|
||||
Entry {
|
||||
line: String::new(),
|
||||
white: side(1, 0, 0, 10, 95.0),
|
||||
black: side(0, 1, 2, 40, 70.0),
|
||||
found: vec![
|
||||
found(20, true, 11, "Rxf7", true),
|
||||
found(23, false, 12, "Nd5", false),
|
||||
],
|
||||
stale: false,
|
||||
skip: None,
|
||||
},
|
||||
);
|
||||
index.set(
|
||||
1,
|
||||
Entry {
|
||||
found: Vec::new(),
|
||||
..index.get(0).unwrap().clone()
|
||||
},
|
||||
);
|
||||
index
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_column_counts_only_the_filters_players_moves() {
|
||||
let index = two_sided();
|
||||
let any = |_| true;
|
||||
let both = Sides::default();
|
||||
let black = Sides {
|
||||
player: Some((Vec::new(), vec![0])),
|
||||
};
|
||||
assert_eq!(index.rank(0, &both, &any), 0);
|
||||
assert_eq!(index.rank(0, &black, &any), 1);
|
||||
// A game where the player is on neither side has nothing of his.
|
||||
assert_eq!(index.rank(1, &black, &any), 2);
|
||||
let e = index.get(0).unwrap().for_sides(false, true);
|
||||
assert_eq!(e.of_sides(true, true).brilliant, 0);
|
||||
assert_eq!(e.of_sides(true, true).great, 1);
|
||||
assert_eq!(
|
||||
e.found.iter().map(Found::label).collect::<Vec<_>>(),
|
||||
["12…Nd5!"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_summary_keeps_the_original_snapshot_and_player_for_continue() {
|
||||
let dir = Dir::new("summary");
|
||||
let (path, db) = source(&dir);
|
||||
let filter = chess_import::chessbase::base::Filter {
|
||||
player: chess_import::chessbase::base::NameFilter {
|
||||
text: "carlsen".into(),
|
||||
exact: None,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let sides = player_sides(&db, &filter, &AtomicBool::new(false));
|
||||
let mut index = two_sided();
|
||||
fit(&mut index, &db);
|
||||
let mut original = vec![0, 1, 2];
|
||||
let selected = Some(SelectedGames {
|
||||
games: 3,
|
||||
hidden: 1,
|
||||
});
|
||||
// Record 0: Carlsen has White (its !!); record 1: Carlsen has Black (a !).
|
||||
let summary = crate::brilliant_ui::Summary::new(
|
||||
&path,
|
||||
&db,
|
||||
&index,
|
||||
&original,
|
||||
&sides,
|
||||
&filter,
|
||||
String::new(),
|
||||
selected,
|
||||
Some((2, 3)),
|
||||
Vec::new(),
|
||||
);
|
||||
// A later live selection has new records: neither the new record nor the changed
|
||||
// order can enter the continuation held by this summary.
|
||||
original.clear();
|
||||
original.push(3);
|
||||
assert_eq!(summary.filter, filter);
|
||||
assert_eq!(summary.rest, vec![2]);
|
||||
assert_eq!(summary.selected_games, selected);
|
||||
assert_eq!(
|
||||
(summary.totals.counts.brilliant, summary.totals.counts.great),
|
||||
(1, 1)
|
||||
);
|
||||
assert_eq!(summary.totals.counts.blunders, 2);
|
||||
assert_eq!(summary.player, Some(("carlsen".to_owned(), 1, 1)));
|
||||
assert_eq!(summary.rows.len(), 1);
|
||||
}
|
||||
|
||||
const FIVE: &str = "[White \"A\"]\n[Black \"B\"]\n[Result \"*\"]\n\n1. e4 e5 *\n\n\
|
||||
[White \"C\"]\n[Black \"D\"]\n[Result \"*\"]\n\n1. d4 d5 *\n\n\
|
||||
[White \"E\"]\n[Black \"F\"]\n[Result \"*\"]\n\n1. c4 e5 *\n\n\
|
||||
[White \"G\"]\n[Black \"H\"]\n[Result \"*\"]\n\n1. Nf3 d5 *\n\n\
|
||||
[White \"I\"]\n[Black \"J\"]\n[Result \"*\"]\n\n1. g3 g6 *\n";
|
||||
|
||||
/// A game deleted (the 2nd of 5): the records after it take other numbers, and none of
|
||||
/// them lends another game's marks — not in the summary, not in the sort; asked again,
|
||||
/// the entries are made anew from the cache.
|
||||
#[test]
|
||||
fn a_deleted_game_never_lends_its_marks() {
|
||||
let dir = Dir::new("deleted");
|
||||
let path = dir.0.join("five.pgn");
|
||||
std::fs::write(&path, FIVE).unwrap();
|
||||
let open = |p: &Path| {
|
||||
chess_import::open(p, &mut |_| {}, &AtomicBool::new(false))
|
||||
.unwrap()
|
||||
.db
|
||||
};
|
||||
let db = open(&path);
|
||||
let file = dir.0.join("marks.json");
|
||||
let index = Mutex::new(Index::load(file.clone()));
|
||||
pass(&db, &[0, 1, 2, 3, 4], &index, &dir, &engine_at(&fake()));
|
||||
// Each game marked: a !! of its own, told apart by its number.
|
||||
{
|
||||
let mut i = index.lock().unwrap();
|
||||
for r in 0..5u32 {
|
||||
let mut e = i.get(r).unwrap().clone();
|
||||
e.white.counts.brilliant = 1;
|
||||
e.found = vec![found(0, true, r + 1, "x", true)];
|
||||
i.set(r, e);
|
||||
}
|
||||
i.save().unwrap();
|
||||
}
|
||||
let without_second: String = FIVE
|
||||
.split("\n\n[")
|
||||
.enumerate()
|
||||
.filter(|(i, _)| *i != 1)
|
||||
.map(|(i, g)| {
|
||||
if i == 0 {
|
||||
g.to_owned()
|
||||
} else {
|
||||
format!("[{g}")
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n\n");
|
||||
std::fs::write(&path, without_second).unwrap();
|
||||
let db = open(&path);
|
||||
assert_eq!(db.len(), 4);
|
||||
let i = index.lock().unwrap();
|
||||
let t = totals(&i, &db, &[0, 1, 2, 3], &Sides::default());
|
||||
assert_eq!(t.games, 1);
|
||||
assert_eq!(
|
||||
t.brilliant
|
||||
.iter()
|
||||
.map(|(_, f)| f.number)
|
||||
.collect::<Vec<_>>(),
|
||||
[1]
|
||||
);
|
||||
assert!(current_entry(&i, &db, 1).is_none());
|
||||
assert_eq!(
|
||||
i.rank(1, &Sides::default(), &|r| current_entry(&i, &db, r)
|
||||
.is_some()),
|
||||
4
|
||||
);
|
||||
drop(i);
|
||||
// «Find» again: counted from the cache, the entries are the games' own again.
|
||||
let cache = dir.cache();
|
||||
let c = crate::brilliant_ui::count(
|
||||
&db,
|
||||
&[0, 1, 2, 3],
|
||||
&Default::default(),
|
||||
&cache,
|
||||
&index,
|
||||
&AtomicBool::new(false),
|
||||
);
|
||||
assert_eq!(c.reviewed, vec![0, 1, 2, 3]);
|
||||
let i = index.lock().unwrap();
|
||||
assert_eq!(totals(&i, &db, &[0, 1, 2, 3], &Sides::default()).games, 4);
|
||||
}
|
||||
|
||||
/// Games that cannot be analysed get «—» with the reason in the index.
|
||||
#[test]
|
||||
fn games_not_analysable_get_their_reason() {
|
||||
let dir = Dir::new("skips");
|
||||
let (_, db) = source(&dir);
|
||||
let index = Mutex::new(Index::load(dir.0.join("marks.json")));
|
||||
let c = crate::brilliant_ui::count(
|
||||
&db,
|
||||
&[2, 3],
|
||||
&Default::default(),
|
||||
&dir.cache(),
|
||||
&index,
|
||||
&AtomicBool::new(false),
|
||||
);
|
||||
assert_eq!(c.skipped, vec![(2, Skip::NullMove), (3, Skip::NoMoves)]);
|
||||
let i = index.lock().unwrap();
|
||||
assert_eq!(
|
||||
current_entry(&i, &db, 2).unwrap().skip,
|
||||
Some(Skip::NullMove)
|
||||
);
|
||||
assert_eq!(i.get(3).unwrap().skip, Some(Skip::NoMoves));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimates_are_said_plainly() {
|
||||
assert_eq!(format_estimate(30.0), "less than a minute");
|
||||
assert_eq!(format_estimate(14.0 * 60.0), "about 14 min");
|
||||
assert_eq!(format_estimate(80.0 * 60.0), "about 1 h 20 min");
|
||||
// The tester's measure: 3 games of 170 plies in 8 processes, 44 s.
|
||||
let secs = estimate_secs([56, 57, 57].into_iter(), 8);
|
||||
assert!((40.0..48.0).contains(&secs), "{secs}");
|
||||
}
|
||||
|
|
@ -1,776 +0,0 @@
|
|||
//! The windows of the search for great moves (task 27,
|
||||
//! docs/design/task-27-brilliant-search-2026-11-27.md): the question before a pass
|
||||
//! (§4.4) and the summary after it (§4.9).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{Receiver, channel};
|
||||
|
||||
use chess_import::Database;
|
||||
use chess_import::chessbase::base::Filter;
|
||||
use egui::{Key, RichText};
|
||||
use game_review::{GameAnalysis, Judgement};
|
||||
|
||||
use crate::brilliant::{Found, Index, SelectedGames, Sides, Skip, Totals};
|
||||
use crate::i18n::{tr, trf};
|
||||
|
||||
/// What a list holds before a pass: the records already analysed, those to analyse with
|
||||
/// their plies, those that cannot be, and the sides of the filter's player.
|
||||
pub struct Counted {
|
||||
pub reviewed: Vec<u32>,
|
||||
pub left: Vec<u32>,
|
||||
pub plies_left: Vec<usize>,
|
||||
pub skipped: Vec<(u32, Skip)>,
|
||||
pub sides: Sides,
|
||||
}
|
||||
|
||||
/// Counts what of `records` is analysed (the analysis cache in `cache`), on this thread.
|
||||
/// The index follows: a game analysed whose entry is missing or belongs to another game
|
||||
/// (one deleted or changed) gets its entry anew from the cache, a game that cannot be
|
||||
/// analysed gets «—» with the reason.
|
||||
pub fn count(
|
||||
db: &Database,
|
||||
records: &[u32],
|
||||
filter: &Filter,
|
||||
cache: &Path,
|
||||
index: &std::sync::Mutex<Index>,
|
||||
cancel: &AtomicBool,
|
||||
) -> Counted {
|
||||
let store = crate::review::Cache(cache.to_path_buf());
|
||||
let mut c = Counted {
|
||||
reviewed: Vec::new(),
|
||||
left: Vec::new(),
|
||||
plies_left: Vec::new(),
|
||||
skipped: Vec::new(),
|
||||
sides: crate::brilliant::player_sides(db, filter, cancel),
|
||||
};
|
||||
for &r in records {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
let set = |entry: crate::brilliant::Entry| {
|
||||
if let Ok(mut i) = index.lock()
|
||||
&& i.get(r) != Some(&entry)
|
||||
{
|
||||
i.set(r, entry);
|
||||
let _ = i.save();
|
||||
}
|
||||
};
|
||||
let Some(parsed) = db.load_game(r as usize) else {
|
||||
c.skipped.push((r, Skip::Unreadable));
|
||||
set(crate::brilliant::skipped_entry(
|
||||
String::new(),
|
||||
Skip::Unreadable,
|
||||
));
|
||||
continue;
|
||||
};
|
||||
let mut a = GameAnalysis::with_store(&parsed.game, Some(&store));
|
||||
if let Some(skip) = crate::brilliant::skip_of(&parsed.game, db.row(r as usize).chess960) {
|
||||
c.skipped.push((r, skip));
|
||||
set(crate::brilliant::skipped_entry(a.cache_key(), skip));
|
||||
continue;
|
||||
}
|
||||
let by_engine = a.has_data() && a.meta.as_ref().is_some_and(|m| m.nodes > 0);
|
||||
if by_engine && (a.stale() || a.missing() == 0) {
|
||||
c.reviewed.push(r);
|
||||
a.refresh(&parsed.game);
|
||||
set(crate::brilliant::entry_of(&a, &parsed.game));
|
||||
} else {
|
||||
c.left.push(r);
|
||||
c.plies_left.push(parsed.game.mainline().len());
|
||||
}
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
/// The question before a pass.
|
||||
pub struct StartDialog {
|
||||
pub source: PathBuf,
|
||||
pub records: Vec<u32>,
|
||||
pub filter: Filter,
|
||||
pub about: String,
|
||||
pub selected: Option<SelectedGames>,
|
||||
rx: Receiver<Counted>,
|
||||
cancel: Arc<AtomicBool>,
|
||||
pub counted: Option<Counted>,
|
||||
}
|
||||
|
||||
pub enum StartOutcome {
|
||||
Start,
|
||||
/// Every game is analysed already, or «Summary of the reviewed».
|
||||
Summary,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
/// One of the three fixed-height source rows: empty rows keep their place.
|
||||
fn source_line(ui: &mut egui::Ui, text: &str, weak: bool, hover: Option<&str>) {
|
||||
if text.is_empty() {
|
||||
return;
|
||||
}
|
||||
let text = RichText::new(text).size(12.0);
|
||||
let text = if weak { text.weak() } else { text };
|
||||
let response = ui.add(egui::Label::new(text).truncate());
|
||||
if let Some(hover) = hover {
|
||||
response.on_hover_text(hover);
|
||||
}
|
||||
}
|
||||
|
||||
impl StartDialog {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
ctx: &egui::Context,
|
||||
source: PathBuf,
|
||||
db: Arc<Database>,
|
||||
records: Vec<u32>,
|
||||
filter: Filter,
|
||||
about: String,
|
||||
selected: Option<SelectedGames>,
|
||||
cache: PathBuf,
|
||||
index: Arc<std::sync::Mutex<Index>>,
|
||||
) -> StartDialog {
|
||||
let (tx, rx) = channel();
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let (list, f, c, ctx) = (records.clone(), filter.clone(), cancel.clone(), ctx.clone());
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("brilliant-count".into())
|
||||
.spawn(move || {
|
||||
let _ = tx.send(count(&db, &list, &f, &cache, &index, &c));
|
||||
ctx.request_repaint();
|
||||
});
|
||||
StartDialog {
|
||||
source,
|
||||
records,
|
||||
filter,
|
||||
about,
|
||||
selected,
|
||||
rx,
|
||||
cancel,
|
||||
counted: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn show(&mut self, ctx: &egui::Context) -> Option<StartOutcome> {
|
||||
if self.counted.is_none()
|
||||
&& let Ok(c) = self.rx.try_recv()
|
||||
{
|
||||
// All analysed: no question, the summary at once.
|
||||
if c.left.is_empty() {
|
||||
self.counted = Some(c);
|
||||
return Some(StartOutcome::Summary);
|
||||
}
|
||||
self.counted = Some(c);
|
||||
}
|
||||
let mut out = None;
|
||||
let name = crate::own_db::base_name(&self.source);
|
||||
egui::Window::new(tr("Find great moves"))
|
||||
.id(egui::Id::new("brilliant_start"))
|
||||
.collapsible(false)
|
||||
.resizable(false)
|
||||
.anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
|
||||
.default_width(520.0)
|
||||
.show(ctx, |ui| {
|
||||
ui.set_width(520.0);
|
||||
let (source, hidden) = match self.selected {
|
||||
Some(selected) => (
|
||||
trf(
|
||||
"Selected: {games}",
|
||||
&[("games", &crate::i18n::games(selected.games))],
|
||||
),
|
||||
(selected.hidden > 0).then(|| {
|
||||
trf(
|
||||
"{k} hidden by the current filter",
|
||||
&[("k", &crate::large_db::grouped(selected.hidden))],
|
||||
)
|
||||
}),
|
||||
),
|
||||
None => (
|
||||
format!(
|
||||
"{} · {}",
|
||||
crate::i18n::games(self.records.len()),
|
||||
self.about
|
||||
),
|
||||
None,
|
||||
),
|
||||
};
|
||||
let player = (self.selected.is_some() && self.filter.player.is_set()).then(|| {
|
||||
let name = self.filter.player.text.trim();
|
||||
match self.filter.side {
|
||||
chess_import::chessbase::base::Side::White => trf(
|
||||
"Only the moves of «{name}» as White count.",
|
||||
&[("name", &name)],
|
||||
),
|
||||
chess_import::chessbase::base::Side::Black => trf(
|
||||
"Only the moves of «{name}» as Black count.",
|
||||
&[("name", &name)],
|
||||
),
|
||||
_ => trf("Only the moves of «{name}» count.", &[("name", &name)]),
|
||||
}
|
||||
});
|
||||
for (text, weak, hover) in [
|
||||
(format!("{name} · {source}"), true, None),
|
||||
(hidden.unwrap_or_default(), true, None),
|
||||
(
|
||||
player.unwrap_or_default(),
|
||||
false,
|
||||
self.filter.player.is_set().then(|| {
|
||||
tr(
|
||||
"The player condition limits the moves counted, but does not exclude selected games from review.",
|
||||
)
|
||||
}),
|
||||
),
|
||||
] {
|
||||
ui.allocate_ui(egui::vec2(520.0, 18.0), |ui| {
|
||||
source_line(ui, &text, weak, hover);
|
||||
});
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
// Two lines kept for the counts: the window does not jump when they come.
|
||||
ui.allocate_ui(egui::vec2(520.0, 60.0), |ui| match &self.counted {
|
||||
None => {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spinner();
|
||||
ui.label(tr("Counting the games already reviewed…"));
|
||||
});
|
||||
}
|
||||
Some(c) => {
|
||||
let secs = crate::brilliant::estimate_secs(
|
||||
c.plies_left.iter().copied(),
|
||||
crate::review::processes(),
|
||||
);
|
||||
ui.label(trf(
|
||||
"The engine will review {games} — {time}.",
|
||||
&[
|
||||
("games", &crate::i18n::games_object(c.left.len())),
|
||||
("time", &crate::brilliant::format_estimate(secs)),
|
||||
],
|
||||
));
|
||||
if !c.reviewed.is_empty() {
|
||||
let key = if crate::i18n::is_one(c.reviewed.len()) {
|
||||
"{games} is already reviewed: its marks come from the saved review."
|
||||
} else {
|
||||
"{games} are already reviewed: their marks come from the saved review."
|
||||
};
|
||||
ui.label(trf(key, &[("games", &crate::i18n::games(c.reviewed.len()))]));
|
||||
}
|
||||
// Why the list here is shorter than the table's.
|
||||
if !c.skipped.is_empty() {
|
||||
let mut reasons: Vec<&str> =
|
||||
c.skipped.iter().map(|(_, s)| s.reason()).collect();
|
||||
reasons.sort_unstable();
|
||||
reasons.dedup();
|
||||
ui.label(
|
||||
RichText::new(trf(
|
||||
"{k} cannot be reviewed ({reason})",
|
||||
&[("k", &c.skipped.len()), ("reason", &reasons.join(", "))],
|
||||
))
|
||||
.weak(),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
ui.label(trf(
|
||||
"The computer will be busy (up to {p} Stockfish 19 processes). You can keep working and stop at any time; the reviewed games are kept.",
|
||||
&[("p", &crate::review::processes())],
|
||||
));
|
||||
ui.add_space(8.0);
|
||||
// Its own height, not the window's: the buttons sit under the text.
|
||||
ui.horizontal(|ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let ready = self.counted.is_some();
|
||||
let start = ui.add_enabled(ready, egui::Button::new(tr("Start")));
|
||||
if start.clicked() || (ready && ui.input(|i| i.key_pressed(Key::Enter))) {
|
||||
out = Some(StartOutcome::Start);
|
||||
}
|
||||
if ui.button(tr("Cancel")).clicked() {
|
||||
out = Some(StartOutcome::Cancel);
|
||||
}
|
||||
if let Some(c) = &self.counted
|
||||
&& !c.reviewed.is_empty()
|
||||
&& ui
|
||||
.button(trf(
|
||||
"Summary of the reviewed ({k})",
|
||||
&[("k", &c.reviewed.len())],
|
||||
))
|
||||
.clicked()
|
||||
{
|
||||
out = Some(StartOutcome::Summary);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
if out.is_none() && ctx.input(|i| i.key_pressed(Key::Escape)) {
|
||||
out = Some(StartOutcome::Cancel);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for StartDialog {
|
||||
fn drop(&mut self) {
|
||||
self.cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// A row of the summary's list: a !! move of a game.
|
||||
pub struct BrilliantRow {
|
||||
pub record: u32,
|
||||
pub found: Found,
|
||||
/// «White — Black · result · event · date».
|
||||
pub game: String,
|
||||
}
|
||||
|
||||
/// The summary of a pass (§4.9), counted anew from the index for the pass's list.
|
||||
pub struct Summary {
|
||||
pub source: PathBuf,
|
||||
pub about: String,
|
||||
pub selected_games: Option<SelectedGames>,
|
||||
pub totals: Totals,
|
||||
/// The filter's player and the games counted for each colour.
|
||||
pub player: Option<(String, usize, usize)>,
|
||||
/// Stopped: analysed of all.
|
||||
pub stopped: Option<(usize, usize)>,
|
||||
/// Not analysed (for «Continue»).
|
||||
pub rest: Vec<u32>,
|
||||
pub skipped: Vec<(u32, Skip)>,
|
||||
pub rows: Vec<BrilliantRow>,
|
||||
pub selected: Option<usize>,
|
||||
/// The pass's filter: «Continue» goes on with it (its player's moves only).
|
||||
pub filter: Filter,
|
||||
}
|
||||
|
||||
pub enum SummaryAction {
|
||||
/// The game of a row chosen in the table behind.
|
||||
Select(u32),
|
||||
/// Open the game at the position after the move.
|
||||
Open {
|
||||
record: u32,
|
||||
ply: u16,
|
||||
},
|
||||
Continue {
|
||||
records: Vec<u32>,
|
||||
filter: Box<Filter>,
|
||||
},
|
||||
/// Sort the table by the «!!» column.
|
||||
Sort,
|
||||
Close,
|
||||
}
|
||||
|
||||
impl Summary {
|
||||
/// The summary of `records` (a pass's list, in its order) from `index`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
source: &Path,
|
||||
db: &Database,
|
||||
index: &Index,
|
||||
records: &[u32],
|
||||
sides: &Sides,
|
||||
filter: &Filter,
|
||||
about: String,
|
||||
selected: Option<SelectedGames>,
|
||||
stopped: Option<(usize, usize)>,
|
||||
skipped: Vec<(u32, Skip)>,
|
||||
) -> Summary {
|
||||
let totals = crate::brilliant::totals(index, db, records, sides);
|
||||
let rest = records
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|r| crate::brilliant::current_entry(index, db, *r).is_none())
|
||||
.collect();
|
||||
let player = sides.player.as_ref().map(|(w, b)| {
|
||||
let count = |v: &Vec<u32>| {
|
||||
records
|
||||
.iter()
|
||||
.filter(|r| v.binary_search(r).is_ok())
|
||||
.count()
|
||||
};
|
||||
(filter.player.text.trim().to_owned(), count(w), count(b))
|
||||
});
|
||||
let rows = totals
|
||||
.brilliant
|
||||
.iter()
|
||||
.map(|(r, f)| {
|
||||
let row = db.row(*r as usize);
|
||||
let mut parts = vec![format!("{} — {}", row.white, row.black)];
|
||||
parts.push(row.result.to_string());
|
||||
if !row.event.trim().is_empty() && row.event != "?" {
|
||||
parts.push(row.event.to_string());
|
||||
}
|
||||
let date = crate::library::display_date(&row.date);
|
||||
if !date.is_empty() {
|
||||
parts.push(date);
|
||||
}
|
||||
BrilliantRow {
|
||||
record: *r,
|
||||
found: f.clone(),
|
||||
game: parts.join(" · "),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Summary {
|
||||
source: source.to_path_buf(),
|
||||
about,
|
||||
selected_games: selected,
|
||||
totals,
|
||||
player,
|
||||
stopped,
|
||||
rest,
|
||||
skipped,
|
||||
rows,
|
||||
selected: None,
|
||||
filter: filter.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn show(&mut self, ctx: &egui::Context) -> Option<SummaryAction> {
|
||||
let mut out = None;
|
||||
// `CP_SUMMARY_CONTINUE=1`, `CP_SUMMARY_OPEN=<i>`: «Continue», or the i-th move of
|
||||
// «Games with !!» opened, once (checks without a mouse).
|
||||
static HOOK: std::sync::Once = std::sync::Once::new();
|
||||
let mut hook = None;
|
||||
HOOK.call_once(|| {
|
||||
if std::env::var_os("CP_SUMMARY_CONTINUE").is_some() && !self.rest.is_empty() {
|
||||
hook = Some(SummaryAction::Continue {
|
||||
records: self.rest.clone(),
|
||||
filter: Box::new(self.filter.clone()),
|
||||
});
|
||||
} else if let Some(row) = std::env::var("CP_SUMMARY_OPEN")
|
||||
.ok()
|
||||
.and_then(|i| i.parse::<usize>().ok())
|
||||
.and_then(|i| self.rows.get(i))
|
||||
{
|
||||
hook = Some(SummaryAction::Open {
|
||||
record: row.record,
|
||||
ply: row.found.ply,
|
||||
});
|
||||
}
|
||||
});
|
||||
if hook.is_some() {
|
||||
return hook;
|
||||
}
|
||||
let mut open = true;
|
||||
let t = &self.totals;
|
||||
let title = match self.stopped {
|
||||
Some((i, n)) if crate::i18n::is_one(i) => trf(
|
||||
"Search stopped · reviewed: {i} of {n} game",
|
||||
&[("i", &i), ("n", &n)],
|
||||
),
|
||||
Some((i, n)) => trf(
|
||||
"Search stopped · reviewed: {i} of {n}",
|
||||
&[("i", &i), ("n", &n)],
|
||||
),
|
||||
None => trf(
|
||||
"Summary · reviewed: {games}",
|
||||
&[("games", &crate::i18n::games(t.games))],
|
||||
),
|
||||
};
|
||||
let width = (ctx.content_rect().width() - 40.0).min(600.0);
|
||||
egui::Window::new(title)
|
||||
.id(egui::Id::new("brilliant_summary"))
|
||||
// In the middle: the «!!» column it sums up stays in sight.
|
||||
.pivot(egui::Align2::CENTER_CENTER)
|
||||
.default_pos(ctx.content_rect().center())
|
||||
.open(&mut open)
|
||||
.collapsible(false)
|
||||
.resizable(false)
|
||||
.default_width(width)
|
||||
.max_height(ctx.content_rect().height() - 80.0)
|
||||
.show(ctx, |ui| {
|
||||
ui.set_width(width);
|
||||
let weak = |ui: &mut egui::Ui, text: String| {
|
||||
ui.add(egui::Label::new(RichText::new(text).weak().size(12.0)).truncate())
|
||||
};
|
||||
let about = match self.selected_games {
|
||||
Some(selected) => trf(
|
||||
"Selected: {games}",
|
||||
&[("games", &crate::i18n::games(selected.games))],
|
||||
),
|
||||
None => self.about.clone(),
|
||||
};
|
||||
let subtitle = weak(
|
||||
ui,
|
||||
format!("{} · {about}", crate::own_db::base_name(&self.source)),
|
||||
);
|
||||
if let Some(selected) = self.selected_games
|
||||
&& selected.hidden > 0
|
||||
{
|
||||
subtitle.on_hover_text(trf(
|
||||
"Hidden by the filter at start: {k}",
|
||||
&[("k", &crate::large_db::grouped(selected.hidden))],
|
||||
));
|
||||
}
|
||||
if let Some((name, w, b)) = &self.player {
|
||||
weak(
|
||||
ui,
|
||||
trf(
|
||||
"Only the moves of «{name}» count: as White {w}, as Black {b}",
|
||||
&[("name", name), ("w", w), ("b", b)],
|
||||
),
|
||||
);
|
||||
}
|
||||
if !self.skipped.is_empty() {
|
||||
let reasons: Vec<&str> = {
|
||||
let mut r: Vec<&str> = self.skipped.iter().map(|(_, s)| s.reason()).collect();
|
||||
r.sort_unstable();
|
||||
r.dedup();
|
||||
r
|
||||
};
|
||||
weak(
|
||||
ui,
|
||||
trf(
|
||||
"Not reviewed: {k} ({reason})",
|
||||
&[("k", &self.skipped.len()), ("reason", &reasons.join(", "))],
|
||||
),
|
||||
);
|
||||
}
|
||||
if t.stale > 0 {
|
||||
weak(
|
||||
ui,
|
||||
trf(
|
||||
"{k} of them were reviewed with the previous engine settings",
|
||||
&[("k", &t.stale)],
|
||||
),
|
||||
);
|
||||
}
|
||||
if !t.player_missing.is_empty() {
|
||||
let numbers: Vec<String> =
|
||||
t.player_missing.iter().map(|r| (r + 1).to_string()).collect();
|
||||
ui.add(
|
||||
egui::Label::new(
|
||||
RichText::new(trf(
|
||||
"In {k} games the player was not found by name: their moves did not count",
|
||||
&[("k", &t.player_missing.len())],
|
||||
))
|
||||
.weak()
|
||||
.size(12.0),
|
||||
)
|
||||
.truncate(),
|
||||
)
|
||||
.on_hover_text(numbers.join(", "));
|
||||
}
|
||||
if self.stopped.is_some() && !self.rest.is_empty() {
|
||||
weak(
|
||||
ui,
|
||||
trf(
|
||||
"{k} games are not reviewed: «Continue» reviews only them",
|
||||
&[("k", &self.rest.len())],
|
||||
),
|
||||
);
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
let dark = ui.visuals().dark_mode;
|
||||
egui::Grid::new("brilliant_totals")
|
||||
.num_columns(2)
|
||||
.spacing([12.0, 4.0])
|
||||
.show(ui, |ui| {
|
||||
let c = &t.counts;
|
||||
for (j, n) in [
|
||||
(Judgement::Brilliant, c.brilliant),
|
||||
(Judgement::Great, c.great),
|
||||
(Judgement::Inaccuracy, c.inaccuracies),
|
||||
(Judgement::Mistake, c.mistakes),
|
||||
(Judgement::Blunder, c.blunders),
|
||||
] {
|
||||
let color = if n == 0 {
|
||||
ui.visuals().weak_text_color()
|
||||
} else {
|
||||
crate::review::judgement_text_color(j, dark)
|
||||
};
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.label(RichText::new(n.to_string()).strong().size(15.0).color(color));
|
||||
});
|
||||
ui.label(
|
||||
RichText::new(crate::review::judgement_plural(j))
|
||||
.size(15.0)
|
||||
.color(color),
|
||||
);
|
||||
ui.end_row();
|
||||
}
|
||||
let shown = |v: Option<String>| v.unwrap_or_else(|| "—".to_owned());
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.label(
|
||||
RichText::new(shown(t.acpl.map(|a| format!("{}", a.round() as i64))))
|
||||
.strong()
|
||||
.size(15.0),
|
||||
);
|
||||
});
|
||||
ui.label(RichText::new(tr("Average centipawn loss")).size(15.0));
|
||||
ui.end_row();
|
||||
let color = t
|
||||
.accuracy
|
||||
.map(|a| crate::review::accuracy_color(a, dark))
|
||||
.unwrap_or(ui.visuals().weak_text_color());
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.label(
|
||||
RichText::new(shown(t.accuracy.map(|a| format!("{}%", a.round() as i64))))
|
||||
.strong()
|
||||
.size(15.0)
|
||||
.color(color),
|
||||
);
|
||||
});
|
||||
let label = ui.label(RichText::new(tr("Average accuracy")).size(15.0));
|
||||
if let Some((lo, hi)) = t.accuracy_range {
|
||||
label.on_hover_text(trf(
|
||||
"Average over {k}: from {min}% to {max}%",
|
||||
&[
|
||||
("k", &crate::i18n::games(t.sides)),
|
||||
("min", &(lo.round() as i64)),
|
||||
("max", &(hi.round() as i64)),
|
||||
],
|
||||
));
|
||||
}
|
||||
ui.end_row();
|
||||
});
|
||||
ui.separator();
|
||||
if self.rows.is_empty() {
|
||||
if t.counts.great > 0 {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(
|
||||
RichText::new(tr(
|
||||
"No brilliant moves. Games with ! — sort by the «!!» column",
|
||||
))
|
||||
.weak(),
|
||||
);
|
||||
if ui.link(tr("Sort")).clicked() {
|
||||
out = Some(SummaryAction::Sort);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
ui.label(RichText::new(tr("No brilliant or great moves")).weak());
|
||||
}
|
||||
} else {
|
||||
ui.label(
|
||||
RichText::new(trf("Games with !! ({n})", &[("n", &self.rows.len())]))
|
||||
.strong()
|
||||
.size(13.0),
|
||||
);
|
||||
let teal = crate::review::judgement_text_color(Judgement::Brilliant, dark);
|
||||
let labels: Vec<String> = self.rows.iter().map(|r| r.found.label()).collect();
|
||||
let move_w = labels
|
||||
.iter()
|
||||
.map(|l| {
|
||||
ui.fonts_mut(|f| {
|
||||
f.layout_no_wrap(
|
||||
l.clone(),
|
||||
egui::TextStyle::Body.resolve(ui.style()),
|
||||
egui::Color32::WHITE,
|
||||
)
|
||||
.size()
|
||||
.x
|
||||
})
|
||||
})
|
||||
.fold(0.0, f32::max)
|
||||
+ 12.0;
|
||||
let rows = if ctx.content_rect().height() < 700.0 { 3 } else { 6 };
|
||||
egui::ScrollArea::vertical()
|
||||
.max_height(24.0 * rows as f32)
|
||||
.auto_shrink([false, true])
|
||||
.show_rows(ui, 24.0, self.rows.len(), |ui, range| {
|
||||
for i in range {
|
||||
let row = &self.rows[i];
|
||||
let selected = self.selected == Some(i);
|
||||
let (rect, resp) = ui.allocate_exact_size(
|
||||
egui::vec2(ui.available_width(), 24.0),
|
||||
egui::Sense::click(),
|
||||
);
|
||||
if selected {
|
||||
ui.painter().rect_filled(rect, 0.0, ui.visuals().selection.bg_fill);
|
||||
} else if resp.hovered() {
|
||||
ui.painter()
|
||||
.rect_filled(rect, 0.0, ui.visuals().widgets.hovered.weak_bg_fill);
|
||||
}
|
||||
let mut child = ui.new_child(
|
||||
egui::UiBuilder::new()
|
||||
.max_rect(rect.shrink2(egui::vec2(4.0, 0.0)))
|
||||
.layout(egui::Layout::left_to_right(egui::Align::Center)),
|
||||
);
|
||||
let color = if selected { ui.visuals().selection.stroke.color } else { teal };
|
||||
child.add_sized(
|
||||
egui::vec2(move_w, 24.0),
|
||||
egui::Label::new(RichText::new(&labels[i]).strong().color(color))
|
||||
.selectable(false),
|
||||
);
|
||||
child.add(egui::Label::new(&row.game).truncate().selectable(false));
|
||||
if resp.clicked() {
|
||||
self.selected = Some(i);
|
||||
out = Some(SummaryAction::Select(row.record));
|
||||
}
|
||||
if resp.double_clicked() {
|
||||
out = Some(SummaryAction::Open {
|
||||
record: row.record,
|
||||
ply: row.found.ply,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.label(
|
||||
RichText::new(tr(
|
||||
"Click: choose the row in the table; double click: open at this move",
|
||||
))
|
||||
.weak()
|
||||
.size(12.0),
|
||||
);
|
||||
// ↑ ↓ through the list, Enter opens.
|
||||
let (up, down, enter) = ui.input(|i| {
|
||||
(
|
||||
i.key_pressed(Key::ArrowUp),
|
||||
i.key_pressed(Key::ArrowDown),
|
||||
i.key_pressed(Key::Enter),
|
||||
)
|
||||
});
|
||||
if up || down {
|
||||
let last = self.rows.len() - 1;
|
||||
let next = match (self.selected, down) {
|
||||
(None, _) => 0,
|
||||
(Some(s), true) => (s + 1).min(last),
|
||||
(Some(s), false) => s.saturating_sub(1),
|
||||
};
|
||||
self.selected = Some(next);
|
||||
out = Some(SummaryAction::Select(self.rows[next].record));
|
||||
}
|
||||
if enter && let Some(s) = self.selected {
|
||||
out = Some(SummaryAction::Open {
|
||||
record: self.rows[s].record,
|
||||
ply: self.rows[s].found.ply,
|
||||
});
|
||||
}
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
// Its own height, not the window's: the buttons sit under the text.
|
||||
ui.horizontal(|ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button(tr("Close")).clicked() {
|
||||
out = Some(SummaryAction::Close);
|
||||
}
|
||||
if !self.rows.is_empty() {
|
||||
let pick = self.selected.map(|s| &self.rows[s]);
|
||||
if ui
|
||||
.add_enabled(pick.is_some(), egui::Button::new(tr("Open game")))
|
||||
.clicked()
|
||||
&& let Some(r) = pick
|
||||
{
|
||||
out = Some(SummaryAction::Open {
|
||||
record: r.record,
|
||||
ply: r.found.ply,
|
||||
});
|
||||
}
|
||||
}
|
||||
if self.stopped.is_some()
|
||||
&& !self.rest.is_empty()
|
||||
&& ui.button(tr("Continue")).clicked()
|
||||
{
|
||||
out = Some(SummaryAction::Continue {
|
||||
records: self.rest.clone(),
|
||||
filter: Box::new(self.filter.clone()),
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
if !open || (out.is_none() && ctx.input(|i| i.key_pressed(Key::Escape))) {
|
||||
out = Some(SummaryAction::Close);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
|
@ -18,8 +18,6 @@ pub const DOWNLOAD_INDICATOR: &str = "download_indicator";
|
|||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Pending {
|
||||
LiveAnalysis,
|
||||
/// The search for great moves in a database's list (task 27), waiting in the app.
|
||||
GreatMoves,
|
||||
/// The analysis of the game on the screen whose `serial` is `game` (no other game's);
|
||||
/// `full`: anew, over evaluations read from the PGN.
|
||||
GameAnalysis {
|
||||
|
|
@ -164,9 +162,6 @@ impl EngineOffer {
|
|||
Some(Pending::OpeningErrors { .. }) => {
|
||||
tr("Stockfish installed — the search for opening errors started")
|
||||
}
|
||||
Some(Pending::GreatMoves) => {
|
||||
tr("Stockfish installed — the search for great moves started")
|
||||
}
|
||||
None => tr("Stockfish installed"),
|
||||
}
|
||||
.to_string(),
|
||||
|
|
@ -399,9 +394,6 @@ impl EngineOffer {
|
|||
Some(Pending::OpeningErrors { .. }) => {
|
||||
tr("The search for opening errors will start by itself when the download finishes.")
|
||||
}
|
||||
Some(Pending::GreatMoves) => {
|
||||
tr("The search for great moves will start by itself when the download finishes.")
|
||||
}
|
||||
_ => tr("Analysis will start by itself when the download finishes."),
|
||||
};
|
||||
ui.label(RichText::new(after).weak());
|
||||
|
|
|
|||
|
|
@ -15,12 +15,10 @@ use crate::analysis::{self, Analysis, PvLine, Status};
|
|||
use crate::assets::Sound;
|
||||
use crate::board::{self, Arrow, BoardState, BoardView};
|
||||
use crate::notation::{
|
||||
CommentEditor, EditorOutcome, MOVE_NAGS, Notation, NotationCommand, ShapeCount, Slot,
|
||||
toggle_nag,
|
||||
CommentEditor, EditorOutcome, MOVE_NAGS, Notation, NotationCommand, Slot, toggle_nag,
|
||||
};
|
||||
use crate::review::{ReportAction, Review};
|
||||
use crate::settings::Settings;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Where an opened game came from (to return to the same library row, to save into).
|
||||
#[derive(Clone, Debug)]
|
||||
|
|
@ -106,9 +104,6 @@ pub struct GameView {
|
|||
/// The engine is busy with the opponent preparation: no game analysis meanwhile
|
||||
/// (one engine job for the whole program, opponent-prep.md §4.3).
|
||||
pub engine_busy: bool,
|
||||
/// Why, when another job than the search for opening errors has it (the search for
|
||||
/// great moves, task 27).
|
||||
pub engine_busy_why: Option<String>,
|
||||
/// The game's data were asked once (on its first add); not again.
|
||||
pub data_asked: bool,
|
||||
/// A newer version to offer (its number), next to Settings.
|
||||
|
|
@ -117,27 +112,6 @@ pub struct GameView {
|
|||
translation: crate::translate_ui::GameTranslation,
|
||||
/// "Translate comments" was chosen (menu, Ctrl+Shift+T): done once the settings are at hand.
|
||||
translate_now: bool,
|
||||
/// The moves whose comments draw on the board, for the notation's sign; by the
|
||||
/// revision of the game they were counted at.
|
||||
shape_counts: Option<(u64, HashMap<NodeId, ShapeCount>)>,
|
||||
/// The hint about drawing arrows above the notation: decided as the notation is
|
||||
/// first drawn (`None`: not yet).
|
||||
shapes_hint: Option<bool>,
|
||||
/// An arrow or a circle went into the game on this frame (the hint has done its job).
|
||||
shape_drawn: bool,
|
||||
/// Dev hook `CP_BEST_DELAY`: the better line to open after the notation is drawn.
|
||||
debug_best: Option<DebugBest>,
|
||||
}
|
||||
|
||||
/// The better line opened on a timer (screenshots of the notation before, during and
|
||||
/// after the line); times in seconds.
|
||||
struct DebugBest {
|
||||
shown: usize,
|
||||
delay: f64,
|
||||
exit: Option<f64>,
|
||||
/// When the notation was first drawn.
|
||||
start: Option<f64>,
|
||||
opened: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
|
|
@ -185,13 +159,6 @@ pub enum GameAction {
|
|||
OpenEngineSettings,
|
||||
OpenSettings,
|
||||
Toast(String),
|
||||
/// The analysis of a game of a database ended: its marks go into that database's
|
||||
/// index (task 27), so its row shows them.
|
||||
Reviewed {
|
||||
path: PathBuf,
|
||||
index: usize,
|
||||
entry: crate::brilliant::Entry,
|
||||
},
|
||||
/// A whole-game analysis started: pause the live engine (they would share the CPU).
|
||||
PauseLive,
|
||||
/// The whole-game analysis ended: resume the live engine if it was paused.
|
||||
|
|
@ -217,8 +184,6 @@ pub enum GameAction {
|
|||
DownloadPgn,
|
||||
/// Settings → Translation.
|
||||
OpenTranslationSettings,
|
||||
/// A hint was shown or put away: the settings are to be written.
|
||||
HintsChanged,
|
||||
}
|
||||
|
||||
impl GameView {
|
||||
|
|
@ -261,16 +226,11 @@ impl GameView {
|
|||
previous: None,
|
||||
previous_prep: false,
|
||||
engine_busy: false,
|
||||
engine_busy_why: None,
|
||||
data_asked: false,
|
||||
target: None,
|
||||
update: None,
|
||||
translation: Default::default(),
|
||||
translate_now: false,
|
||||
shape_counts: None,
|
||||
shapes_hint: None,
|
||||
shape_drawn: false,
|
||||
debug_best: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -705,116 +665,7 @@ impl GameView {
|
|||
}
|
||||
}
|
||||
let comments = chess_core::with_shapes(node.comments_after(), &arrows, &squares);
|
||||
if self
|
||||
.game
|
||||
.annotate(id, node.nags().to_vec(), comments)
|
||||
.is_ok()
|
||||
{
|
||||
self.shape_drawn = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// The moves with arrows or circles in their comments, counted again after an edit.
|
||||
fn shape_counts(&mut self) -> &HashMap<NodeId, ShapeCount> {
|
||||
let revision = self.game.revision();
|
||||
if self
|
||||
.shape_counts
|
||||
.as_ref()
|
||||
.is_none_or(|(r, _)| *r != revision)
|
||||
{
|
||||
self.shape_counts = Some((revision, crate::notation::shape_counts(&self.game)));
|
||||
}
|
||||
&self.shape_counts.get_or_insert_default().1
|
||||
}
|
||||
|
||||
/// Who this game is among those opened in the session (a hint counts a game once).
|
||||
fn session_key(&self) -> String {
|
||||
match &self.source {
|
||||
Some(s) => format!("{}#{}", s.path.display(), s.index),
|
||||
None => format!("view#{}", self.serial),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the hint about drawing on the board stands above the notation
|
||||
/// (docs/design/tasks-42-43-2026-11-27.md §43.3). Decided once, as the notation is
|
||||
/// first drawn: only where shapes go into the game, never with the translation strip
|
||||
/// (then not counted either). Returns whether the hint's settings changed.
|
||||
fn decide_shapes_hint(
|
||||
&mut self,
|
||||
hint: &mut crate::settings::Hint,
|
||||
seen: &mut std::collections::HashSet<String>,
|
||||
translating: bool,
|
||||
) -> bool {
|
||||
if self.shapes_hint.is_some() {
|
||||
return false;
|
||||
}
|
||||
let possible =
|
||||
!translating && self.preview.is_none() && self.play.is_none() && self.train.is_none();
|
||||
let key = self.session_key();
|
||||
let fresh = !seen.contains(&key);
|
||||
let show = possible && hint.offer(fresh);
|
||||
if show {
|
||||
seen.insert(key);
|
||||
}
|
||||
self.shapes_hint = Some(show);
|
||||
show && fresh
|
||||
}
|
||||
|
||||
/// The hint's strip: the translation strip's look, closed for good by its ×; dimmed
|
||||
/// (its height kept) while the board shows an engine line and takes no drawing.
|
||||
/// Returns whether the hint's settings changed.
|
||||
fn shapes_hint_strip(
|
||||
&mut self,
|
||||
ui: &mut Ui,
|
||||
hint: &mut crate::settings::Hint,
|
||||
dim: bool,
|
||||
) -> bool {
|
||||
let mut closed = false;
|
||||
egui::Frame::new()
|
||||
.fill(ui.visuals().faint_bg_color)
|
||||
.inner_margin(egui::Margin::symmetric(8, 4))
|
||||
.show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
let row_h = ui.spacing().interact_size.y;
|
||||
ui.horizontal_top(|ui| {
|
||||
let close_w = 22.0 + ui.spacing().item_spacing.x;
|
||||
ui.allocate_ui_with_layout(
|
||||
vec2((ui.available_width() - close_w).max(120.0), 0.0),
|
||||
egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true),
|
||||
|ui| {
|
||||
ui.set_min_height(row_h);
|
||||
ui.add_enabled_ui(!dim, |ui| {
|
||||
ui.add(
|
||||
egui::Label::new(tr(
|
||||
"Arrows and circles: drag or click with the right mouse button on the board. They are saved in the game.",
|
||||
))
|
||||
.wrap(),
|
||||
)
|
||||
.on_hover_text(tr(
|
||||
"No key — green, Shift — red, Alt — blue, Shift+Alt — yellow. Draw the same one again to remove it. Ctrl+Z undoes.",
|
||||
));
|
||||
});
|
||||
},
|
||||
);
|
||||
ui.allocate_ui_with_layout(
|
||||
vec2(22.0, row_h),
|
||||
egui::Layout::left_to_right(egui::Align::Center),
|
||||
|ui| {
|
||||
if crate::widgets::small_close_button(ui)
|
||||
.on_hover_text(tr("Don't show again"))
|
||||
.clicked()
|
||||
{
|
||||
closed = true;
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
if closed {
|
||||
hint.done = true;
|
||||
self.shapes_hint = Some(false);
|
||||
}
|
||||
closed
|
||||
let _ = self.game.annotate(id, node.nags().to_vec(), comments);
|
||||
}
|
||||
|
||||
/// Assessment of the move that led to the current position, for the board: the
|
||||
|
|
@ -874,26 +725,13 @@ impl GameView {
|
|||
) -> Vec<GameAction> {
|
||||
let mut actions = Vec::new();
|
||||
self.translation.update(ui.ctx(), &self.game, settings, hub);
|
||||
let reviewed = self.review.poll();
|
||||
if reviewed {
|
||||
if self.review.poll() {
|
||||
actions.push(GameAction::ResumeLive);
|
||||
if let Some(e) = &self.review.error {
|
||||
actions.push(GameAction::Toast(e.clone()));
|
||||
}
|
||||
}
|
||||
self.review.refresh(&self.game);
|
||||
if reviewed
|
||||
&& self.review.error.is_none()
|
||||
&& !self.game.is_modified()
|
||||
&& self.review.missing() == 0
|
||||
&& let Some(src) = &self.source
|
||||
{
|
||||
actions.push(GameAction::Reviewed {
|
||||
path: src.path.clone(),
|
||||
index: src.index,
|
||||
entry: crate::brilliant::entry_of(&self.review.analysis, &self.game),
|
||||
});
|
||||
}
|
||||
if analysis.status == Status::Running
|
||||
&& let Some(e) = settings.active_engine()
|
||||
{
|
||||
|
|
@ -975,28 +813,14 @@ impl GameView {
|
|||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
self.board_area(ui, &*settings, analysis, hover, &mut actions)
|
||||
});
|
||||
// Drawn on the board: the hint has done its job (gone after the button is let go).
|
||||
if std::mem::take(&mut self.shape_drawn) {
|
||||
let hint = &mut settings.hints.board_shapes;
|
||||
if !hint.done {
|
||||
hint.done = true;
|
||||
actions.push(GameAction::HintsChanged);
|
||||
}
|
||||
if self.shapes_hint == Some(true) {
|
||||
self.shapes_hint = Some(false);
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
self.sync_analysis(analysis);
|
||||
|
||||
// «Analyse»: at once — the search is the same for everyone, nothing to choose.
|
||||
if std::mem::take(&mut self.review_asked) {
|
||||
if self.engine_busy {
|
||||
actions.push(GameAction::Toast(
|
||||
self.engine_busy_why.clone().unwrap_or_else(|| {
|
||||
tr("Opening errors are being searched — wait or stop it in the report")
|
||||
.to_owned()
|
||||
}),
|
||||
tr("Opening errors are being searched — wait or stop it in the report")
|
||||
.to_owned(),
|
||||
));
|
||||
} else {
|
||||
self.start_review(false, ui.ctx(), &mut actions);
|
||||
|
|
@ -1092,18 +916,17 @@ impl GameView {
|
|||
.on_hover_text(tr(
|
||||
"Report: show or hide the evaluation graph and the report (Shift+A)",
|
||||
));
|
||||
} else if review_colored(ui, !self.engine_busy, |ui| {
|
||||
ui.add_enabled(!self.engine_busy, egui::Button::new(big("📈")))
|
||||
})
|
||||
.on_hover_text(format!(
|
||||
"{}\n{}",
|
||||
tr("Analyse game: accuracy, inaccuracies, mistakes, blunders (Shift+A)"),
|
||||
self.review.estimate()
|
||||
))
|
||||
.on_disabled_hover_text(self.engine_busy_why.clone().unwrap_or_else(|| {
|
||||
tr("Opening errors are being searched — wait or stop it in the report").to_owned()
|
||||
}))
|
||||
.clicked()
|
||||
} else if ui
|
||||
.add_enabled(!self.engine_busy, egui::Button::new(big("📈")))
|
||||
.on_hover_text(format!(
|
||||
"{}\n{}",
|
||||
tr("Analyse game: accuracy, inaccuracies, mistakes, blunders (Shift+A)"),
|
||||
self.review.estimate()
|
||||
))
|
||||
.on_disabled_hover_text(tr(
|
||||
"Opening errors are being searched — wait or stop it in the report",
|
||||
))
|
||||
.clicked()
|
||||
{
|
||||
self.review_asked = true;
|
||||
}
|
||||
|
|
@ -1602,7 +1425,6 @@ impl GameView {
|
|||
&& t.flash.is_none()
|
||||
&& self.cursor == self.game.line_end(NodeId::ROOT)
|
||||
}),
|
||||
temporary_shapes: self.play.is_some() || self.train.is_some(),
|
||||
show_coords: settings.show_coords,
|
||||
theme: settings.board_theme.theme(),
|
||||
pieces: settings.piece_set,
|
||||
|
|
@ -1729,26 +1551,11 @@ impl GameView {
|
|||
}
|
||||
return;
|
||||
}
|
||||
let strip_top = ui.cursor().top();
|
||||
let strip = if crate::platform::CAPS.translation {
|
||||
self.translation.strip(ui, settings, hub)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let translating = ui.cursor().top() > strip_top;
|
||||
let seen_id = egui::Id::new("shapes_hint_games");
|
||||
let mut seen: std::collections::HashSet<String> =
|
||||
ui.data_mut(|d| d.get_temp(seen_id)).unwrap_or_default();
|
||||
let mut hints_changed =
|
||||
self.decide_shapes_hint(&mut settings.hints.board_shapes, &mut seen, translating);
|
||||
ui.data_mut(|d| d.insert_temp(seen_id, seen));
|
||||
if self.shapes_hint == Some(true) && !translating {
|
||||
let dim = self.preview.is_some();
|
||||
hints_changed |= self.shapes_hint_strip(ui, &mut settings.hints.board_shapes, dim);
|
||||
}
|
||||
if hints_changed {
|
||||
actions.push(GameAction::HintsChanged);
|
||||
}
|
||||
match strip {
|
||||
Some(crate::translate_ui::StripAction::OpenSettings) => {
|
||||
actions.push(GameAction::OpenTranslationSettings)
|
||||
|
|
@ -1761,8 +1568,6 @@ impl GameView {
|
|||
if std::mem::take(&mut self.translate_now) {
|
||||
self.translation.translate(ui.ctx(), settings, hub);
|
||||
}
|
||||
self.shape_counts();
|
||||
self.debug_best_tick(ui.ctx());
|
||||
egui::ScrollArea::vertical()
|
||||
.auto_shrink(false)
|
||||
.show(ui, |ui| {
|
||||
|
|
@ -1780,7 +1585,6 @@ impl GameView {
|
|||
read_only: self.play.is_some(),
|
||||
dim_until: None,
|
||||
mistakes: None,
|
||||
shapes: self.shape_counts.as_ref().map(|(_, c)| c),
|
||||
}
|
||||
.show(ui);
|
||||
if let Some(id) = resp.clicked {
|
||||
|
|
@ -2344,50 +2148,6 @@ impl GameView {
|
|||
}
|
||||
}
|
||||
|
||||
/// `debug_best_line` `delay` s after the notation is first drawn; closed (as by a
|
||||
/// click on the game's move) `exit` s after it opened.
|
||||
pub fn debug_best_line_later(&mut self, shown: usize, delay: f64, exit: Option<f64>) {
|
||||
self.debug_best = Some(DebugBest {
|
||||
shown,
|
||||
delay,
|
||||
exit,
|
||||
start: None,
|
||||
opened: false,
|
||||
});
|
||||
}
|
||||
|
||||
fn debug_best_tick(&mut self, ctx: &egui::Context) {
|
||||
let Some(mut d) = self.debug_best.take() else {
|
||||
return;
|
||||
};
|
||||
let now = ctx.input(|i| i.time);
|
||||
let start = *d.start.get_or_insert(now);
|
||||
if !d.opened {
|
||||
if now - start >= d.delay {
|
||||
self.debug_best_line(d.shown);
|
||||
d.opened = true;
|
||||
d.start = Some(now);
|
||||
} else {
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64(
|
||||
d.delay - (now - start),
|
||||
));
|
||||
}
|
||||
self.debug_best = Some(d);
|
||||
return;
|
||||
}
|
||||
match d.exit {
|
||||
Some(exit) if now - start >= exit => {
|
||||
let base = self.cursor;
|
||||
self.goto(base);
|
||||
}
|
||||
Some(exit) => {
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64(exit - (now - start)));
|
||||
self.debug_best = Some(d);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the better line of the first engine-marked move up to its `shown`-th move.
|
||||
pub fn debug_best_line(&mut self, shown: usize) {
|
||||
let mark = self
|
||||
|
|
@ -3657,7 +3417,6 @@ impl GameView {
|
|||
.and_then(|s| self.game.node(s.floor))
|
||||
.map(|n| n.ply()),
|
||||
mistakes: None,
|
||||
shapes: None,
|
||||
}
|
||||
.show(ui);
|
||||
if let Some(id) = resp.clicked {
|
||||
|
|
@ -4122,21 +3881,6 @@ impl GameView {
|
|||
|
||||
/// Dev hook (`CP_SHAPE=Ge2e4,Rd5`): shapes drawn on the board at the current move.
|
||||
pub fn debug_shapes(&mut self, spec: &str) {
|
||||
let temporary = self.play.is_some() || self.train.is_some();
|
||||
let position = if temporary {
|
||||
self.game.position(self.cursor).cloned()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut record = |drawn| {
|
||||
if temporary {
|
||||
if let Some(pos) = &position {
|
||||
self.board.draw_temporary(drawn, pos);
|
||||
}
|
||||
} else {
|
||||
self.apply_shape(drawn);
|
||||
}
|
||||
};
|
||||
for item in spec.split(',').map(str::trim).filter(|s| !s.is_empty()) {
|
||||
let parsed = chess_core::parse_comment(&if item.len() > 3 {
|
||||
format!("[%cal {item}]")
|
||||
|
|
@ -4147,12 +3891,12 @@ impl GameView {
|
|||
match p {
|
||||
CommentPart::Annotation(Annotation::Arrows(list)) => {
|
||||
for (c, a, b) in list {
|
||||
record(board::Drawn::Arrow(c, a, b));
|
||||
self.apply_shape(board::Drawn::Arrow(c, a, b));
|
||||
}
|
||||
}
|
||||
CommentPart::Annotation(Annotation::Squares(list)) => {
|
||||
for (c, sq) in list {
|
||||
record(board::Drawn::Circle(c, sq));
|
||||
self.apply_shape(board::Drawn::Circle(c, sq));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
|
|
@ -4321,7 +4065,6 @@ impl GameView {
|
|||
editor: None,
|
||||
read_only: true,
|
||||
dim_until: None,
|
||||
shapes: None,
|
||||
mistakes: marks.as_ref(),
|
||||
}
|
||||
.show(ui);
|
||||
|
|
@ -4367,18 +4110,17 @@ impl GameView {
|
|||
.size(15.0),
|
||||
);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let white = pos.turn() == Color::White;
|
||||
let long = if white {
|
||||
tr("White to move")
|
||||
} else {
|
||||
tr("Black to move")
|
||||
let (short, long) = match pos.turn() {
|
||||
Color::White => ("♔", tr("♔ White to move")),
|
||||
Color::Black => ("♚", tr("♚ Black to move")),
|
||||
};
|
||||
// In a narrow panel the king alone says who moves.
|
||||
let narrow = ui.available_width() < 110.0;
|
||||
if !narrow {
|
||||
ui.label(RichText::new(long).strong().size(15.0));
|
||||
}
|
||||
ui.add(crate::widgets::side_king(white, 17.0).sense(egui::Sense::hover()))
|
||||
let text = if ui.available_width() < 110.0 {
|
||||
short
|
||||
} else {
|
||||
long
|
||||
};
|
||||
ui.label(RichText::new(text).strong().size(15.0))
|
||||
.on_hover_text(long);
|
||||
});
|
||||
});
|
||||
|
|
@ -5576,307 +5318,3 @@ fn paste_line_full(line: &[(u32, Color, String)]) -> String {
|
|||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
impl GameView {
|
||||
/// The report tab and the graph shown (a game opened at a move the search for great
|
||||
/// moves found).
|
||||
pub fn show_report(&mut self) {
|
||||
self.review.visible = true;
|
||||
self.side_tab = SideTab::Report;
|
||||
}
|
||||
}
|
||||
|
||||
/// «📈 Analyse game» in the colour of «!!» (task 26): the report it makes marks its finds
|
||||
/// with it. Hover and press stay visible (egui's own states, shaded); a disabled button
|
||||
/// keeps the usual look.
|
||||
fn review_colored(
|
||||
ui: &mut egui::Ui,
|
||||
enabled: bool,
|
||||
add: impl FnOnce(&mut egui::Ui) -> egui::Response,
|
||||
) -> egui::Response {
|
||||
if !enabled {
|
||||
return add(ui);
|
||||
}
|
||||
let dark = ui.visuals().dark_mode;
|
||||
let Some(fill) = crate::notation::assessment_text_color(Nag(3), dark) else {
|
||||
return add(ui);
|
||||
};
|
||||
// The icon dark on the dark theme's teal, white on the light one's (contrast ≥ 4.5:1).
|
||||
let icon = if dark {
|
||||
egui::Color32::from_rgb(0x1b, 0x1b, 0x1b)
|
||||
} else {
|
||||
egui::Color32::WHITE
|
||||
};
|
||||
let (hover, press) = if dark {
|
||||
(
|
||||
fill.lerp_to_gamma(egui::Color32::WHITE, 0.18),
|
||||
fill.lerp_to_gamma(egui::Color32::BLACK, 0.15),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
fill.lerp_to_gamma(egui::Color32::BLACK, 0.15),
|
||||
fill.lerp_to_gamma(egui::Color32::BLACK, 0.3),
|
||||
)
|
||||
};
|
||||
ui.scope(|ui| {
|
||||
let w = &mut ui.visuals_mut().widgets;
|
||||
for (state, color) in [
|
||||
(&mut w.inactive, fill),
|
||||
(&mut w.hovered, hover),
|
||||
(&mut w.active, press),
|
||||
] {
|
||||
state.weak_bg_fill = color;
|
||||
state.bg_fill = color;
|
||||
state.fg_stroke.color = icon;
|
||||
}
|
||||
add(ui)
|
||||
})
|
||||
.inner
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::settings::Hint;
|
||||
use std::collections::HashSet;
|
||||
|
||||
type Shapes = (Vec<(ShapeColor, Square, Square)>, Vec<(ShapeColor, Square)>);
|
||||
|
||||
fn view(pgn: &str) -> GameView {
|
||||
let parsed = chess_core::parse_str(pgn);
|
||||
GameView::new(parsed.game, None, parsed.diagnostics)
|
||||
}
|
||||
|
||||
/// The node reached by these moves from the start, through any variation.
|
||||
fn at(game: &Game, moves: &[&str]) -> NodeId {
|
||||
moves.iter().fold(NodeId::ROOT, |node, san| {
|
||||
*game
|
||||
.children(node)
|
||||
.iter()
|
||||
.find(|c| game.game_move(**c).is_some_and(|m| m.san == *san))
|
||||
.unwrap_or_else(|| panic!("no {san} after {node:?}"))
|
||||
})
|
||||
}
|
||||
|
||||
fn sq(s: &str) -> Square {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
fn arrow(color: ShapeColor, from: &str, to: &str) -> board::Drawn {
|
||||
board::Drawn::Arrow(color, sq(from), sq(to))
|
||||
}
|
||||
|
||||
fn shapes_at(game: &Game, id: NodeId) -> Shapes {
|
||||
chess_core::shapes(game.node(id).unwrap().comments_after())
|
||||
}
|
||||
|
||||
/// Written to PGN and read again: the shapes of the same node.
|
||||
fn reread(game: &Game, moves: &[&str]) -> Shapes {
|
||||
let text = chess_core::write_game(game, &Default::default());
|
||||
let back = chess_core::parse_str(&text).game;
|
||||
shapes_at(&back, at(&back, moves))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_goes_into_the_current_move_and_back_out() {
|
||||
let mut v = view("1. e4 e5 {Open game [%clk 0:05:00]} $1 2. Nf3 *");
|
||||
let e5 = at(&v.game, &["e4", "e5"]);
|
||||
v.goto(e5);
|
||||
v.apply_shape(arrow(ShapeColor::Green, "g1", "f3"));
|
||||
assert_eq!(
|
||||
shapes_at(&v.game, e5),
|
||||
(vec![(ShapeColor::Green, sq("g1"), sq("f3"))], vec![])
|
||||
);
|
||||
let node = v.game.node(e5).unwrap();
|
||||
assert_eq!(node.nags(), &[Nag(1)]);
|
||||
let text = node.comments_after().join(" ");
|
||||
assert!(
|
||||
text.contains("Open game") && text.contains("[%clk 0:05:00]"),
|
||||
"{text}"
|
||||
);
|
||||
assert_eq!(
|
||||
reread(&v.game, &["e4", "e5"]).0,
|
||||
vec![(ShapeColor::Green, sq("g1"), sq("f3"))]
|
||||
);
|
||||
|
||||
// Another colour repaints it, the same colour again takes it off.
|
||||
v.apply_shape(arrow(ShapeColor::Red, "g1", "f3"));
|
||||
assert_eq!(
|
||||
shapes_at(&v.game, e5).0,
|
||||
vec![(ShapeColor::Red, sq("g1"), sq("f3"))]
|
||||
);
|
||||
v.apply_shape(arrow(ShapeColor::Red, "g1", "f3"));
|
||||
assert!(shapes_at(&v.game, e5).0.is_empty());
|
||||
|
||||
// One step of undo per shape.
|
||||
v.game.undo();
|
||||
assert_eq!(
|
||||
shapes_at(&v.game, e5).0,
|
||||
vec![(ShapeColor::Red, sq("g1"), sq("f3"))]
|
||||
);
|
||||
v.game.undo();
|
||||
v.game.undo();
|
||||
assert_eq!(shapes_at(&v.game, e5), (vec![], vec![]));
|
||||
assert!(!v.game.is_modified());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circles_toggle_and_recolour() {
|
||||
let mut v = view("1. d4 *");
|
||||
let d4 = at(&v.game, &["d4"]);
|
||||
v.goto(d4);
|
||||
v.apply_shape(board::Drawn::Circle(ShapeColor::Green, sq("d5")));
|
||||
v.apply_shape(board::Drawn::Circle(ShapeColor::Blue, sq("e5")));
|
||||
v.apply_shape(board::Drawn::Circle(ShapeColor::Yellow, sq("d5")));
|
||||
assert_eq!(
|
||||
shapes_at(&v.game, d4).1,
|
||||
vec![(ShapeColor::Yellow, sq("d5")), (ShapeColor::Blue, sq("e5"))]
|
||||
);
|
||||
v.apply_shape(board::Drawn::Circle(ShapeColor::Blue, sq("e5")));
|
||||
assert_eq!(
|
||||
shapes_at(&v.game, d4).1,
|
||||
vec![(ShapeColor::Yellow, sq("d5"))]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_at_the_start_stays_with_the_start() {
|
||||
let mut v = view("{Intro} 1. e4 e5 *");
|
||||
v.apply_shape(arrow(ShapeColor::Blue, "e2", "e4"));
|
||||
assert_eq!(
|
||||
reread(&v.game, &[]).0,
|
||||
vec![(ShapeColor::Blue, sq("e2"), sq("e4"))]
|
||||
);
|
||||
let text = chess_core::write_game(&v.game, &Default::default());
|
||||
assert!(text.contains("Intro"), "{text}");
|
||||
assert!(shapes_at(&v.game, at(&v.game, &["e4"])).0.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_in_a_nested_variation_stays_there() {
|
||||
let mut v = view("1. e4 e5 (1... c5 2. Nf3 (2. c3 d5) 2... d6) 2. Nf3 *");
|
||||
let path = ["e4", "c5", "c3", "d5"];
|
||||
let d5 = at(&v.game, &path);
|
||||
v.goto(d5);
|
||||
v.apply_shape(arrow(ShapeColor::Green, "e4", "d5"));
|
||||
assert_eq!(
|
||||
reread(&v.game, &path).0,
|
||||
vec![(ShapeColor::Green, sq("e4"), sq("d5"))]
|
||||
);
|
||||
assert!(reread(&v.game, &["e4", "e5"]).0.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_after_a_null_move_and_from_a_fen_with_move_zero() {
|
||||
let mut v = view("1. e4 -- 2. d4 *");
|
||||
let null = at(&v.game, &["e4", "--"]);
|
||||
v.goto(null);
|
||||
v.apply_shape(board::Drawn::Circle(ShapeColor::Red, sq("d4")));
|
||||
assert_eq!(
|
||||
reread(&v.game, &["e4", "--"]).1,
|
||||
vec![(ShapeColor::Red, sq("d4"))]
|
||||
);
|
||||
|
||||
let mut v =
|
||||
view("[FEN \"4k3/8/8/8/8/8/8/4K3 b - - 0 0\"]\n[SetUp \"1\"]\n\n0... Kd7 1. Ke2 *");
|
||||
let kd7 = at(&v.game, &["Kd7"]);
|
||||
v.goto(kd7);
|
||||
v.apply_shape(arrow(ShapeColor::Yellow, "e1", "e2"));
|
||||
assert_eq!(
|
||||
reread(&v.game, &["Kd7"]).0,
|
||||
vec![(ShapeColor::Yellow, sq("e1"), sq("e2"))]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_drawn_marks_the_hint_done_and_counts_for_the_notation() {
|
||||
let mut v = view("1. e4 e5 {[%csl Gd5]} *");
|
||||
assert_eq!(v.shape_counts().len(), 1);
|
||||
let e4 = at(&v.game, &["e4"]);
|
||||
v.goto(e4);
|
||||
v.apply_shape(arrow(ShapeColor::Green, "g1", "f3"));
|
||||
assert!(v.shape_drawn);
|
||||
assert_eq!(
|
||||
v.shape_counts().get(&e4),
|
||||
Some(&ShapeCount {
|
||||
arrows: 1,
|
||||
circles: 0
|
||||
})
|
||||
);
|
||||
assert_eq!(v.shape_counts().len(), 2);
|
||||
v.game.undo();
|
||||
assert_eq!(v.shape_counts().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_hint_is_decided_once_per_game_and_not_beside_the_translation() {
|
||||
let mut hint = Hint::default();
|
||||
let mut seen = HashSet::new();
|
||||
|
||||
// With the translation strip: not shown, not counted.
|
||||
let mut v = view("1. e4 *");
|
||||
assert!(!v.decide_shapes_hint(&mut hint, &mut seen, true));
|
||||
assert_eq!(v.shapes_hint, Some(false));
|
||||
assert_eq!(hint.shown, 0);
|
||||
assert!(seen.is_empty());
|
||||
|
||||
// Decided on the first frame only.
|
||||
let mut v = view("1. e4 *");
|
||||
assert!(v.decide_shapes_hint(&mut hint, &mut seen, false));
|
||||
assert!(!v.decide_shapes_hint(&mut hint, &mut seen, false));
|
||||
assert_eq!((v.shapes_hint, hint.shown), (Some(true), 1));
|
||||
|
||||
// The same game opened again in the session: shown, not counted.
|
||||
let source = |index| GameSource {
|
||||
path: PathBuf::from("/tmp/a.pgn"),
|
||||
index,
|
||||
block: None,
|
||||
};
|
||||
let open = |index| {
|
||||
let mut v = view("1. e4 *");
|
||||
v.source = Some(source(index));
|
||||
v
|
||||
};
|
||||
let mut a = open(0);
|
||||
assert!(a.decide_shapes_hint(&mut hint, &mut seen, false));
|
||||
let mut again = open(0);
|
||||
assert!(!again.decide_shapes_hint(&mut hint, &mut seen, false));
|
||||
assert_eq!((again.shapes_hint, hint.shown), (Some(true), 2));
|
||||
|
||||
let mut b = open(1);
|
||||
b.decide_shapes_hint(&mut hint, &mut seen, false);
|
||||
assert_eq!(hint.shown, 3);
|
||||
// The third counted game opened again keeps the hint, uncounted.
|
||||
let mut b_again = open(1);
|
||||
assert!(!b_again.decide_shapes_hint(&mut hint, &mut seen, false));
|
||||
assert_eq!((b_again.shapes_hint, hint.shown), (Some(true), 3));
|
||||
// The fourth game: gone by itself.
|
||||
let mut c = open(2);
|
||||
assert!(!c.decide_shapes_hint(&mut hint, &mut seen, false));
|
||||
assert_eq!(c.shapes_hint, Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_hint_is_not_shown_while_playing_or_after_it_is_done() {
|
||||
let mut seen = HashSet::new();
|
||||
let mut hint = Hint {
|
||||
done: true,
|
||||
shown: 0,
|
||||
};
|
||||
let mut v = view("1. e4 *");
|
||||
v.decide_shapes_hint(&mut hint, &mut seen, false);
|
||||
assert_eq!(v.shapes_hint, Some(false));
|
||||
|
||||
let mut hint = Hint::default();
|
||||
let mut v = view("1. e4 *");
|
||||
v.preview = Some(Preview {
|
||||
base: NodeId::ROOT,
|
||||
root: Chess::default(),
|
||||
moves: Vec::new(),
|
||||
san: Vec::new(),
|
||||
shown: 0,
|
||||
});
|
||||
v.decide_shapes_hint(&mut hint, &mut seen, false);
|
||||
assert_eq!((v.shapes_hint, hint.shown), (Some(false), 0));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
763
apps/desktop/src/learning_branches.rs
Normal file
763
apps/desktop/src/learning_branches.rs
Normal file
|
|
@ -0,0 +1,763 @@
|
|||
use std::collections::HashMap;
|
||||
|
||||
use egui::{Align, Layout, RichText, Sense, Ui};
|
||||
use egui_extras::{Column, TableBuilder};
|
||||
use trainer::repertoire::{BranchLearningAnalytics, RepertoireId};
|
||||
|
||||
use crate::i18n::tr;
|
||||
|
||||
const HEADER_HEIGHT: f32 = 40.0;
|
||||
const ROW_HEIGHT: f32 = 32.0;
|
||||
const BODY_TEXT_SIZE: f32 = 14.0;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct BranchSelection {
|
||||
pub repertoire_id: RepertoireId,
|
||||
pub branch_root: Vec<String>,
|
||||
}
|
||||
|
||||
pub fn show(
|
||||
ui: &mut egui::Ui,
|
||||
rows: &[BranchLearningAnalytics],
|
||||
names: &HashMap<RepertoireId, String>,
|
||||
labels: &HashMap<(RepertoireId, Vec<String>), Vec<String>>,
|
||||
selected: &mut Option<BranchSelection>,
|
||||
) {
|
||||
ui.style_mut().interaction.selectable_labels = false;
|
||||
if rows.is_empty() {
|
||||
*selected = None;
|
||||
ui.label(tr("No branches in this scope"));
|
||||
return;
|
||||
}
|
||||
if selected
|
||||
.as_ref()
|
||||
.is_none_or(|selection| !rows.iter().any(|row| selection == &selection_for(row)))
|
||||
{
|
||||
*selected = Some(selection_for(&rows[0]));
|
||||
}
|
||||
|
||||
ui.add(
|
||||
egui::Label::new(tr(
|
||||
"Continuations to review. Shared moves may appear in several variations.",
|
||||
))
|
||||
.wrap(),
|
||||
);
|
||||
ui.add_space(6.0);
|
||||
let include_repertoire = include_repertoire_names(rows);
|
||||
let mut clicked = None;
|
||||
show_table(
|
||||
ui,
|
||||
rows,
|
||||
names,
|
||||
labels,
|
||||
include_repertoire,
|
||||
selected.as_ref(),
|
||||
&mut clicked,
|
||||
);
|
||||
if let Some(selection) = clicked {
|
||||
*selected = Some(selection);
|
||||
}
|
||||
|
||||
if let Some(selection) = selected.as_ref()
|
||||
&& let Some(row) = rows.iter().find(|row| selection == &selection_for(row))
|
||||
{
|
||||
ui.separator();
|
||||
show_details(ui, row, names, labels, include_repertoire);
|
||||
}
|
||||
}
|
||||
|
||||
fn selection_for(row: &BranchLearningAnalytics) -> BranchSelection {
|
||||
BranchSelection {
|
||||
repertoire_id: row.repertoire_id.clone(),
|
||||
branch_root: row.branch_root.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn include_repertoire_names(rows: &[BranchLearningAnalytics]) -> bool {
|
||||
rows.first().is_some_and(|first| {
|
||||
rows.iter()
|
||||
.any(|row| row.repertoire_id != first.repertoire_id)
|
||||
})
|
||||
}
|
||||
|
||||
fn san_path(
|
||||
row: &BranchLearningAnalytics,
|
||||
labels: &HashMap<(RepertoireId, Vec<String>), Vec<String>>,
|
||||
) -> String {
|
||||
let labels = labels.get(&(row.repertoire_id.clone(), row.branch_root.clone()));
|
||||
row.branch_root
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, uci)| {
|
||||
let label = labels.and_then(|labels| labels.get(index)).unwrap_or(uci);
|
||||
crate::san::show(label).into_owned()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
fn branch_text(
|
||||
row: &BranchLearningAnalytics,
|
||||
names: &HashMap<RepertoireId, String>,
|
||||
labels: &HashMap<(RepertoireId, Vec<String>), Vec<String>>,
|
||||
include_repertoire: bool,
|
||||
) -> String {
|
||||
let path = san_path(row, labels);
|
||||
if !include_repertoire {
|
||||
return if path.is_empty() {
|
||||
"—".to_owned()
|
||||
} else {
|
||||
path
|
||||
};
|
||||
}
|
||||
let name = names
|
||||
.get(&row.repertoire_id)
|
||||
.map_or_else(|| row.repertoire_id.as_str(), String::as_str);
|
||||
if path.is_empty() {
|
||||
name.to_owned()
|
||||
} else {
|
||||
format!("{name} · {path}")
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn show_table(
|
||||
ui: &mut Ui,
|
||||
rows: &[BranchLearningAnalytics],
|
||||
names: &HashMap<RepertoireId, String>,
|
||||
labels: &HashMap<(RepertoireId, Vec<String>), Vec<String>>,
|
||||
include_repertoire: bool,
|
||||
selected: Option<&BranchSelection>,
|
||||
clicked: &mut Option<BranchSelection>,
|
||||
) {
|
||||
let numeric_width = (ui.available_width() - 3.0 * ui.spacing().item_spacing.x) * 0.4 / 3.0;
|
||||
TableBuilder::new(ui)
|
||||
.id_salt("learning_branches")
|
||||
.striped(true)
|
||||
.sense(Sense::click())
|
||||
.max_scroll_height(192.0)
|
||||
.cell_layout(Layout::left_to_right(Align::Center))
|
||||
.column(Column::remainder().clip(true))
|
||||
.column(Column::exact(numeric_width).clip(true))
|
||||
.column(Column::exact(numeric_width).clip(true))
|
||||
.column(Column::exact(numeric_width).clip(true))
|
||||
.header(HEADER_HEIGHT, |mut header| {
|
||||
for (index, key) in ["Variation start", "Learnt", "Due now", "Accuracy"]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
header.col(|ui| {
|
||||
header_cell(ui, tr(key), index > 0);
|
||||
});
|
||||
}
|
||||
})
|
||||
.body(|body| {
|
||||
body.rows(ROW_HEIGHT, rows.len(), |mut table_row| {
|
||||
let row = &rows[table_row.index()];
|
||||
let selection = selection_for(row);
|
||||
table_row.set_selected(selected == Some(&selection));
|
||||
table_row.col(|ui| {
|
||||
let text = branch_text(row, names, labels, include_repertoire);
|
||||
text_cell(ui, &text, false).on_hover_text(text);
|
||||
});
|
||||
for value in [
|
||||
format!("{} / {}", row.summary.learnt, row.summary.total),
|
||||
row.summary.due.to_string(),
|
||||
format_percent(row.summary.accuracy_percent),
|
||||
] {
|
||||
table_row.col(|ui| {
|
||||
text_cell(ui, &value, true);
|
||||
});
|
||||
}
|
||||
if table_row.response().clicked() {
|
||||
*clicked = Some(selection);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn show_details(
|
||||
ui: &mut Ui,
|
||||
row: &BranchLearningAnalytics,
|
||||
names: &HashMap<RepertoireId, String>,
|
||||
labels: &HashMap<(RepertoireId, Vec<String>), Vec<String>>,
|
||||
include_repertoire: bool,
|
||||
) {
|
||||
let branch = branch_text(row, names, labels, include_repertoire);
|
||||
ui.add(egui::Label::new(RichText::new(&branch).strong().size(BODY_TEXT_SIZE)).wrap())
|
||||
.on_hover_text(branch);
|
||||
ui.add_space(4.0);
|
||||
let details = [
|
||||
(
|
||||
"Learnt moves",
|
||||
format!("{} / {}", row.summary.learnt, row.summary.total),
|
||||
),
|
||||
("Due now", row.summary.due.to_string()),
|
||||
("Not practised yet", row.summary.unseen.to_string()),
|
||||
("Accuracy", format_percent(row.summary.accuracy_percent)),
|
||||
];
|
||||
show_details_rows(ui, &details);
|
||||
}
|
||||
|
||||
fn show_details_rows(ui: &mut Ui, details: &[(&'static str, String)]) {
|
||||
let label_width = (ui.available_width() * 0.36).clamp(110.0, 160.0);
|
||||
TableBuilder::new(ui)
|
||||
.id_salt("learning_branches_details")
|
||||
.vscroll(false)
|
||||
.cell_layout(Layout::left_to_right(Align::Min))
|
||||
.column(Column::exact(label_width).clip(true))
|
||||
.column(Column::remainder().at_least(80.0).clip(true))
|
||||
.body(|body| {
|
||||
body.rows(36.0, details.len(), |mut row| {
|
||||
let (label, value) = &details[row.index()];
|
||||
row.col(|ui| {
|
||||
ui.add(
|
||||
egui::Label::new(RichText::new(tr(label)).weak().size(BODY_TEXT_SIZE))
|
||||
.wrap(),
|
||||
);
|
||||
});
|
||||
row.col(|ui| {
|
||||
ui.add(egui::Label::new(RichText::new(value).size(BODY_TEXT_SIZE)).wrap());
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn header_cell(ui: &mut Ui, text: &str, _numeric: bool) -> egui::Response {
|
||||
ui.add(egui::Label::new(RichText::new(text).strong().size(BODY_TEXT_SIZE)).wrap())
|
||||
}
|
||||
|
||||
fn text_cell(ui: &mut Ui, text: &str, _numeric: bool) -> egui::Response {
|
||||
ui.add(egui::Label::new(RichText::new(text).size(BODY_TEXT_SIZE)).truncate())
|
||||
}
|
||||
|
||||
fn format_percent(value: Option<f64>) -> String {
|
||||
value.map_or_else(|| "—".to_owned(), |value| format!("{value:.0} %"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use trainer::repertoire::{LearningAggregate, Repertoire};
|
||||
|
||||
use super::*;
|
||||
|
||||
const BASE: i64 = 1_800_000_000;
|
||||
|
||||
struct Fixture {
|
||||
rows: Vec<BranchLearningAnalytics>,
|
||||
names: HashMap<RepertoireId, String>,
|
||||
labels: HashMap<(RepertoireId, Vec<String>), Vec<String>>,
|
||||
}
|
||||
|
||||
fn fixture() -> Fixture {
|
||||
let first = Repertoire::default().id;
|
||||
let second = Repertoire::default().id;
|
||||
let branch_root = vec!["e2e4".to_owned(), "e7e5".to_owned()];
|
||||
let summary = LearningAggregate {
|
||||
total: 8,
|
||||
unseen: 2,
|
||||
learning: 2,
|
||||
learnt: 4,
|
||||
uncertain: 1,
|
||||
learnt_confident: 3,
|
||||
due: 3,
|
||||
learnt_percent: Some(50.0),
|
||||
accuracy_correct: 6,
|
||||
accuracy_wrong: 2,
|
||||
accuracy_attempts: 8,
|
||||
accuracy_percent: Some(75.0),
|
||||
..LearningAggregate::default()
|
||||
};
|
||||
let rows = vec![
|
||||
BranchLearningAnalytics {
|
||||
repertoire_id: first.clone(),
|
||||
branch_root: branch_root.clone(),
|
||||
summary: summary.clone(),
|
||||
last_independent_at: Some(BASE),
|
||||
},
|
||||
BranchLearningAnalytics {
|
||||
repertoire_id: second.clone(),
|
||||
branch_root: branch_root.clone(),
|
||||
summary,
|
||||
last_independent_at: Some(BASE),
|
||||
},
|
||||
];
|
||||
let names = HashMap::from([
|
||||
(first.clone(), "First".to_owned()),
|
||||
(second.clone(), "Second".to_owned()),
|
||||
]);
|
||||
let labels = HashMap::from([
|
||||
(
|
||||
(first, branch_root.clone()),
|
||||
vec!["1.e4".to_owned(), "1...e5".to_owned()],
|
||||
),
|
||||
((second, branch_root), vec!["1.e4".to_owned()]),
|
||||
]);
|
||||
Fixture {
|
||||
rows,
|
||||
names,
|
||||
labels,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn render(
|
||||
ctx: &egui::Context,
|
||||
width: f32,
|
||||
height: f32,
|
||||
time: f64,
|
||||
events: Vec<egui::Event>,
|
||||
rows: &[BranchLearningAnalytics],
|
||||
names: &HashMap<RepertoireId, String>,
|
||||
labels: &HashMap<(RepertoireId, Vec<String>), Vec<String>>,
|
||||
selected: &mut Option<BranchSelection>,
|
||||
) -> Vec<egui::epaint::ClippedShape> {
|
||||
let output = ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(width, height),
|
||||
)),
|
||||
time: Some(time),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
show(ui, rows, names, labels, selected);
|
||||
});
|
||||
},
|
||||
);
|
||||
let shapes = output.shapes.clone();
|
||||
output.drop_without_applying_deltas();
|
||||
shapes
|
||||
}
|
||||
|
||||
fn has_text(shapes: &[egui::epaint::ClippedShape], expected: &str) -> bool {
|
||||
shapes.iter().any(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text) => text.galley.text().replace('\n', " ") == expected,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
fn has_translated_text(shapes: &[egui::epaint::ClippedShape], key: &'static str) -> bool {
|
||||
crate::i18n::all_languages(key)
|
||||
.into_iter()
|
||||
.any(|translation| has_text(shapes, translation))
|
||||
}
|
||||
|
||||
fn text_position(shapes: &[egui::epaint::ClippedShape], expected: &str) -> Option<egui::Pos2> {
|
||||
shapes.iter().find_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text) if text.galley.text().replace('\n', " ") == expected => {
|
||||
Some(text.pos + egui::vec2(8.0, 6.0))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn text_occurrences(shapes: &[egui::epaint::ClippedShape], expected: &str) -> usize {
|
||||
shapes
|
||||
.iter()
|
||||
.filter(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text) => text.galley.text().replace('\n', " ") == expected,
|
||||
_ => false,
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
fn click(position: egui::Pos2) -> Vec<egui::Event> {
|
||||
vec![
|
||||
egui::Event::PointerMoved(position),
|
||||
egui::Event::PointerButton {
|
||||
pos: position,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed: true,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
},
|
||||
egui::Event::PointerButton {
|
||||
pos: position,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed: false,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn assert_bounds(shapes: &[egui::epaint::ClippedShape], width: f32, height: f32) {
|
||||
for clipped in shapes {
|
||||
let bounds = clipped.shape.visual_bounding_rect();
|
||||
if bounds.is_finite() && bounds.is_positive() {
|
||||
assert!(
|
||||
bounds.min.x >= -0.5
|
||||
&& bounds.min.y >= -0.5
|
||||
&& bounds.max.x <= width + 0.5
|
||||
&& bounds.max.y <= height + 0.5,
|
||||
"shape outside {width}x{height}: {bounds:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarized_shared_rows_are_not_deduplicated_and_labels_fall_back_to_uci() {
|
||||
let fixture = fixture();
|
||||
let ctx = egui::Context::default();
|
||||
let mut selected = None;
|
||||
let shapes = render(
|
||||
&ctx,
|
||||
1200.0,
|
||||
800.0,
|
||||
0.0,
|
||||
Vec::new(),
|
||||
&fixture.rows,
|
||||
&fixture.names,
|
||||
&fixture.labels,
|
||||
&mut selected,
|
||||
);
|
||||
assert_eq!(selected, Some(selection_for(&fixture.rows[0])));
|
||||
assert!(has_text(&shapes, "First · 1.e4 1...e5"));
|
||||
assert!(has_text(&shapes, "Second · 1.e4 e7e5"));
|
||||
|
||||
let names = fixture.names.clone();
|
||||
let shapes = render(
|
||||
&ctx,
|
||||
1200.0,
|
||||
800.0,
|
||||
1.0,
|
||||
Vec::new(),
|
||||
&fixture.rows[..1],
|
||||
&names,
|
||||
&fixture.labels,
|
||||
&mut selected,
|
||||
);
|
||||
assert!(has_text(&shapes, "1.e4 1...e5"));
|
||||
assert!(!has_text(&shapes, "First · 1.e4 1...e5"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unified_layout_stays_in_bounds_in_light_and_dark() {
|
||||
let fixture = fixture();
|
||||
for visuals in [egui::Visuals::light(), egui::Visuals::dark()] {
|
||||
for (width, height) in [(1400.0, 900.0), (960.0, 600.0), (640.0, 480.0)] {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_visuals(visuals.clone());
|
||||
let mut selected = None;
|
||||
for pass in 0..2 {
|
||||
let shapes = render(
|
||||
&ctx,
|
||||
width,
|
||||
height,
|
||||
pass as f64,
|
||||
Vec::new(),
|
||||
&fixture.rows,
|
||||
&fixture.names,
|
||||
&fixture.labels,
|
||||
&mut selected,
|
||||
);
|
||||
assert!(!shapes.is_empty());
|
||||
assert_bounds(&shapes, width, height);
|
||||
for key in [
|
||||
"Variation start",
|
||||
"Learnt",
|
||||
"Due now",
|
||||
"Accuracy",
|
||||
"Learnt moves",
|
||||
"Not practised yet",
|
||||
] {
|
||||
assert!(
|
||||
has_translated_text(&shapes, key),
|
||||
"missing header/detail {key}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headers_fit_accepted_matrix_in_russian_and_german() {
|
||||
let cases = [
|
||||
["Начало варианта", "Изучено", "Повторить", "Точность"],
|
||||
["Variantenanfang", "Gelernt", "Wiederholen", "Genauigkeit"],
|
||||
];
|
||||
for visuals in [egui::Visuals::light(), egui::Visuals::dark()] {
|
||||
for (width, height) in [(960.0, 600.0), (1400.0, 900.0)] {
|
||||
for headers in &cases {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_visuals(visuals.clone());
|
||||
let output = ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(width, height),
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
let numeric_width =
|
||||
(ui.available_width() - 3.0 * ui.spacing().item_spacing.x) * 0.4
|
||||
/ 3.0;
|
||||
let mut table = TableBuilder::new(ui)
|
||||
.id_salt("learning_branches_wide_header_test")
|
||||
.cell_layout(Layout::left_to_right(Align::Center))
|
||||
.column(Column::remainder().at_least(120.0).clip(true));
|
||||
for _ in 0..3 {
|
||||
table = table.column(Column::exact(numeric_width).clip(true));
|
||||
}
|
||||
table.header(HEADER_HEIGHT, |mut header| {
|
||||
for (index, key) in headers.iter().enumerate() {
|
||||
header.col(|ui| {
|
||||
header_cell(ui, tr(key), index > 0);
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
let shapes = output.shapes.clone();
|
||||
output.drop_without_applying_deltas();
|
||||
assert_bounds(&shapes, width, height);
|
||||
for expected in headers {
|
||||
let (rect, clip, lines) = shapes
|
||||
.iter()
|
||||
.find_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text)
|
||||
if text.galley.text().replace('\n', " ") == *expected =>
|
||||
{
|
||||
Some((
|
||||
egui::Rect::from_min_size(text.pos, text.galley.size()),
|
||||
clipped.clip_rect,
|
||||
text.galley.text().lines().count(),
|
||||
))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| {
|
||||
panic!("missing full header {expected} at {width}x{height}")
|
||||
});
|
||||
assert!(lines <= 2, "header wraps too much: {expected}");
|
||||
assert!(
|
||||
rect.min.x >= clip.min.x - 0.1
|
||||
&& rect.min.y >= clip.min.y - 0.1
|
||||
&& rect.max.x <= clip.max.x + 0.1
|
||||
&& rect.max.y <= clip.max.y + 0.1,
|
||||
"clipped header {expected} at {width}x{height}: {rect:?} {clip:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn details_are_visible_and_click_selects_the_branch() {
|
||||
let fixture = fixture();
|
||||
let ctx = egui::Context::default();
|
||||
let mut selected = None;
|
||||
let shapes = render(
|
||||
&ctx,
|
||||
640.0,
|
||||
480.0,
|
||||
0.0,
|
||||
Vec::new(),
|
||||
&fixture.rows,
|
||||
&fixture.names,
|
||||
&fixture.labels,
|
||||
&mut selected,
|
||||
);
|
||||
assert_eq!(selected, Some(selection_for(&fixture.rows[0])));
|
||||
let second = text_position(&shapes, "Second · 1.e4 e7e5")
|
||||
.expect("second branch row should be visible");
|
||||
let shapes = render(
|
||||
&ctx,
|
||||
640.0,
|
||||
480.0,
|
||||
1.0,
|
||||
click(second),
|
||||
&fixture.rows,
|
||||
&fixture.names,
|
||||
&fixture.labels,
|
||||
&mut selected,
|
||||
);
|
||||
assert_eq!(selected, Some(selection_for(&fixture.rows[1])));
|
||||
assert!(text_occurrences(&shapes, "Second · 1.e4 e7e5") >= 2);
|
||||
for key in ["Learnt moves", "Due now", "Not practised yet", "Accuracy"] {
|
||||
assert!(has_translated_text(&shapes, key), "missing detail {key}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn details_keep_long_labels_readable_at_all_widths() {
|
||||
let cases: Vec<Vec<(&str, String)>> = vec![
|
||||
vec![
|
||||
("Новый", "2".to_owned()),
|
||||
("Изучается", "1".to_owned()),
|
||||
("Изучено", "4".to_owned()),
|
||||
("Не подтверждено", "1".to_owned()),
|
||||
("К повторению", "3".to_owned()),
|
||||
("Точность", "75 %".to_owned()),
|
||||
("Последняя тренировка", "2026-11-04 08:26".to_owned()),
|
||||
],
|
||||
vec![
|
||||
("Neu", "2".to_owned()),
|
||||
("Wird gelernt", "1".to_owned()),
|
||||
("Gelernt", "4".to_owned()),
|
||||
("Nicht bestätigt", "1".to_owned()),
|
||||
("Fällig", "3".to_owned()),
|
||||
("Genauigkeit", "75 %".to_owned()),
|
||||
("Zuletzt trainiert", "2026-11-04 08:26".to_owned()),
|
||||
],
|
||||
];
|
||||
for visuals in [egui::Visuals::light(), egui::Visuals::dark()] {
|
||||
for width in [320.0, 360.0, 420.0, 640.0] {
|
||||
for details in &cases {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_visuals(visuals.clone());
|
||||
let mut expected_label_width = 0.0;
|
||||
let output = ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(width, 700.0),
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
expected_label_width =
|
||||
(ui.available_width() * 0.36).clamp(110.0, 160.0);
|
||||
show_details_rows(ui, details);
|
||||
});
|
||||
},
|
||||
);
|
||||
let shapes = output.shapes.clone();
|
||||
output.drop_without_applying_deltas();
|
||||
assert_bounds(&shapes, width, 700.0);
|
||||
for (label, _) in details {
|
||||
let (clip, lines) = shapes
|
||||
.iter()
|
||||
.find_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text)
|
||||
if text.galley.text().replace('\n', " ") == *label =>
|
||||
{
|
||||
Some((clipped.clip_rect, text.galley.text().lines().count()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| panic!("missing full label {label} at {width}"));
|
||||
assert!(
|
||||
(clip.width() - expected_label_width).abs() < 0.1,
|
||||
"label column at {width}: {clip:?}, expected {expected_label_width}: {label}"
|
||||
);
|
||||
assert!(lines <= 2, "label wraps too much at {width}: {label}");
|
||||
}
|
||||
assert!(has_text(&shapes, "2026-11-04 08:26"));
|
||||
assert!(has_text(&shapes, "75 %"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_accuracy_renders_as_dashes_in_table_and_details() {
|
||||
let fixture = fixture();
|
||||
let mut row = fixture.rows[0].clone();
|
||||
row.summary.accuracy_percent = None;
|
||||
row.summary.learnt_percent = None;
|
||||
row.last_independent_at = None;
|
||||
let names = HashMap::from([(row.repertoire_id.clone(), "Only".to_owned())]);
|
||||
let labels = HashMap::new();
|
||||
let ctx = egui::Context::default();
|
||||
let mut selected = None;
|
||||
let shapes = render(
|
||||
&ctx,
|
||||
640.0,
|
||||
480.0,
|
||||
0.0,
|
||||
Vec::new(),
|
||||
std::slice::from_ref(&row),
|
||||
&names,
|
||||
&labels,
|
||||
&mut selected,
|
||||
);
|
||||
let dashes = text_occurrences(&shapes, "—");
|
||||
assert!(
|
||||
dashes >= 2,
|
||||
"expected null accuracy in table and details: {dashes}"
|
||||
);
|
||||
assert_eq!(format_percent(None), "—");
|
||||
assert_eq!(format_percent(Some(75.0)), "75 %");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_selected_notation_wraps_in_details_and_row_retains_wide_column() {
|
||||
let mut fixture = fixture();
|
||||
fixture.rows.truncate(1);
|
||||
fixture.rows[0].branch_root = (0..40).map(|i| format!("move{i}")).collect();
|
||||
let notation: Vec<_> = (1..=40).map(|i| format!("{i}.Nf3")).collect();
|
||||
fixture.labels.insert(
|
||||
(
|
||||
fixture.rows[0].repertoire_id.clone(),
|
||||
fixture.rows[0].branch_root.clone(),
|
||||
),
|
||||
notation,
|
||||
);
|
||||
let expected = san_path(&fixture.rows[0], &fixture.labels);
|
||||
for width in [960.0, 1400.0] {
|
||||
let ctx = egui::Context::default();
|
||||
let mut selected = None;
|
||||
let shapes = render(
|
||||
&ctx,
|
||||
width,
|
||||
900.0,
|
||||
0.0,
|
||||
Vec::new(),
|
||||
&fixture.rows,
|
||||
&fixture.names,
|
||||
&fixture.labels,
|
||||
&mut selected,
|
||||
);
|
||||
assert_bounds(&shapes, width, 900.0);
|
||||
let texts: Vec<_> = shapes
|
||||
.iter()
|
||||
.filter_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text) if text.galley.text() == expected => {
|
||||
Some((clipped, text))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(texts.len(), 2, "table row and full selected notation");
|
||||
assert!(texts[0].0.clip_rect.width() >= width * 0.5);
|
||||
assert_eq!(
|
||||
texts[0].1.galley.rows.len(),
|
||||
1,
|
||||
"table notation stays on one line"
|
||||
);
|
||||
assert!(
|
||||
texts[1].1.galley.rows.len() > 1,
|
||||
"full selected notation wraps"
|
||||
);
|
||||
assert!(has_text(&shapes, "4 / 8"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_scope_clears_selection() {
|
||||
let fixture = fixture();
|
||||
let ctx = egui::Context::default();
|
||||
let mut selected = Some(selection_for(&fixture.rows[0]));
|
||||
let shapes = render(
|
||||
&ctx,
|
||||
640.0,
|
||||
480.0,
|
||||
0.0,
|
||||
Vec::new(),
|
||||
&[],
|
||||
&fixture.names,
|
||||
&fixture.labels,
|
||||
&mut selected,
|
||||
);
|
||||
assert_eq!(selected, None);
|
||||
assert!(has_translated_text(&shapes, "No branches in this scope"));
|
||||
}
|
||||
}
|
||||
507
apps/desktop/src/learning_charts.rs
Normal file
507
apps/desktop/src/learning_charts.rs
Normal file
|
|
@ -0,0 +1,507 @@
|
|||
use std::{collections::BTreeMap, fmt};
|
||||
|
||||
use egui::{
|
||||
Align2, Color32, FontId, Painter, Pos2, Rect, RichText, Sense, Shape, Stroke, Ui, Visuals,
|
||||
pos2, vec2,
|
||||
};
|
||||
use trainer::repertoire::{LearningSnapshot, ScheduledBuckets, SequenceHistograms};
|
||||
|
||||
use crate::i18n::tr;
|
||||
|
||||
const CHART_HEIGHT: f32 = 180.0;
|
||||
const HISTORY_DATE_HEIGHT: f32 = 18.0;
|
||||
const SCHEDULED_LABEL_HEIGHT: f32 = 40.0;
|
||||
const HISTOGRAM_LABEL_HEIGHT: f32 = 28.0;
|
||||
const MAX_HISTOGRAM_BARS: usize = 12;
|
||||
const WIDE_SEQUENCE_WIDTH: f32 = 900.0;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Marker {
|
||||
Circle,
|
||||
Square,
|
||||
Diamond,
|
||||
}
|
||||
|
||||
type HistorySeries = (Color32, Marker, fn(&LearningSnapshot) -> usize);
|
||||
|
||||
impl Marker {
|
||||
fn paint(self, painter: &Painter, center: Pos2, color: Color32) {
|
||||
match self {
|
||||
Self::Circle => {
|
||||
painter.circle_filled(center, 2.8, color);
|
||||
}
|
||||
Self::Square => {
|
||||
painter.rect_filled(Rect::from_center_size(center, vec2(5.2, 5.2)), 0.0, color);
|
||||
}
|
||||
Self::Diamond => {
|
||||
painter.add(Shape::convex_polygon(
|
||||
vec![
|
||||
pos2(center.x, center.y - 3.4),
|
||||
pos2(center.x + 3.4, center.y),
|
||||
pos2(center.x, center.y + 3.4),
|
||||
pos2(center.x - 3.4, center.y),
|
||||
],
|
||||
color,
|
||||
Stroke::NONE,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn history(ui: &mut Ui, snapshots: &[LearningSnapshot]) {
|
||||
if snapshots.is_empty() {
|
||||
return;
|
||||
}
|
||||
let palette = series_palette(ui.visuals());
|
||||
history_legend(ui, &palette);
|
||||
ui.add_space(4.0);
|
||||
|
||||
let mut ordered = snapshots.iter().collect::<Vec<_>>();
|
||||
ordered.sort_by_key(|snapshot| snapshot.as_of);
|
||||
let (Some(first), Some(last)) = (ordered.first(), ordered.last()) else {
|
||||
return;
|
||||
};
|
||||
let start = first.as_of;
|
||||
let end = last.as_of;
|
||||
let max_value = snapshots.iter().fold(0_usize, |max, snapshot| {
|
||||
max.max(snapshot.learning)
|
||||
.max(snapshot.learnt)
|
||||
.max(snapshot.uncertain)
|
||||
});
|
||||
|
||||
let (rect, painter) = chart_area(ui);
|
||||
let plot = plot_rect(&painter, rect, max_value, HISTORY_DATE_HEIGHT);
|
||||
draw_axes(&painter, plot, max_value, ui.visuals());
|
||||
|
||||
let series: [HistorySeries; 3] = [
|
||||
(palette[0], Marker::Circle, |snapshot| snapshot.learning),
|
||||
(palette[1], Marker::Square, |snapshot| snapshot.learnt),
|
||||
(palette[2], Marker::Diamond, |snapshot| snapshot.uncertain),
|
||||
];
|
||||
for (color, marker, value) in series {
|
||||
let points = ordered
|
||||
.iter()
|
||||
.map(|snapshot| {
|
||||
pos2(
|
||||
time_x(snapshot.as_of, start, end, plot.left(), plot.right()),
|
||||
value_y(value(snapshot), max_value, plot.top(), plot.bottom()),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if points.len() >= 2 {
|
||||
painter.add(Shape::line(points.clone(), Stroke::new(1.6, color)));
|
||||
}
|
||||
for point in points {
|
||||
marker.paint(&painter, point, color);
|
||||
}
|
||||
}
|
||||
|
||||
let text_color = ui.visuals().weak_text_color();
|
||||
if ordered.len() == 1 {
|
||||
painter.text(
|
||||
pos2(plot.center().x, rect.bottom()),
|
||||
Align2::CENTER_BOTTOM,
|
||||
&first.date,
|
||||
label_font(),
|
||||
text_color,
|
||||
);
|
||||
} else {
|
||||
painter.text(
|
||||
pos2(plot.left(), rect.bottom()),
|
||||
Align2::LEFT_BOTTOM,
|
||||
&first.date,
|
||||
label_font(),
|
||||
text_color,
|
||||
);
|
||||
painter.text(
|
||||
pos2(plot.right(), rect.bottom()),
|
||||
Align2::RIGHT_BOTTOM,
|
||||
&last.date,
|
||||
label_font(),
|
||||
text_color,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scheduled(ui: &mut Ui, buckets: ScheduledBuckets) {
|
||||
let rows = [
|
||||
(tr("Overdue").to_owned(), buckets.overdue),
|
||||
(tr("Today").to_owned(), buckets.today),
|
||||
(tr("Next 7 days").to_owned(), buckets.week),
|
||||
(tr("Next 30 days").to_owned(), buckets.month),
|
||||
(tr("Next 365 days").to_owned(), buckets.year),
|
||||
(tr("Later").to_owned(), buckets.later),
|
||||
];
|
||||
let color = series_palette(ui.visuals())[0];
|
||||
bar_chart(ui, &rows, color, SCHEDULED_LABEL_HEIGHT, 56.0);
|
||||
}
|
||||
|
||||
pub fn sequences(ui: &mut Ui, histograms: &SequenceHistograms) {
|
||||
let correct = histogram_rows(&histograms.correct_streak);
|
||||
let wrong = histogram_rows(&histograms.wrong_streak);
|
||||
let attempts = histogram_rows(&histograms.attempts);
|
||||
let palette = series_palette(ui.visuals());
|
||||
|
||||
if ui.available_width() >= WIDE_SEQUENCE_WIDTH {
|
||||
ui.columns(3, |columns| {
|
||||
sequence_chart(&mut columns[0], "Correct streak", &correct, palette[1]);
|
||||
sequence_chart(&mut columns[1], "Wrong streak", &wrong, palette[2]);
|
||||
sequence_chart(&mut columns[2], "Attempts", &attempts, palette[0]);
|
||||
});
|
||||
} else {
|
||||
sequence_chart(ui, "Correct streak", &correct, palette[1]);
|
||||
sequence_chart(ui, "Wrong streak", &wrong, palette[2]);
|
||||
sequence_chart(ui, "Attempts", &attempts, palette[0]);
|
||||
}
|
||||
}
|
||||
|
||||
fn history_legend(ui: &mut Ui, palette: &[Color32; 3]) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for (key, color, marker) in [
|
||||
("Still learning", palette[0], Marker::Circle),
|
||||
("Learnt moves", palette[1], Marker::Square),
|
||||
("Long overdue learnt moves", palette[2], Marker::Diamond),
|
||||
] {
|
||||
ui.horizontal(|ui| {
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(18.0, 12.0), Sense::hover());
|
||||
let painter = ui.painter().with_clip_rect(rect);
|
||||
let y = rect.center().y;
|
||||
painter.line_segment(
|
||||
[pos2(rect.left(), y), pos2(rect.right(), y)],
|
||||
Stroke::new(1.6, color),
|
||||
);
|
||||
marker.paint(&painter, rect.center(), color);
|
||||
ui.label(tr(key));
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn sequence_chart(ui: &mut Ui, title: &'static str, rows: &[(String, usize)], color: Color32) {
|
||||
ui.add(egui::Label::new(RichText::new(tr(title)).strong()).truncate());
|
||||
ui.add_space(4.0);
|
||||
bar_chart(ui, rows, color, HISTOGRAM_LABEL_HEIGHT, 38.0);
|
||||
ui.add_space(10.0);
|
||||
}
|
||||
|
||||
fn chart_area(ui: &mut Ui) -> (Rect, Painter) {
|
||||
let width = ui.available_width().max(1.0);
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(width, CHART_HEIGHT), Sense::hover());
|
||||
let painter = ui.painter().with_clip_rect(rect);
|
||||
(rect, painter)
|
||||
}
|
||||
|
||||
fn plot_rect(painter: &Painter, rect: Rect, max_value: usize, label_height: f32) -> Rect {
|
||||
let text_color = Color32::TRANSPARENT;
|
||||
let y_label_width = [max_value.to_string(), "0".to_owned()]
|
||||
.into_iter()
|
||||
.map(|label| {
|
||||
painter
|
||||
.layout_no_wrap(label, label_font(), text_color)
|
||||
.size()
|
||||
.x
|
||||
})
|
||||
.fold(0.0_f32, f32::max);
|
||||
let reserved = (y_label_width + 8.0).min((rect.width() - 32.0).max(0.0));
|
||||
let right = (rect.right() - 4.0).max(rect.left());
|
||||
let left = (rect.left() + reserved).min(right);
|
||||
let top = (rect.top() + 6.0).min(rect.bottom());
|
||||
let bottom = (rect.bottom() - label_height).max(top).min(rect.bottom());
|
||||
Rect::from_min_max(pos2(left, top), pos2(right, bottom))
|
||||
}
|
||||
|
||||
fn draw_axes(painter: &Painter, plot: Rect, max_value: usize, visuals: &Visuals) {
|
||||
let grid_color = visuals.weak_text_color().gamma_multiply(0.18);
|
||||
for y in [plot.top(), plot.center().y, plot.bottom()] {
|
||||
painter.line_segment(
|
||||
[pos2(plot.left(), y), pos2(plot.right(), y)],
|
||||
Stroke::new(1.0, grid_color),
|
||||
);
|
||||
}
|
||||
let axis_color = visuals.weak_text_color().gamma_multiply(0.55);
|
||||
painter.line_segment(
|
||||
[plot.left_top(), plot.left_bottom()],
|
||||
Stroke::new(1.0, axis_color),
|
||||
);
|
||||
painter.line_segment(
|
||||
[plot.left_bottom(), plot.right_bottom()],
|
||||
Stroke::new(1.0, axis_color),
|
||||
);
|
||||
let text_color = visuals.weak_text_color();
|
||||
painter.text(
|
||||
pos2(plot.left() - 6.0, plot.top()),
|
||||
Align2::RIGHT_TOP,
|
||||
max_value,
|
||||
label_font(),
|
||||
text_color,
|
||||
);
|
||||
painter.text(
|
||||
pos2(plot.left() - 6.0, plot.bottom()),
|
||||
Align2::RIGHT_BOTTOM,
|
||||
0,
|
||||
label_font(),
|
||||
text_color,
|
||||
);
|
||||
}
|
||||
|
||||
fn bar_chart(
|
||||
ui: &mut Ui,
|
||||
rows: &[(String, usize)],
|
||||
color: Color32,
|
||||
label_height: f32,
|
||||
max_bar_width: f32,
|
||||
) {
|
||||
let max_value = rows.iter().map(|(_, count)| *count).max().unwrap_or(0);
|
||||
let (rect, painter) = chart_area(ui);
|
||||
let plot = plot_rect(&painter, rect, max_value, label_height);
|
||||
draw_axes(&painter, plot, max_value, ui.visuals());
|
||||
if rows.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let slot_width = (plot.width() / rows.len() as f32).max(0.0);
|
||||
let text_color = ui.visuals().weak_text_color();
|
||||
for (index, (label, count)) in rows.iter().enumerate() {
|
||||
let center = plot.left() + (index as f32 + 0.5) * slot_width;
|
||||
if *count > 0 && max_value > 0 {
|
||||
let width = (slot_width - 6.0).max(0.0).min(max_bar_width);
|
||||
if width > 0.0 {
|
||||
let top = value_y(*count, max_value, plot.top(), plot.bottom());
|
||||
painter.rect_filled(
|
||||
Rect::from_min_max(
|
||||
pos2(center - width / 2.0, top),
|
||||
pos2(center + width / 2.0, plot.bottom()),
|
||||
),
|
||||
0.0,
|
||||
color,
|
||||
);
|
||||
}
|
||||
}
|
||||
let galley = painter.layout(label.clone(), label_font(), text_color, slot_width.max(1.0));
|
||||
painter.galley(
|
||||
pos2(
|
||||
center - galley.size().x / 2.0,
|
||||
rect.bottom() - galley.size().y,
|
||||
),
|
||||
galley,
|
||||
text_color,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn value_y(value: usize, max_value: usize, top: f32, bottom: f32) -> f32 {
|
||||
if max_value == 0 {
|
||||
return bottom;
|
||||
}
|
||||
let fraction = (value as f64 / max_value as f64).clamp(0.0, 1.0) as f32;
|
||||
bottom - (bottom - top) * fraction
|
||||
}
|
||||
|
||||
fn time_x(at: i64, start: i64, end: i64, left: f32, right: f32) -> f32 {
|
||||
if start == end {
|
||||
return (left + right) / 2.0;
|
||||
}
|
||||
let numerator = i128::from(at) - i128::from(start);
|
||||
let denominator = i128::from(end) - i128::from(start);
|
||||
let fraction = (numerator as f64 / denominator as f64).clamp(0.0, 1.0) as f32;
|
||||
left + (right - left) * fraction
|
||||
}
|
||||
|
||||
fn histogram_rows<K: Ord + fmt::Display>(histogram: &BTreeMap<K, usize>) -> Vec<(String, usize)> {
|
||||
if histogram.len() <= MAX_HISTOGRAM_BARS {
|
||||
return histogram
|
||||
.iter()
|
||||
.map(|(value, count)| (value.to_string(), *count))
|
||||
.collect();
|
||||
}
|
||||
|
||||
let mut rows = histogram
|
||||
.iter()
|
||||
.take(MAX_HISTOGRAM_BARS - 1)
|
||||
.map(|(value, count)| (value.to_string(), *count))
|
||||
.collect::<Vec<_>>();
|
||||
if let Some((value, _)) = histogram.iter().nth(MAX_HISTOGRAM_BARS - 1) {
|
||||
let count = histogram
|
||||
.iter()
|
||||
.skip(MAX_HISTOGRAM_BARS - 1)
|
||||
.fold(0_usize, |sum, (_, count)| sum.saturating_add(*count));
|
||||
rows.push((format!("{value}+"), count));
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
fn series_palette(visuals: &Visuals) -> [Color32; 3] {
|
||||
if visuals.dark_mode {
|
||||
[
|
||||
Color32::from_rgb(112, 184, 232),
|
||||
Color32::from_rgb(126, 200, 150),
|
||||
Color32::from_rgb(232, 174, 100),
|
||||
]
|
||||
} else {
|
||||
[
|
||||
Color32::from_rgb(35, 105, 155),
|
||||
Color32::from_rgb(45, 125, 80),
|
||||
Color32::from_rgb(170, 95, 35),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
fn label_font() -> FontId {
|
||||
FontId::proportional(12.0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use trainer::repertoire::{LearningSide, LocalDatePolicy, StatsScope};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn snapshot(
|
||||
at: i64,
|
||||
date: &str,
|
||||
learning: usize,
|
||||
learnt: usize,
|
||||
uncertain: usize,
|
||||
) -> LearningSnapshot {
|
||||
LearningSnapshot {
|
||||
date: date.to_owned(),
|
||||
scope: StatsScope::new(Vec::new(), LearningSide::White, at),
|
||||
as_of: at,
|
||||
timezone: LocalDatePolicy::UTC,
|
||||
total: learning + learnt,
|
||||
unseen: 0,
|
||||
learning,
|
||||
learnt,
|
||||
uncertain,
|
||||
due: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn input(width: f32, height: f32) -> egui::RawInput {
|
||||
egui::RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(width, height))),
|
||||
time: Some(0.0),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn value_scaling_has_stable_endpoints() {
|
||||
assert_eq!(value_y(0, 20, 10.0, 150.0), 150.0);
|
||||
assert_eq!(value_y(20, 20, 10.0, 150.0), 10.0);
|
||||
assert_eq!(value_y(10, 20, 10.0, 150.0), 80.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_scaling_stays_on_the_baseline() {
|
||||
assert_eq!(value_y(0, 0, 10.0, 150.0), 150.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_time_point_is_centered() {
|
||||
assert_eq!(time_x(42, 42, 42, 20.0, 220.0), 120.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_scaling_handles_the_full_timestamp_range() {
|
||||
assert_eq!(time_x(i64::MIN, i64::MIN, i64::MAX, 20.0, 220.0), 20.0);
|
||||
assert_eq!(time_x(i64::MAX, i64::MIN, i64::MAX, 20.0, 220.0), 220.0);
|
||||
let middle = time_x(0, i64::MIN, i64::MAX, 20.0, 220.0);
|
||||
assert!((middle - 120.0).abs() < 0.001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn histogram_tail_preserves_zero_and_total() {
|
||||
let histogram = (0_u64..25).map(|value| (value, 1_usize)).collect();
|
||||
let rows = histogram_rows(&histogram);
|
||||
assert_eq!(rows.len(), MAX_HISTOGRAM_BARS);
|
||||
assert_eq!(rows[0], ("0".to_owned(), 1));
|
||||
assert_eq!(rows.last(), Some(&("11+".to_owned(), 14)));
|
||||
assert_eq!(rows.iter().map(|(_, count)| count).sum::<usize>(), 25);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_snapshot_paints_a_visible_marker() {
|
||||
let snapshots = [snapshot(42, "2026-11-04", 2, 3, 1)];
|
||||
let ctx = egui::Context::default();
|
||||
let output = ctx.run_ui(input(640.0, 480.0), |ui| history(ui, &snapshots));
|
||||
assert!(
|
||||
output
|
||||
.shapes
|
||||
.iter()
|
||||
.any(|clipped| matches!(&clipped.shape, Shape::Circle(_)))
|
||||
);
|
||||
output.drop_without_applying_deltas();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn charts_render_wide_narrow_light_and_dark_without_horizontal_overflow() {
|
||||
let snapshots = vec![
|
||||
snapshot(100, "2026-11-02", 8, 2, 0),
|
||||
snapshot(200, "2026-11-03", 5, 5, 1),
|
||||
snapshot(300, "2026-11-04", 3, 9, 2),
|
||||
];
|
||||
let scheduled_buckets = ScheduledBuckets {
|
||||
overdue: 4,
|
||||
today: 2,
|
||||
week: 7,
|
||||
month: 3,
|
||||
year: 5,
|
||||
later: 1,
|
||||
};
|
||||
let histograms = SequenceHistograms {
|
||||
correct_streak: (0_u32..18).map(|key| (key, 2)).collect(),
|
||||
wrong_streak: BTreeMap::from([(0, 8), (1, 3), (2, 1)]),
|
||||
attempts: (0_u64..16).map(|key| (key, 1)).collect(),
|
||||
};
|
||||
|
||||
for visuals in [Visuals::light(), Visuals::dark()] {
|
||||
for (width, height) in [(1400.0, 900.0), (640.0, 480.0)] {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_visuals(visuals.clone());
|
||||
for _ in 0..2 {
|
||||
let output = ctx.run_ui(input(width, height), |ui| {
|
||||
history(ui, &snapshots);
|
||||
ui.separator();
|
||||
scheduled(ui, scheduled_buckets);
|
||||
ui.separator();
|
||||
sequences(ui, &histograms);
|
||||
});
|
||||
assert!(!output.shapes.is_empty());
|
||||
for clipped in &output.shapes {
|
||||
let bounds = clipped
|
||||
.shape
|
||||
.visual_bounding_rect()
|
||||
.intersect(clipped.clip_rect);
|
||||
if bounds.is_finite() && bounds.is_positive() {
|
||||
assert!(
|
||||
bounds.min.x >= -0.5 && bounds.max.x <= width + 0.5,
|
||||
"horizontal overflow at {width}x{height}: {bounds:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
output.drop_without_applying_deltas();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_and_all_zero_inputs_render() {
|
||||
let zero_histograms = SequenceHistograms {
|
||||
correct_streak: BTreeMap::from([(0, 0)]),
|
||||
wrong_streak: BTreeMap::from([(0, 0)]),
|
||||
attempts: BTreeMap::from([(0_u64, 0)]),
|
||||
};
|
||||
let ctx = egui::Context::default();
|
||||
let output = ctx.run_ui(input(640.0, 480.0), |ui| {
|
||||
history(ui, &[]);
|
||||
scheduled(ui, ScheduledBuckets::default());
|
||||
sequences(ui, &SequenceHistograms::default());
|
||||
sequences(ui, &zero_histograms);
|
||||
});
|
||||
assert!(!output.shapes.is_empty());
|
||||
output.drop_without_applying_deltas();
|
||||
}
|
||||
}
|
||||
204
apps/desktop/src/learning_context_controls.rs
Normal file
204
apps/desktop/src/learning_context_controls.rs
Normal file
|
|
@ -0,0 +1,204 @@
|
|||
use trainer::repertoire::LearningContextPolicy;
|
||||
|
||||
use crate::i18n::tr;
|
||||
|
||||
fn hint(ui: &mut egui::Ui, text: &'static str) {
|
||||
ui.add(egui::Label::new(egui::RichText::new(tr(text)).weak()).wrap());
|
||||
}
|
||||
|
||||
pub fn show(ui: &mut egui::Ui, policy: &mut LearningContextPolicy) -> bool {
|
||||
let before = *policy;
|
||||
ui.strong(tr("Moves before the task"));
|
||||
hint(ui, "The app shows the moves leading to the task position.");
|
||||
ui.add_space(6.0);
|
||||
ui.checkbox(
|
||||
&mut policy.consider_leadup_moves,
|
||||
tr("Ask me to play preceding moves"),
|
||||
);
|
||||
ui.add_enabled_ui(
|
||||
policy.consider_leadup_moves || !policy.use_fixed_piece_speed,
|
||||
|ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(tr("Correct answers in a row"));
|
||||
ui.add(
|
||||
egui::DragValue::new(&mut policy.reinforce_minimum_correct).range(0..=u32::MAX),
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
hint(
|
||||
ui,
|
||||
"Ask until this streak is reached. This also sets the maximum acceleration point for adaptive playback.",
|
||||
);
|
||||
ui.add_space(6.0);
|
||||
ui.add_enabled_ui(policy.consider_leadup_moves, |ui| {
|
||||
let mut enabled = policy.reinforce_minimum_days.is_some();
|
||||
if ui
|
||||
.checkbox(&mut enabled, tr("Review ahead of schedule"))
|
||||
.changed()
|
||||
{
|
||||
policy.reinforce_minimum_days = enabled.then_some(7);
|
||||
}
|
||||
ui.add_enabled_ui(enabled, |ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(tr("Days before the due date"));
|
||||
let mut days = policy.reinforce_minimum_days.unwrap_or(7);
|
||||
if ui
|
||||
.add(egui::DragValue::new(&mut days).range(0..=u32::MAX))
|
||||
.changed()
|
||||
{
|
||||
policy.reinforce_minimum_days = Some(days);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
hint(ui, "Also ask moves that are already due.");
|
||||
ui.add_space(10.0);
|
||||
ui.separator();
|
||||
ui.strong(tr("Skip a familiar opening"));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(tr("Skip after this many correct answers in a row"));
|
||||
ui.add(
|
||||
egui::DragValue::new(&mut policy.dont_show_start_moves_threshold).range(0..=u32::MAX),
|
||||
);
|
||||
});
|
||||
hint(
|
||||
ui,
|
||||
"Each of your opening moves must reach this streak. 0 means always show the opening.",
|
||||
);
|
||||
ui.add_space(10.0);
|
||||
ui.separator();
|
||||
ui.strong(tr("Playback speed"));
|
||||
let mut adaptive = !policy.use_fixed_piece_speed;
|
||||
if ui
|
||||
.checkbox(&mut adaptive, tr("Speed up familiar moves"))
|
||||
.changed()
|
||||
{
|
||||
policy.use_fixed_piece_speed = !adaptive;
|
||||
}
|
||||
hint(
|
||||
ui,
|
||||
"Base animation speed comes from board settings. Familiar moves play up to twice as fast.",
|
||||
);
|
||||
if adaptive {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(tr("Base speed multiplier"));
|
||||
ui.add(egui::DragValue::new(&mut policy.move_speed_adjustment)
|
||||
.range(-2.0..=2.0).speed(0.05).fixed_decimals(2).suffix(" ×"))
|
||||
.on_hover_text(tr("Range −2…2. Adaptive speed = adjustment × (1 + learned fraction), limited to 0.25×–4×: 1.5 gives 3× for a fully learned move; 0 or less gives 0.25×."));
|
||||
});
|
||||
hint(ui, "0 or less uses the minimum speed (0.25×).");
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
hint(ui, "Learning counters do not use these playback settings.");
|
||||
*policy != before
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn render(
|
||||
ctx: &egui::Context,
|
||||
width: f32,
|
||||
height: f32,
|
||||
container_width: f32,
|
||||
time: f64,
|
||||
events: Vec<egui::Event>,
|
||||
policy: &mut LearningContextPolicy,
|
||||
) -> (Vec<egui::epaint::ClippedShape>, bool, egui::Rect) {
|
||||
let mut changed = false;
|
||||
let mut container =
|
||||
egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(container_width, height));
|
||||
let output = ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(width, height),
|
||||
)),
|
||||
time: Some(time),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
let available = ui.available_rect_before_wrap();
|
||||
container = egui::Rect::from_min_size(
|
||||
available.min,
|
||||
egui::vec2(container_width, available.height()),
|
||||
);
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(container), |ui| {
|
||||
ui.set_clip_rect(container);
|
||||
changed = show(ui, policy);
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
let shapes = output.shapes.clone();
|
||||
output.drop_without_applying_deltas();
|
||||
(shapes, changed, container)
|
||||
}
|
||||
|
||||
fn text_rect(shapes: &[egui::epaint::ClippedShape], key: &'static str) -> Option<egui::Rect> {
|
||||
let translations = crate::i18n::all_languages(key);
|
||||
shapes.iter().find_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text)
|
||||
if translations
|
||||
.iter()
|
||||
.any(|candidate| *candidate == text.galley.text()) =>
|
||||
{
|
||||
Some(egui::Rect::from_min_size(text.pos, text.galley.size()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn text_position(
|
||||
shapes: &[egui::epaint::ClippedShape],
|
||||
key: &'static str,
|
||||
) -> Option<egui::Pos2> {
|
||||
text_rect(shapes, key).map(|rect| rect.min + egui::vec2(8.0, 6.0))
|
||||
}
|
||||
|
||||
fn click(position: egui::Pos2) -> Vec<egui::Event> {
|
||||
vec![
|
||||
egui::Event::PointerMoved(position),
|
||||
egui::Event::PointerButton {
|
||||
pos: position,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed: true,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
},
|
||||
egui::Event::PointerButton {
|
||||
pos: position,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed: false,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_options_preserve_values_until_changed_and_enable_dependencies() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut policy = LearningContextPolicy::default();
|
||||
let (shapes, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 0.0, Vec::new(), &mut policy);
|
||||
assert!(!changed);
|
||||
assert_eq!(policy, LearningContextPolicy::default());
|
||||
let leadup = text_position(&shapes, "Ask me to play preceding moves").unwrap();
|
||||
let (_, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 1.0, click(leadup), &mut policy);
|
||||
assert!(changed);
|
||||
assert!(policy.consider_leadup_moves);
|
||||
let (shapes, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 2.0, Vec::new(), &mut policy);
|
||||
assert!(!changed);
|
||||
let days = text_position(&shapes, "Review ahead of schedule").unwrap();
|
||||
let (_, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 3.0, click(days), &mut policy);
|
||||
assert!(changed);
|
||||
assert_eq!(policy.reinforce_minimum_days, Some(7));
|
||||
let speed = text_position(&shapes, "Speed up familiar moves").unwrap();
|
||||
let (_, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 4.0, click(speed), &mut policy);
|
||||
assert!(changed);
|
||||
assert!(!policy.use_fixed_piece_speed);
|
||||
assert_eq!(policy.move_speed_adjustment, 1.0);
|
||||
}
|
||||
}
|
||||
1968
apps/desktop/src/learning_dashboard.rs
Normal file
1968
apps/desktop/src/learning_dashboard.rs
Normal file
File diff suppressed because it is too large
Load diff
4139
apps/desktop/src/learning_training.rs
Normal file
4139
apps/desktop/src/learning_training.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -15,11 +15,8 @@ mod adjourned;
|
|||
mod analysis;
|
||||
mod app;
|
||||
mod assets;
|
||||
mod batch_copy;
|
||||
mod board;
|
||||
mod board_search;
|
||||
mod brilliant;
|
||||
mod brilliant_ui;
|
||||
mod chatgpt;
|
||||
mod db_counts;
|
||||
mod engine_download;
|
||||
|
|
@ -33,6 +30,16 @@ mod game_view;
|
|||
mod graphics;
|
||||
mod i18n;
|
||||
mod large_db;
|
||||
#[cfg(not(web))]
|
||||
mod learning_branches;
|
||||
#[cfg(not(web))]
|
||||
mod learning_charts;
|
||||
#[cfg(not(web))]
|
||||
mod learning_context_controls;
|
||||
#[cfg(not(web))]
|
||||
mod learning_dashboard;
|
||||
#[cfg(not(web))]
|
||||
mod learning_training;
|
||||
mod library;
|
||||
mod maia_download;
|
||||
#[cfg(web)]
|
||||
|
|
@ -41,12 +48,6 @@ mod notation;
|
|||
mod online;
|
||||
#[cfg(not(web))]
|
||||
mod online_ui;
|
||||
#[cfg(not(web))]
|
||||
mod opening_layout;
|
||||
#[cfg(not(web))]
|
||||
mod opening_lines;
|
||||
#[cfg(not(web))]
|
||||
mod opening_session;
|
||||
mod own_db;
|
||||
pub mod platform;
|
||||
mod play;
|
||||
|
|
@ -55,6 +56,10 @@ mod prep_saved;
|
|||
mod prep_ui;
|
||||
mod reference;
|
||||
#[cfg(not(web))]
|
||||
mod repertoire_editor;
|
||||
#[cfg(not(web))]
|
||||
mod repertoire_training;
|
||||
#[cfg(not(web))]
|
||||
mod repertoire_ui;
|
||||
mod review;
|
||||
mod review_engine;
|
||||
|
|
|
|||
|
|
@ -83,35 +83,6 @@ pub enum LibraryAction {
|
|||
path: PathBuf,
|
||||
index: usize,
|
||||
},
|
||||
/// «New database from selected…»: the chosen records (by number) of `path`, the
|
||||
/// table's order, how many of them the filter hides (task 42).
|
||||
CopySelection {
|
||||
path: PathBuf,
|
||||
records: Vec<u32>,
|
||||
sort: chess_import::chessbase::base::SortKey,
|
||||
ascending: bool,
|
||||
hidden: usize,
|
||||
},
|
||||
/// A short message (a toast).
|
||||
Notice(String),
|
||||
/// Open a game at the position `at` with its report shown (a move the search for
|
||||
/// great moves found).
|
||||
OpenGameReport {
|
||||
path: PathBuf,
|
||||
index: usize,
|
||||
at: Option<shakmaty::Chess>,
|
||||
},
|
||||
/// «!! Find great moves» over the list `records` of `path` (in the table's order),
|
||||
/// found by `filter` (task 27).
|
||||
FindGreatMoves {
|
||||
path: PathBuf,
|
||||
records: Vec<u32>,
|
||||
filter: chess_import::chessbase::base::Filter,
|
||||
/// The conditions in words, for a filtered question and summary.
|
||||
about: String,
|
||||
/// The manual source and its hidden count, fixed with `records`.
|
||||
selected: Option<crate::brilliant::SelectedGames>,
|
||||
},
|
||||
EditGameData {
|
||||
path: PathBuf,
|
||||
index: usize,
|
||||
|
|
@ -295,39 +266,6 @@ pub struct Library {
|
|||
pub aside: Option<crate::adjourned::Card>,
|
||||
/// The games of the databases not opened, for their cards.
|
||||
counts: crate::db_counts::Counts,
|
||||
/// Chosen records being copied into a new database (one copy at a time).
|
||||
batch: Option<BatchJob>,
|
||||
/// The marks of great moves of each database (task 27), read once per session.
|
||||
marks: HashMap<PathBuf, Arc<Mutex<crate::brilliant::Index>>>,
|
||||
/// The search for great moves under way (one engine job in the program).
|
||||
pub pass: Option<crate::brilliant::PassJob>,
|
||||
}
|
||||
|
||||
/// A copy of chosen records into a new database, written in the background.
|
||||
struct BatchJob {
|
||||
source: PathBuf,
|
||||
target: PathBuf,
|
||||
total: usize,
|
||||
work: crate::board_search::Background<
|
||||
Result<crate::batch_copy::CopyReport, crate::batch_copy::CopyError>,
|
||||
>,
|
||||
cancelling: bool,
|
||||
}
|
||||
|
||||
/// How a copy of chosen records ended.
|
||||
pub enum BatchEnd {
|
||||
Done {
|
||||
target: PathBuf,
|
||||
report: crate::batch_copy::CopyReport,
|
||||
},
|
||||
Cancelled {
|
||||
target: PathBuf,
|
||||
},
|
||||
Failed {
|
||||
source: PathBuf,
|
||||
target: PathBuf,
|
||||
error: crate::batch_copy::CopyError,
|
||||
},
|
||||
}
|
||||
|
||||
impl Library {
|
||||
|
|
@ -348,203 +286,9 @@ impl Library {
|
|||
update: None,
|
||||
aside: None,
|
||||
counts: crate::db_counts::Counts::new(ctx),
|
||||
batch: None,
|
||||
marks: HashMap::new(),
|
||||
pass: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The marks of great moves of the database at `path`.
|
||||
pub fn marks(&mut self, path: &Path) -> Arc<Mutex<crate::brilliant::Index>> {
|
||||
self.marks
|
||||
.entry(path.to_path_buf())
|
||||
.or_insert_with(|| Arc::new(Mutex::new(crate::brilliant::Index::of(path))))
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// The search under way, as each database's conditions line shows it; «Stop» of
|
||||
/// any of them stops it. Called every frame.
|
||||
pub fn show_pass(&mut self, estimate: impl Fn(&[u32]) -> f64) {
|
||||
let status = self.pass.as_ref().map(|job| {
|
||||
(
|
||||
job.source.clone(),
|
||||
crate::own_db::base_name(&job.source),
|
||||
job.selected,
|
||||
job.done(),
|
||||
job.records.len(),
|
||||
job.current(),
|
||||
job.left_secs(&estimate),
|
||||
job.stopping,
|
||||
)
|
||||
});
|
||||
let mut stop = false;
|
||||
for (path, view) in self.large.iter_mut() {
|
||||
view.pass = status.as_ref().map(
|
||||
|(source, name, selected, done, total, current, left, stopping)| {
|
||||
large_db::PassStatus {
|
||||
here: source == path,
|
||||
name: name.clone(),
|
||||
selected: *selected,
|
||||
done: *done,
|
||||
total: *total,
|
||||
current: *current,
|
||||
left_secs: *left,
|
||||
stopping: *stopping,
|
||||
}
|
||||
},
|
||||
);
|
||||
stop |= std::mem::take(&mut view.stop_pass);
|
||||
}
|
||||
if stop && let Some(job) = self.pass.as_mut() {
|
||||
job.stop();
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the search may not start now (the engine is busy elsewhere), for every
|
||||
/// database's button.
|
||||
pub fn set_engine_busy(&mut self, why: Option<String>) {
|
||||
for view in self.large.values_mut() {
|
||||
view.engine_busy = why.clone();
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the last search in `path` stopped with an error, where its progress was.
|
||||
pub fn set_pass_error(&mut self, path: &Path, text: Option<String>) {
|
||||
if let Some(view) = self.large.get_mut(path) {
|
||||
view.pass_error = text;
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts copying `records` of `source` into the new file `target` (none while
|
||||
/// another copy is written). `false`: the source is not read or the thread did not
|
||||
/// start.
|
||||
pub fn start_batch(
|
||||
&mut self,
|
||||
ctx: &egui::Context,
|
||||
source: &Path,
|
||||
records: Vec<u32>,
|
||||
sort: chess_import::chessbase::base::SortKey,
|
||||
ascending: bool,
|
||||
target: PathBuf,
|
||||
) -> bool {
|
||||
if self.batch.is_some() {
|
||||
return false;
|
||||
}
|
||||
let Some(db) = self.database(source) else {
|
||||
return false;
|
||||
};
|
||||
let total = records.len();
|
||||
let req = crate::batch_copy::CopyRequest {
|
||||
records,
|
||||
sort,
|
||||
ascending,
|
||||
target: target.clone(),
|
||||
slow: std::env::var_os("CP_BATCH_SLOW").is_some(),
|
||||
};
|
||||
let now = ctx.input(|i| i.time);
|
||||
let Some(work) = crate::board_search::Background::spawn(ctx, now, move |p, c| {
|
||||
crate::batch_copy::copy_into_new(&db, &req, p, c)
|
||||
}) else {
|
||||
return false;
|
||||
};
|
||||
if let Some(view) = self.large.get_mut(source) {
|
||||
view.batch_error = None;
|
||||
}
|
||||
self.batch = Some(BatchJob {
|
||||
source: source.to_path_buf(),
|
||||
target,
|
||||
total,
|
||||
work,
|
||||
cancelling: false,
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
/// Why the copy from `path` wrote nothing, said where its progress was.
|
||||
pub fn set_batch_error(&mut self, path: &Path, text: String) {
|
||||
if let Some(view) = self.large.get_mut(path) {
|
||||
view.batch_error = Some(text);
|
||||
}
|
||||
}
|
||||
|
||||
/// The chosen records of `path` let go (their numbers no longer mean the same games).
|
||||
pub fn clear_selection(&mut self, path: &Path) {
|
||||
if let Some(view) = self.large.get_mut(path) {
|
||||
view.clear_marks();
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks the copy being written to stop.
|
||||
pub fn cancel_batch(&mut self) {
|
||||
if let Some(job) = &mut self.batch {
|
||||
job.work.cancel();
|
||||
job.cancelling = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops the copy being written and waits a little for it to clean up (closing the
|
||||
/// program): its temporary file goes, no new database appears.
|
||||
pub fn stop_batch(&mut self) {
|
||||
if let Some(job) = self.batch.take() {
|
||||
job.work.cancel();
|
||||
job.work.wait(std::time::Duration::from_secs(3));
|
||||
}
|
||||
}
|
||||
|
||||
/// The end of the copy being written, once it came (called every frame, whatever is
|
||||
/// on the screen); while it runs the source's conditions line shows it.
|
||||
pub fn poll_batch(&mut self, ctx: &egui::Context) -> Option<BatchEnd> {
|
||||
let job = self.batch.as_ref()?;
|
||||
// `CP_BATCH_CANCEL_AFTER=<ms>`: «Cancel» pressed that long after the start (checks,
|
||||
// screenshots of the cancelling).
|
||||
let cancel_after = std::env::var("CP_BATCH_CANCEL_AFTER")
|
||||
.ok()
|
||||
.and_then(|ms| ms.parse::<f64>().ok());
|
||||
if let Some(ms) = cancel_after
|
||||
&& !job.cancelling
|
||||
&& ctx.input(|i| i.time) - job.work.started >= ms / 1000.0
|
||||
{
|
||||
self.cancel_batch();
|
||||
}
|
||||
let job = self.batch.as_ref()?;
|
||||
let Some(result) = job.work.poll() else {
|
||||
let status = large_db::BatchStatus {
|
||||
name: crate::own_db::base_name(&job.target),
|
||||
done: job.work.progress(),
|
||||
total: job.total,
|
||||
cancelling: job.cancelling,
|
||||
};
|
||||
let source = job.source.clone();
|
||||
let mut cancel = false;
|
||||
if let Some(view) = self.large.get_mut(&source) {
|
||||
cancel = std::mem::take(&mut view.cancel_batch);
|
||||
view.batch = Some(status);
|
||||
}
|
||||
if cancel {
|
||||
self.cancel_batch();
|
||||
}
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(100));
|
||||
return None;
|
||||
};
|
||||
let job = self.batch.take()?;
|
||||
if let Some(view) = self.large.get_mut(&job.source) {
|
||||
view.batch = None;
|
||||
view.cancel_batch = false;
|
||||
}
|
||||
Some(match result {
|
||||
None => BatchEnd::Cancelled { target: job.target },
|
||||
Some(Ok(report)) => BatchEnd::Done {
|
||||
target: job.target,
|
||||
report,
|
||||
},
|
||||
Some(Err(error)) => BatchEnd::Failed {
|
||||
source: job.source,
|
||||
target: job.target,
|
||||
error,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// Starts loading `path` in the background (no-op if already loaded/loading).
|
||||
pub fn load(&mut self, path: &Path, ctx: &egui::Context) {
|
||||
if matches!(
|
||||
|
|
@ -601,21 +345,6 @@ impl Library {
|
|||
}
|
||||
}
|
||||
|
||||
/// Chooses the row of `index` alone (any choice of several let go) and scrolls to it.
|
||||
pub fn choose_only(&mut self, path: &Path, index: usize) {
|
||||
if let Some(view) = self.large.get_mut(path) {
|
||||
view.clear_marks();
|
||||
view.reveal(index);
|
||||
}
|
||||
}
|
||||
|
||||
/// Sorts the table of `path` by its «!!» column.
|
||||
pub fn sort_by_marks(&mut self, path: &Path) {
|
||||
if let Some(view) = self.large.get_mut(path) {
|
||||
view.sort_marks_on();
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects (and scrolls to) a game row, e.g. when returning from a game.
|
||||
pub fn reveal(&mut self, path: &Path, index: usize) {
|
||||
if let Some(view) = self.large.get_mut(path) {
|
||||
|
|
@ -628,10 +357,7 @@ impl Library {
|
|||
let selected = self.selected_db.as_deref() == Some(path);
|
||||
// The conditions, the position, the sort and the selection stay (§9.7): the view
|
||||
// finds its list anew once the file is read.
|
||||
let mut view = self.large.remove(path);
|
||||
if let (Some(v), Some(db)) = (view.as_mut(), self.database(path)) {
|
||||
v.before_reread(&db);
|
||||
}
|
||||
let view = self.large.remove(path);
|
||||
self.forget(path);
|
||||
if let Some(v) = view {
|
||||
self.large.insert(path.to_path_buf(), v);
|
||||
|
|
@ -954,11 +680,6 @@ impl Library {
|
|||
{
|
||||
ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape));
|
||||
}
|
||||
for view in self.large.values_mut() {
|
||||
if let Some(text) = view.notice.take() {
|
||||
actions.push(LibraryAction::Notice(text));
|
||||
}
|
||||
}
|
||||
if let Some(path) = self.selected_db.clone()
|
||||
&& let Some(view) = self.large.get_mut(&path)
|
||||
&& let Some(entry) = view.prepare.take()
|
||||
|
|
@ -1725,15 +1446,6 @@ impl Library {
|
|||
.entry(path.clone())
|
||||
.or_insert_with(|| LargeView::for_database(&db, online));
|
||||
let notes = self.info.get(&path).map_or(0, |i| i.notes.len());
|
||||
view.set_marks_db(&db);
|
||||
if view.marks.is_none() {
|
||||
let marks = self
|
||||
.marks
|
||||
.entry(path.clone())
|
||||
.or_insert_with(|| Arc::new(Mutex::new(crate::brilliant::Index::of(&path))))
|
||||
.clone();
|
||||
view.marks = Some(marks);
|
||||
}
|
||||
if view.table(
|
||||
ui,
|
||||
&path,
|
||||
|
|
|
|||
|
|
@ -29,84 +29,6 @@ pub struct Notation<'a> {
|
|||
pub dim_until: Option<u32>,
|
||||
/// Mistakes on main-line moves (learning an opening): how many, the move was shown.
|
||||
pub mistakes: Option<&'a HashMap<NodeId, (u32, bool)>>,
|
||||
/// Arrows and circles of the moves' comments (`[%cal]`, `[%csl]`): a quiet sign by
|
||||
/// the move ([`shape_counts`]).
|
||||
pub shapes: Option<&'a HashMap<NodeId, ShapeCount>>,
|
||||
}
|
||||
|
||||
/// How many arrows and circles a move's comment draws on the board.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ShapeCount {
|
||||
pub arrows: usize,
|
||||
pub circles: usize,
|
||||
}
|
||||
|
||||
impl ShapeCount {
|
||||
/// «Arrows: 2 · circles: 1 — shown on the board at this move»; a count of none is left out.
|
||||
pub fn hint(self) -> String {
|
||||
let (a, c) = (self.arrows, self.circles);
|
||||
match (a, c) {
|
||||
(_, 0) => crate::i18n::trf(
|
||||
"Arrows: {a} — shown on the board at this move",
|
||||
&[("a", &a)],
|
||||
),
|
||||
(0, _) => crate::i18n::trf(
|
||||
"Circles: {c} — shown on the board at this move",
|
||||
&[("c", &c)],
|
||||
),
|
||||
_ => crate::i18n::trf(
|
||||
"Arrows: {a} · circles: {c} — shown on the board at this move",
|
||||
&[("a", &a), ("c", &c)],
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The nodes of the game whose comment after them draws arrows or circles.
|
||||
pub fn shape_counts(game: &Game) -> HashMap<NodeId, ShapeCount> {
|
||||
game.all_nodes()
|
||||
.filter_map(|id| {
|
||||
let (arrows, circles) = chess_core::shapes(game.node(id)?.comments_after());
|
||||
let count = ShapeCount {
|
||||
arrows: arrows.len(),
|
||||
circles: circles.len(),
|
||||
};
|
||||
(count != ShapeCount::default()).then_some((id, count))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The sign's box; it is drawn this far after the move.
|
||||
const SIGN: f32 = 10.0;
|
||||
const SIGN_GAP: f32 = 4.0;
|
||||
|
||||
/// The sign of a move whose comment draws on the board: an arrow if it has one, a ring
|
||||
/// otherwise. Painted (no font has both at the height of a move's text), so it is sharp
|
||||
/// at any scale; it does not repeat the shapes' colours, which would argue with NAGs.
|
||||
fn paint_shapes_sign(
|
||||
painter: &egui::Painter,
|
||||
center: egui::Pos2,
|
||||
count: ShapeCount,
|
||||
color: Color32,
|
||||
) {
|
||||
let stroke = Stroke::new(1.5, color);
|
||||
if count.arrows > 0 {
|
||||
let h = SIGN / 2.0 - 0.5;
|
||||
let (from, tip) = (center + vec2(-h, h), center + vec2(h, -h));
|
||||
let dir = (tip - from).normalized();
|
||||
let head = 4.5;
|
||||
let base = tip - dir * head;
|
||||
let side = vec2(-dir.y, dir.x) * (head * 0.55);
|
||||
painter.line_segment([from, base + dir * 0.5], stroke);
|
||||
painter.add(egui::Shape::convex_polygon(
|
||||
vec![tip, base + side, base - side],
|
||||
color,
|
||||
Stroke::NONE,
|
||||
));
|
||||
} else {
|
||||
// The ring's outer edge within the sign's box, as the arrow's.
|
||||
painter.circle_stroke(center, SIGN / 2.0 - 1.0, stroke);
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of a frame of the notation panel.
|
||||
|
|
@ -403,7 +325,6 @@ impl Row {
|
|||
resp.hovered(),
|
||||
dim,
|
||||
);
|
||||
let mut right = text_right;
|
||||
if let Some(&(count, shown)) = n.mistakes.and_then(|m| m.get(&id)) {
|
||||
let color = if shown {
|
||||
ui.visuals().warn_fg_color
|
||||
|
|
@ -426,7 +347,6 @@ impl Row {
|
|||
ui.painter().rect_filled(pill, 7.0, color);
|
||||
ui.painter()
|
||||
.galley(pill.min + vec2(4.0, 1.0), galley, Color32::WHITE);
|
||||
right = pill.right();
|
||||
let tip = if shown {
|
||||
crate::i18n::trf("Mistakes: {n}; the move was shown", &[("n", &count)])
|
||||
} else {
|
||||
|
|
@ -434,22 +354,6 @@ impl Row {
|
|||
};
|
||||
resp.clone().on_hover_text(tip);
|
||||
}
|
||||
if let Some(&count) = n.shapes.and_then(|s| s.get(&id)) {
|
||||
let color = if id == n.cursor {
|
||||
ui.visuals().selection.stroke.color
|
||||
} else {
|
||||
ui.visuals().weak_text_color()
|
||||
};
|
||||
let x =
|
||||
(right + SIGN_GAP + SIGN / 2.0).min(cell.right() - SIGN / 2.0 - 2.0);
|
||||
paint_shapes_sign(
|
||||
ui.painter(),
|
||||
egui::pos2(x, cell.center().y),
|
||||
count,
|
||||
color,
|
||||
);
|
||||
resp.clone().on_hover_text(count.hint());
|
||||
}
|
||||
handle_move_response(ui, &resp, n, id, out);
|
||||
}
|
||||
None => {
|
||||
|
|
@ -758,7 +662,7 @@ fn mark_block(ui: &mut Ui, n: &Notation, id: NodeId, mark: &Mark, out: &mut Nota
|
|||
};
|
||||
let label = crate::san::show(&label).into_owned();
|
||||
let current = shown == Some(i + 1);
|
||||
let resp = move_chip(ui, &label, None, current, None)
|
||||
let resp = move_chip(ui, &label, None, current)
|
||||
.on_hover_text(tr("Show this line on the board"));
|
||||
if current && n.scroll_to_cursor {
|
||||
resp.scroll_to_me(Some(egui::Align::Center));
|
||||
|
|
@ -934,16 +838,11 @@ const MARK_ROOM: f32 = 18.0;
|
|||
|
||||
fn comment_block(ui: &mut Ui, n: &Notation, text: &str, slot: Slot, out: &mut NotationResponse) {
|
||||
let (shown, mark) = translated(n, text);
|
||||
// The start of the game draws on the board: the sign at the block's right edge.
|
||||
let shapes = (slot == Slot::After(NodeId::ROOT))
|
||||
.then(|| n.shapes.and_then(|s| s.get(&NodeId::ROOT)).copied())
|
||||
.flatten();
|
||||
let room = MARK_ROOM * (u8::from(mark.is_some()) + u8::from(shapes.is_some())) as f32;
|
||||
let mut frame = block_frame(ui);
|
||||
if room > 0.0 {
|
||||
if mark.is_some() {
|
||||
frame = frame.inner_margin(egui::Margin {
|
||||
left: 10,
|
||||
right: 10 + room as i8,
|
||||
right: 10 + MARK_ROOM as i8,
|
||||
top: 6,
|
||||
bottom: 6,
|
||||
});
|
||||
|
|
@ -968,18 +867,6 @@ fn comment_block(ui: &mut Ui, n: &Notation, text: &str, slot: Slot, out: &mut No
|
|||
let at = r.response.rect.right_top() + vec2(-8.0, 7.0);
|
||||
translation_mark(ui, at, m, text);
|
||||
}
|
||||
if let Some(count) = shapes {
|
||||
let shift = if mark.is_some() { MARK_ROOM } else { 0.0 };
|
||||
let center = r.response.rect.right_top() + vec2(-8.0 - shift - SIGN / 2.0, 6.0 + 9.0);
|
||||
paint_shapes_sign(ui.painter(), center, count, ui.visuals().weak_text_color());
|
||||
let id = ui.id().with("root_shapes");
|
||||
ui.interact(
|
||||
egui::Rect::from_center_size(center, vec2(SIGN, SIGN) + vec2(4.0, 4.0)),
|
||||
id,
|
||||
Sense::hover(),
|
||||
)
|
||||
.on_hover_text(count.hint());
|
||||
}
|
||||
}
|
||||
|
||||
/// A double click opens the comment for editing; the right button offers that and
|
||||
|
|
@ -1267,7 +1154,6 @@ enum Token {
|
|||
/// The label with the move number, for the move that starts a piece of the flow.
|
||||
numbered: String,
|
||||
color: Option<Color32>,
|
||||
shapes: Option<ShapeCount>,
|
||||
},
|
||||
Comment {
|
||||
slot: Slot,
|
||||
|
|
@ -1323,13 +1209,7 @@ fn variation_block(
|
|||
/// A move in flowing text: the current one highlighted as in the main-line table,
|
||||
/// the others lit under the mouse. Painted by hand, so its size never changes with the
|
||||
/// mouse (a button's frame does).
|
||||
fn move_chip(
|
||||
ui: &mut Ui,
|
||||
label: &str,
|
||||
color: Option<Color32>,
|
||||
current: bool,
|
||||
shapes: Option<ShapeCount>,
|
||||
) -> egui::Response {
|
||||
fn move_chip(ui: &mut Ui, label: &str, color: Option<Color32>, current: bool) -> egui::Response {
|
||||
let sel = ui.visuals().selection;
|
||||
let font = FontId::proportional(15.0);
|
||||
let text_color = if current {
|
||||
|
|
@ -1341,14 +1221,7 @@ fn move_chip(
|
|||
.painter()
|
||||
.layout_no_wrap(label.to_owned(), font, text_color);
|
||||
let pad = vec2(4.0, 2.0);
|
||||
// The sign and the chip's own right padding after it.
|
||||
let sign = if shapes.is_some() {
|
||||
SIGN_GAP + SIGN + 2.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let (rect, resp) =
|
||||
ui.allocate_exact_size(galley.size() + 2.0 * pad + vec2(sign, 0.0), Sense::click());
|
||||
let (rect, resp) = ui.allocate_exact_size(galley.size() + 2.0 * pad, Sense::click());
|
||||
if current {
|
||||
ui.painter().rect(
|
||||
rect,
|
||||
|
|
@ -1361,18 +1234,7 @@ fn move_chip(
|
|||
ui.painter()
|
||||
.rect_filled(rect, 2.0, ui.visuals().widgets.hovered.weak_bg_fill);
|
||||
}
|
||||
let text_right = rect.min.x + pad.x + galley.size().x;
|
||||
ui.painter().galley(rect.min + pad, galley, text_color);
|
||||
if let Some(count) = shapes {
|
||||
let color = if current {
|
||||
sel.stroke.color
|
||||
} else {
|
||||
ui.visuals().weak_text_color()
|
||||
};
|
||||
let center = egui::pos2(text_right + SIGN_GAP + SIGN / 2.0, rect.center().y);
|
||||
paint_shapes_sign(ui.painter(), center, count, color);
|
||||
return resp.on_hover_text(count.hint());
|
||||
}
|
||||
resp
|
||||
}
|
||||
|
||||
|
|
@ -1396,7 +1258,6 @@ fn flow(
|
|||
label,
|
||||
numbered,
|
||||
color,
|
||||
shapes,
|
||||
} => {
|
||||
let current = *id == n.cursor;
|
||||
// After the editor the flow starts anew: with the move number.
|
||||
|
|
@ -1405,7 +1266,7 @@ fn flow(
|
|||
} else {
|
||||
label
|
||||
};
|
||||
let resp = move_chip(ui, label, *color, current, *shapes);
|
||||
let resp = move_chip(ui, label, *color, current);
|
||||
handle_move_response(ui, &resp, n, *id, out);
|
||||
}
|
||||
Token::Comment { slot, text } => {
|
||||
|
|
@ -1471,7 +1332,6 @@ fn line_tokens(n: &Notation, first: NodeId, dark: bool, tokens: &mut Vec<Token>)
|
|||
label,
|
||||
numbered,
|
||||
color: sym_color,
|
||||
shapes: n.shapes.and_then(|s| s.get(&node)).copied(),
|
||||
});
|
||||
let after = comment_text(nd.comments_after());
|
||||
if !after.is_empty() {
|
||||
|
|
@ -1502,54 +1362,3 @@ fn line_tokens(n: &Notation, first: NodeId, dark: bool, tokens: &mut Vec<Token>)
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shape_counts_find_arrows_and_circles_of_comments_only() {
|
||||
let game = chess_core::parse_str(
|
||||
"{[%csl Re4]} 1. e4 {[%cal Gg1f3,Gf1c4] [%csl Ga8] [%clk 0:01:00]} e5 {plain} \
|
||||
(1... c5 {[%csl Yd5]}) 2. Nf3 {[%eval 0.3]} *",
|
||||
)
|
||||
.game;
|
||||
let counts = shape_counts(&game);
|
||||
let e4 = game.main_child(NodeId::ROOT).unwrap();
|
||||
let c5 = game.variations(e4)[0];
|
||||
assert_eq!(counts.len(), 3, "{counts:?}");
|
||||
assert_eq!(
|
||||
counts[&NodeId::ROOT],
|
||||
ShapeCount {
|
||||
arrows: 0,
|
||||
circles: 1
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
counts[&e4],
|
||||
ShapeCount {
|
||||
arrows: 2,
|
||||
circles: 1
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
counts[&c5],
|
||||
ShapeCount {
|
||||
arrows: 0,
|
||||
circles: 1
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sign_hint_leaves_out_a_count_of_none() {
|
||||
crate::i18n::set_lang(crate::i18n::Lang::En);
|
||||
let hint = |arrows, circles| ShapeCount { arrows, circles }.hint();
|
||||
assert_eq!(
|
||||
hint(2, 1),
|
||||
"Arrows: 2 · circles: 1 — shown on the board at this move"
|
||||
);
|
||||
assert_eq!(hint(2, 0), "Arrows: 2 — shown on the board at this move");
|
||||
assert_eq!(hint(0, 1), "Circles: 1 — shown on the board at this move");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,600 +0,0 @@
|
|||
//! What the three opening-training screens share (docs/design/opening-trainer-v2-spec.md
|
||||
//! §1): the frame of the game screen, the card, the board's PGN marks and the texts
|
||||
//! about moves, sides and dates.
|
||||
|
||||
use chess_core::shakmaty::{Color, Square, uci::UciMove};
|
||||
use chess_core::{Annotation, CommentPart, Game, MoveKind, NodeId, parse_comment};
|
||||
use egui::{Color32, RichText, Ui, vec2};
|
||||
use trainer::repertoire::{LearningSide, RepertoireId, TrainingMode};
|
||||
|
||||
use crate::board::{Arrow, Badge};
|
||||
use crate::i18n::{tr, trf};
|
||||
use crate::settings::Settings;
|
||||
|
||||
/// The panel's least width: the table of repertoires still shows its numbers whole.
|
||||
pub(crate) const SIDE_LEAST: f32 = 360.0;
|
||||
/// Where the width the user dragged the panel to is kept for the app to save
|
||||
/// (`Settings::opening_side_width`).
|
||||
pub(crate) const SIDE_WIDTH_ID: &str = "opening_side_width";
|
||||
/// Under a stacked board: the panel's least height (`STACK_BOTTOM_MIN`).
|
||||
const STACK_BOTTOM_MIN: f32 = 300.0;
|
||||
const BOARD_MIN: f32 = 220.0;
|
||||
/// Space between the blocks of the panel.
|
||||
pub(crate) const GAP: f32 = 6.0;
|
||||
/// The new moves of one session and of "10 more new".
|
||||
pub(crate) const NEW_PER_SESSION: usize = 10;
|
||||
|
||||
/// Header, side panel and board in the places of the game screen. The same panel id on
|
||||
/// every screen of the section: switching screens never moves the board.
|
||||
pub(crate) fn screen<T: ?Sized>(
|
||||
ui: &mut Ui,
|
||||
this: &mut T,
|
||||
header: impl FnOnce(&mut T, &mut Ui),
|
||||
side: impl FnOnce(&mut T, &mut Ui),
|
||||
board: impl FnOnce(&mut T, &mut Ui),
|
||||
) {
|
||||
egui::Panel::top("opening_header").show(ui, |ui| header(this, ui));
|
||||
let width = ui.available_width();
|
||||
let height = ui.available_height();
|
||||
let board_side = (height - 16.0).min(width - SIDE_LEAST - 24.0);
|
||||
let board_stack = (width - 16.0).min(height - STACK_BOTTOM_MIN - 16.0);
|
||||
let stacked = board_stack >= 1.25 * board_side;
|
||||
let panel = if stacked {
|
||||
let most = (height - BOARD_MIN - 16.0).max(STACK_BOTTOM_MIN);
|
||||
let rest = (height - board_stack - 16.0).clamp(STACK_BOTTOM_MIN, most);
|
||||
egui::Panel::bottom("opening_side_stacked")
|
||||
.resizable(true)
|
||||
.default_size(rest)
|
||||
.size_range(STACK_BOTTOM_MIN..=most)
|
||||
.show(ui, |ui| side(this, ui))
|
||||
} else {
|
||||
let board = height - 16.0;
|
||||
let most = (width - BOARD_MIN - 24.0).max(SIDE_LEAST);
|
||||
let room = (width - board - 24.0).clamp(SIDE_LEAST, most);
|
||||
let id = egui::Id::new(SIDE_WIDTH_ID);
|
||||
let kept = ui.ctx().data(|d| d.get_temp::<f32>(id));
|
||||
let default = kept.unwrap_or_else(|| side_default(width, room));
|
||||
let handle = egui::Id::new("opening_side").with("__resize");
|
||||
// Until the user drags it, the panel follows the window: a window that opens
|
||||
// small and grows gets the width of its final size, not of its first frame.
|
||||
let dragging = ui
|
||||
.ctx()
|
||||
.read_response(handle)
|
||||
.is_some_and(|r| r.dragged() || r.drag_stopped());
|
||||
if kept.is_none() && !dragging {
|
||||
ui.ctx().data_mut(|d| {
|
||||
d.remove::<egui::containers::panel::PanelState>(egui::Id::new("opening_side"))
|
||||
});
|
||||
}
|
||||
let panel = egui::Panel::right("opening_side")
|
||||
.resizable(true)
|
||||
.default_size(default.clamp(SIDE_LEAST, most))
|
||||
.size_range(SIDE_LEAST..=most)
|
||||
.show(ui, |ui| side(this, ui));
|
||||
// The width the user dragged to is kept; a window that squeezes the panel does
|
||||
// not change it.
|
||||
if ui
|
||||
.ctx()
|
||||
.read_response(handle)
|
||||
.is_some_and(|r| r.drag_stopped())
|
||||
{
|
||||
let shown = panel.response.rect.width().round();
|
||||
ui.ctx().data_mut(|d| d.insert_temp(id, shown));
|
||||
}
|
||||
panel
|
||||
};
|
||||
crate::widgets::check_panel("opening_side", &panel.response);
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
let area = ui.available_rect_before_wrap();
|
||||
let side = area.width().min(area.height()).max(1.0).floor();
|
||||
let left = area.left() + ((area.width() - side) / 2.0).max(0.0).floor();
|
||||
let top = area.top() + ((area.height() - side) / 2.0).max(0.0).floor();
|
||||
let rect = egui::Rect::from_min_size(egui::pos2(left, top), vec2(side, side));
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| board(this, ui));
|
||||
});
|
||||
}
|
||||
|
||||
/// The panel's width before the user drags it: about a third of the window, the board
|
||||
/// keeping its room.
|
||||
pub(crate) fn side_default(width: f32, room: f32) -> f32 {
|
||||
(width * 0.36).clamp(380.0, 560.0).min(room)
|
||||
}
|
||||
|
||||
/// The frame of a state card (the player's card of a game against the computer).
|
||||
pub(crate) fn card(ui: &Ui, active: bool, alert: bool) -> egui::Frame {
|
||||
let mut frame = egui::Frame::new()
|
||||
.inner_margin(egui::Margin::symmetric(10, 6))
|
||||
.corner_radius(4)
|
||||
.stroke(egui::Stroke::new(
|
||||
1.0,
|
||||
ui.visuals().widgets.noninteractive.bg_stroke.color,
|
||||
));
|
||||
if active {
|
||||
frame = frame.fill(ui.visuals().selection.bg_fill.gamma_multiply(0.35));
|
||||
}
|
||||
if alert {
|
||||
frame = frame.stroke(egui::Stroke::new(1.5, ui.visuals().error_fg_color));
|
||||
}
|
||||
frame
|
||||
}
|
||||
|
||||
/// The content size of a [`card`] filling a block of `height`: the frame's margins and
|
||||
/// its stroke stay inside the block.
|
||||
pub(crate) fn card_inner(ui: &Ui, height: f32) -> egui::Vec2 {
|
||||
vec2(ui.available_width() - 22.0, height - 14.0).max(egui::Vec2::ZERO)
|
||||
}
|
||||
|
||||
/// A block of a fixed height: whatever it holds, what follows never moves.
|
||||
pub(crate) fn fixed_block<R>(ui: &mut Ui, height: f32, add: impl FnOnce(&mut Ui) -> R) -> R {
|
||||
let width = ui.available_width().max(1.0);
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(width, height), egui::Sense::hover());
|
||||
let mut child = ui.new_child(
|
||||
egui::UiBuilder::new()
|
||||
.max_rect(rect)
|
||||
.layout(egui::Layout::top_down(egui::Align::Min)),
|
||||
);
|
||||
child.set_clip_rect(rect.intersect(ui.clip_rect()));
|
||||
add(&mut child)
|
||||
}
|
||||
|
||||
/// One line of text cut with "…", the whole text on hover.
|
||||
pub(crate) fn line(ui: &mut Ui, text: impl Into<RichText>) -> egui::Response {
|
||||
let text = text.into();
|
||||
let hover = text.text().to_owned();
|
||||
let response = ui.add(egui::Label::new(text).truncate());
|
||||
if hover.is_empty() {
|
||||
response
|
||||
} else {
|
||||
response.on_hover_text(hover)
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` cut on the left by whole words ("… 4. Ba4 Nf6") to fit `width` in `font`:
|
||||
/// the last moves of a path matter most.
|
||||
pub(crate) fn cut_left(ui: &Ui, text: &str, font: &egui::FontId, width: f32) -> String {
|
||||
let fits = |text: &str| {
|
||||
ui.fonts_mut(|fonts| {
|
||||
fonts
|
||||
.layout_no_wrap(text.to_owned(), font.clone(), Color32::WHITE)
|
||||
.size()
|
||||
.x
|
||||
}) <= width
|
||||
};
|
||||
if fits(text) {
|
||||
return text.to_owned();
|
||||
}
|
||||
let mut rest = text;
|
||||
while let Some((_, tail)) = rest.split_once(' ') {
|
||||
rest = tail;
|
||||
let cut = format!("… {rest}");
|
||||
if fits(&cut) {
|
||||
return cut;
|
||||
}
|
||||
}
|
||||
format!("… {rest}")
|
||||
}
|
||||
|
||||
/// One line cut on the left ([`cut_left`]), the whole text on hover.
|
||||
pub(crate) fn line_left(ui: &mut Ui, text: &str, strong: bool) -> egui::Response {
|
||||
let font = egui::TextStyle::Body.resolve(ui.style());
|
||||
let shown = cut_left(ui, text, &font, ui.available_width());
|
||||
let mut rich = RichText::new(shown);
|
||||
if strong {
|
||||
rich = rich.strong();
|
||||
}
|
||||
let response = ui.add(egui::Label::new(rich).truncate());
|
||||
if text.is_empty() {
|
||||
response
|
||||
} else {
|
||||
response.on_hover_text(text)
|
||||
}
|
||||
}
|
||||
|
||||
/// The trained colour of a repertoire, kept in the settings since 2.2.0 (an old "both
|
||||
/// colours" repertoire opens for White).
|
||||
pub(crate) fn side_of(settings: &Settings, id: &RepertoireId) -> LearningSide {
|
||||
match settings.repertoire_modes.get(id.as_str()) {
|
||||
Some((TrainingMode::Black, _)) => LearningSide::Black,
|
||||
_ => LearningSide::White,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_side(settings: &mut Settings, id: &RepertoireId, side: LearningSide) {
|
||||
let mode = match side {
|
||||
LearningSide::White => TrainingMode::White,
|
||||
LearningSide::Black => TrainingMode::Black,
|
||||
};
|
||||
settings.repertoire_modes.insert(
|
||||
id.to_string(),
|
||||
(mode, trainer::repertoire::QueueMode::SpacedRepetition),
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn king(side: LearningSide) -> egui::Image<'static> {
|
||||
crate::widgets::side_king(side == LearningSide::White, KING)
|
||||
}
|
||||
|
||||
/// The side of the king of [`king`] (as a 14-point ♔ took).
|
||||
pub(crate) const KING: f32 = 16.0;
|
||||
|
||||
pub(crate) fn you_play(side: LearningSide) -> &'static str {
|
||||
tr(match side {
|
||||
LearningSide::White => "You play White",
|
||||
LearningSide::Black => "You play Black",
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn orientation(side: LearningSide) -> Color {
|
||||
side.color()
|
||||
}
|
||||
|
||||
/// "4. Ba4" or "4… Nf6" in the notation of the application.
|
||||
pub(crate) fn move_text(game: &Game, node: NodeId) -> Option<String> {
|
||||
let (number, color) = game.move_number(node)?;
|
||||
let san = crate::san::show(&game.game_move(node)?.san).into_owned();
|
||||
Some(match color {
|
||||
Color::White => format!("{number}. {san}"),
|
||||
Color::Black => format!("{number}… {san}"),
|
||||
})
|
||||
}
|
||||
|
||||
/// "1. e4 e5 2. Nf3": the moves from the start to `node` with move numbers.
|
||||
pub(crate) fn path_text(game: &Game, node: NodeId) -> String {
|
||||
let mut words = Vec::new();
|
||||
for id in game.path(node).into_iter().skip(1) {
|
||||
let Some(mv) = game.game_move(id) else {
|
||||
continue;
|
||||
};
|
||||
let san = crate::san::show(&mv.san).into_owned();
|
||||
match game.move_number(id) {
|
||||
Some((number, Color::White)) => words.push(format!("{number}. {san}")),
|
||||
Some((number, Color::Black)) if words.is_empty() => {
|
||||
words.push(format!("{number}… {san}"))
|
||||
}
|
||||
_ => words.push(san),
|
||||
}
|
||||
}
|
||||
words.join(" ")
|
||||
}
|
||||
|
||||
/// The symbol of a move's assessment (`!`, `?!` …) and its colour for text.
|
||||
pub(crate) fn assessment(game: &Game, node: NodeId, dark: bool) -> Option<(&'static str, Color32)> {
|
||||
let nag = game
|
||||
.node(node)?
|
||||
.nags()
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|nag| nag.is_move_assessment())?;
|
||||
Some((
|
||||
nag.symbol()?,
|
||||
crate::notation::assessment_text_color(nag, dark)?,
|
||||
))
|
||||
}
|
||||
|
||||
/// The node reached from the root by these UCI moves.
|
||||
pub(crate) fn node_at(game: &Game, path: &[String]) -> Option<NodeId> {
|
||||
let mut at = NodeId::ROOT;
|
||||
for uci in path {
|
||||
let mv = uci
|
||||
.parse::<UciMove>()
|
||||
.ok()?
|
||||
.to_move(game.position(at)?)
|
||||
.ok()?;
|
||||
at = game.find_child(at, mv)?;
|
||||
}
|
||||
Some(at)
|
||||
}
|
||||
|
||||
/// The UCI moves from the root to a node.
|
||||
pub(crate) fn uci_path(game: &Game, node: NodeId) -> Vec<String> {
|
||||
game.path(node)
|
||||
.into_iter()
|
||||
.skip(1)
|
||||
.filter_map(|id| game.game_move(id).and_then(|mv| mv.uci()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// "C84 · Ruy Lopez: Closed": the most precise named position on the way to `node`.
|
||||
pub(crate) fn opening_text(game: &Game, node: NodeId) -> String {
|
||||
let keys: Vec<u64> = game
|
||||
.path(node)
|
||||
.into_iter()
|
||||
.filter_map(|id| game.position(id))
|
||||
.map(chess_openings::key)
|
||||
.collect();
|
||||
match chess_openings::deepest(&keys) {
|
||||
Some((_, id)) => {
|
||||
let opening = chess_openings::get(id);
|
||||
format!("{} · {}", opening.eco, opening.name)
|
||||
}
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The start a repertoire's lines share: the last move before the first branching.
|
||||
pub(crate) fn common_start(game: &Game) -> NodeId {
|
||||
let mut at = NodeId::ROOT;
|
||||
while let [only] = game.children(at) {
|
||||
at = *only;
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
pub(crate) fn last_move(game: &Game, node: NodeId) -> Option<(Square, Square)> {
|
||||
match game.game_move(node)?.kind {
|
||||
MoveKind::Normal(mv) => Some((
|
||||
mv.from().unwrap_or_else(|| mv.to()),
|
||||
crate::board::ui_target(&mv),
|
||||
)),
|
||||
MoveKind::Null => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines of a repertoire: the paths of its last moves, without switched-off
|
||||
/// branches, in PGN order.
|
||||
pub(crate) fn lines(game: &Game, disabled: impl Fn(&[String]) -> bool) -> Vec<Vec<String>> {
|
||||
let mut out = Vec::new();
|
||||
let mut stack = vec![(NodeId::ROOT, Vec::new())];
|
||||
while let Some((node, path)) = stack.pop() {
|
||||
let children: Vec<_> = game
|
||||
.children(node)
|
||||
.iter()
|
||||
.filter_map(|child| {
|
||||
let uci = game.game_move(*child)?.uci()?;
|
||||
let mut next = path.clone();
|
||||
next.push(uci);
|
||||
(!disabled(&next)).then_some((*child, next))
|
||||
})
|
||||
.collect();
|
||||
if children.is_empty() {
|
||||
if !path.is_empty() {
|
||||
out.push(path);
|
||||
}
|
||||
} else {
|
||||
stack.extend(children.into_iter().rev());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The end of the local day: "today" in the counts includes everything due before it.
|
||||
pub(crate) fn end_of_today() -> i64 {
|
||||
use chrono::{Local, TimeZone};
|
||||
let now = Local::now();
|
||||
let tomorrow = now.date_naive().succ_opt().unwrap_or(now.date_naive());
|
||||
tomorrow
|
||||
.and_hms_opt(0, 0, 0)
|
||||
.and_then(|midnight| Local.from_local_datetime(&midnight).earliest())
|
||||
.map_or(now.timestamp() + 24 * 60 * 60, |midnight| {
|
||||
midnight.timestamp() - 1
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn now() -> i64 {
|
||||
chrono::Local::now().timestamp()
|
||||
}
|
||||
|
||||
/// "today at 18:40", "tomorrow", "in 3 days", then a date as in the library.
|
||||
pub(crate) fn when(at: i64, now: i64) -> String {
|
||||
use chrono::{Local, TimeZone};
|
||||
let (Some(at), Some(now)) = (
|
||||
Local.timestamp_opt(at, 0).single(),
|
||||
Local.timestamp_opt(now, 0).single(),
|
||||
) else {
|
||||
return String::new();
|
||||
};
|
||||
let days = (at.date_naive() - now.date_naive()).num_days();
|
||||
match days {
|
||||
..=0 => trf("today at {time}", &[("time", &at.format("%H:%M"))]),
|
||||
1 => tr("tomorrow").to_owned(),
|
||||
2..=6 => trf("in {days} days", &[("days", &days)]),
|
||||
_ => at.format("%d.%m.%Y").to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct BoardAnnotations {
|
||||
pub(crate) arrows: Vec<Arrow>,
|
||||
pub(crate) circles: Vec<(Square, Color32)>,
|
||||
pub(crate) badge: Option<Badge>,
|
||||
}
|
||||
|
||||
/// The marks of a PGN move on the board: its assessment badge, `[%cal]` arrows and
|
||||
/// `[%csl]` squares.
|
||||
pub(crate) fn pgn_annotations_at(game: &Game, at: NodeId) -> BoardAnnotations {
|
||||
let mut out = BoardAnnotations::default();
|
||||
let Some(node) = game.node(at) else {
|
||||
return out;
|
||||
};
|
||||
let square = node.game_move().and_then(|game_move| match game_move.kind {
|
||||
MoveKind::Normal(mv) => Some(crate::board::ui_target(&mv)),
|
||||
MoveKind::Null => None,
|
||||
});
|
||||
if let Some(square) = square {
|
||||
out.badge = node
|
||||
.nags()
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|nag| nag.is_move_assessment())
|
||||
.and_then(|nag| {
|
||||
Some(Badge {
|
||||
square,
|
||||
text: nag.symbol()?,
|
||||
color: crate::notation::assessment_color(nag)?,
|
||||
})
|
||||
});
|
||||
}
|
||||
for comment in node.comments_after() {
|
||||
for part in parse_comment(comment) {
|
||||
match part {
|
||||
CommentPart::Annotation(Annotation::Arrows(list)) => {
|
||||
out.arrows
|
||||
.extend(list.into_iter().map(|(color, from, to)| Arrow {
|
||||
from,
|
||||
to,
|
||||
color: crate::game_view::shape_color(color),
|
||||
weight: 0.9,
|
||||
}));
|
||||
}
|
||||
CommentPart::Annotation(Annotation::Squares(list)) => {
|
||||
out.circles.extend(
|
||||
list.into_iter()
|
||||
.map(|(color, square)| (square, crate::game_view::shape_color(color))),
|
||||
);
|
||||
}
|
||||
CommentPart::Text(_) | CommentPart::Annotation(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The position after a node, for a board that only shows it.
|
||||
pub(crate) fn position_of(game: &Game, node: NodeId) -> chess_core::shakmaty::Chess {
|
||||
game.position(node)
|
||||
.or_else(|| game.position(NodeId::ROOT))
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A board that only shows a position.
|
||||
pub(crate) fn still_board(
|
||||
ui: &mut Ui,
|
||||
state: &mut crate::board::BoardState,
|
||||
settings: &Settings,
|
||||
pos: &chess_core::shakmaty::Chess,
|
||||
orientation: Color,
|
||||
last_move: Option<(Square, Square)>,
|
||||
annotations: &BoardAnnotations,
|
||||
) {
|
||||
crate::board::BoardView {
|
||||
pos,
|
||||
orientation,
|
||||
last_move,
|
||||
arrows: &annotations.arrows,
|
||||
circles: &annotations.circles,
|
||||
badge: annotations.badge,
|
||||
interactive: false,
|
||||
temporary_shapes: false,
|
||||
show_coords: settings.show_coords,
|
||||
theme: settings.board_theme.theme(),
|
||||
pieces: settings.piece_set,
|
||||
animation: settings.animation.seconds(),
|
||||
premove: None,
|
||||
auto_queen: false,
|
||||
alert: None,
|
||||
}
|
||||
.show(ui, state);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn pgn_node_badges_keep_the_existing_palette_and_special_move_destinations() {
|
||||
for (nag, symbol) in [
|
||||
(1, "!"),
|
||||
(2, "?"),
|
||||
(3, "!!"),
|
||||
(4, "??"),
|
||||
(5, "!?"),
|
||||
(6, "?!"),
|
||||
] {
|
||||
let game = chess_core::parse_str(&format!("1. e4 ${nag} *")).game;
|
||||
let node = game.main_child(NodeId::ROOT).unwrap();
|
||||
let badge = pgn_annotations_at(&game, node).badge.unwrap();
|
||||
assert_eq!(badge.text, symbol);
|
||||
assert_eq!(badge.square, Square::E4);
|
||||
assert_eq!(
|
||||
badge.color,
|
||||
crate::notation::assessment_color(chess_core::Nag(nag)).unwrap()
|
||||
);
|
||||
}
|
||||
for (fen, san, expected) in [
|
||||
("4k3/8/8/8/8/8/8/4K2R w K - 0 1", "O-O!!", Square::G1),
|
||||
("4k3/P7/8/8/8/8/8/4K3 w - - 0 1", "a8=Q+!", Square::A8),
|
||||
] {
|
||||
let game =
|
||||
chess_core::parse_str(&format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n1. {san} *"))
|
||||
.game;
|
||||
let node = game.main_child(NodeId::ROOT).unwrap();
|
||||
assert_eq!(
|
||||
pgn_annotations_at(&game, node).badge.unwrap().square,
|
||||
expected
|
||||
);
|
||||
}
|
||||
let game = chess_core::parse_str("1. e4 $14 *").game;
|
||||
let node = game.main_child(NodeId::ROOT).unwrap();
|
||||
assert!(
|
||||
pgn_annotations_at(&game, node).badge.is_none(),
|
||||
"position assessments are not move badges"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pgn_shapes_of_a_move_become_arrows_and_circles() {
|
||||
let game = chess_core::parse_str("1. e4 {[%cal Re2e4,Ge7e5] [%csl Ye4]} *").game;
|
||||
let node = game.main_child(NodeId::ROOT).unwrap();
|
||||
let marks = pgn_annotations_at(&game, node);
|
||||
assert_eq!(marks.arrows.len(), 2);
|
||||
assert_eq!(
|
||||
marks.arrows[0].color,
|
||||
crate::game_view::shape_color(chess_core::ShapeColor::Red)
|
||||
);
|
||||
assert_eq!(
|
||||
marks.circles,
|
||||
[(
|
||||
Square::E4,
|
||||
crate::game_view::shape_color(chess_core::ShapeColor::Yellow)
|
||||
)]
|
||||
);
|
||||
assert!(pgn_annotations_at(&game, NodeId::ROOT).badge.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn common_start_stops_before_the_first_branching() {
|
||||
let game = chess_core::parse_str("1. e4 e5 2. Nf3 (2. Bc4) Nc6 *").game;
|
||||
let start = common_start(&game);
|
||||
assert_eq!(uci_path(&game, start), ["e2e4", "e7e5"]);
|
||||
let game = chess_core::parse_str("1. e4 (1. d4) *").game;
|
||||
assert_eq!(common_start(&game), NodeId::ROOT);
|
||||
let game = chess_core::parse_str("*").game;
|
||||
assert_eq!(common_start(&game), NodeId::ROOT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_are_the_last_moves_in_pgn_order_without_switched_off_branches() {
|
||||
let game = chess_core::parse_str("1. e4 e5 (1... c5 2. Nf3) 2. Nf3 (2. Bc4) *").game;
|
||||
let all = lines(&game, |_| false);
|
||||
assert_eq!(
|
||||
all,
|
||||
[
|
||||
vec!["e2e4", "e7e5", "g1f3"],
|
||||
vec!["e2e4", "e7e5", "f1c4"],
|
||||
vec!["e2e4", "c7c5", "g1f3"],
|
||||
]
|
||||
.map(|line| line.into_iter().map(str::to_owned).collect::<Vec<_>>())
|
||||
);
|
||||
let without_c5 = lines(&game, |path| {
|
||||
path.starts_with(&["e2e4".into(), "c7c5".into()])
|
||||
});
|
||||
assert_eq!(without_c5.len(), 2);
|
||||
let node = node_at(&game, &all[1]).unwrap();
|
||||
assert_eq!(uci_path(&game, node), all[1]);
|
||||
assert_eq!(move_text(&game, node).as_deref(), Some("2. Bc4"));
|
||||
let black = node_at(&game, &all[2][..2]).unwrap();
|
||||
assert_eq!(move_text(&game, black).as_deref(), Some("1… c5"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dates_read_as_today_tomorrow_days_then_a_date() {
|
||||
let at = 1_800_000_000;
|
||||
assert!(when(at + 60, at).contains(':'));
|
||||
assert_eq!(when(at + 24 * 3600, at), tr("tomorrow"));
|
||||
assert!(when(at + 3 * 24 * 3600, at).contains('3'));
|
||||
assert_eq!(when(at + 30 * 24 * 3600, at).len(), 10);
|
||||
assert!(end_of_today() >= now());
|
||||
assert!(end_of_today() - now() < 24 * 3600 + 3600);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,566 +0,0 @@
|
|||
//! The «Lines» screen of opening training (spec §6.3): the repertoire's tree, read only,
|
||||
//! to choose what to train and which branches to leave out.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::mpsc;
|
||||
|
||||
use chess_core::shakmaty::Color;
|
||||
use chess_core::{Game, NodeId};
|
||||
use egui::{Key, KeyboardShortcut, Modifiers, RichText, Ui, vec2};
|
||||
use trainer::repertoire::{
|
||||
LearningData, LearningItemKey, LearningSide, Library, Repertoire, RepertoireId, StatsScope,
|
||||
active_learning_memberships,
|
||||
};
|
||||
|
||||
use crate::board::BoardState;
|
||||
use crate::i18n::{tr, trf};
|
||||
use crate::opening_layout::{self as layout, GAP, pgn_annotations_at};
|
||||
use crate::settings::Settings;
|
||||
|
||||
const SELECTED_H: f32 = 92.0;
|
||||
const TOOL_H: f32 = 28.0;
|
||||
const MAIN_W: f32 = 170.0;
|
||||
|
||||
pub enum LinesAction {
|
||||
Back,
|
||||
OpenSettings,
|
||||
/// Train the lines through this move (empty: every line).
|
||||
Train {
|
||||
through: Vec<String>,
|
||||
label: String,
|
||||
},
|
||||
/// Switch a branch off (`true`) or on again, from the move at this path.
|
||||
SetDisabled {
|
||||
path: Vec<String>,
|
||||
disabled: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// The repertoire's own moves with their paths and which of them are learnt; computed
|
||||
/// off the frame.
|
||||
struct Counts {
|
||||
moves: Vec<(Vec<String>, LearningItemKey)>,
|
||||
learnt: BTreeSet<LearningItemKey>,
|
||||
}
|
||||
|
||||
pub struct OpeningLinesUi {
|
||||
id: RepertoireId,
|
||||
name: String,
|
||||
side: LearningSide,
|
||||
repertoire: Repertoire,
|
||||
game: Game,
|
||||
lines: Vec<Vec<String>>,
|
||||
cursor: NodeId,
|
||||
scroll: bool,
|
||||
orientation: Color,
|
||||
board: BoardState,
|
||||
counts: Option<Counts>,
|
||||
counting: Option<mpsc::Receiver<Result<Counts, String>>>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
impl OpeningLinesUi {
|
||||
pub fn new(
|
||||
library: &Library,
|
||||
learning: &LearningData,
|
||||
id: RepertoireId,
|
||||
side: LearningSide,
|
||||
cursor: Option<Vec<String>>,
|
||||
) -> Option<Self> {
|
||||
let repertoire = library.repertoire(&id)?.clone();
|
||||
let game = repertoire.game();
|
||||
let cursor = cursor
|
||||
.and_then(|path| layout::node_at(&game, &path))
|
||||
.unwrap_or(NodeId::ROOT);
|
||||
let lines = layout::lines(&game, |path| repertoire.is_prefix_disabled(path));
|
||||
let mut this = Self {
|
||||
id,
|
||||
name: repertoire.name.clone(),
|
||||
side,
|
||||
repertoire,
|
||||
game,
|
||||
lines,
|
||||
cursor,
|
||||
scroll: true,
|
||||
orientation: layout::orientation(side),
|
||||
board: BoardState::default(),
|
||||
counts: None,
|
||||
counting: None,
|
||||
error: None,
|
||||
};
|
||||
this.count(library, learning);
|
||||
Some(this)
|
||||
}
|
||||
|
||||
pub fn id(&self) -> &RepertoireId {
|
||||
&self.id
|
||||
}
|
||||
|
||||
pub fn cursor_path(&self) -> Vec<String> {
|
||||
layout::uci_path(&self.game, self.cursor)
|
||||
}
|
||||
|
||||
/// The library changed (a branch switched off or on): recount, keep the move.
|
||||
pub fn refresh(&mut self, library: &Library, learning: &LearningData) {
|
||||
if let Some(repertoire) = library.repertoire(&self.id) {
|
||||
self.repertoire = repertoire.clone();
|
||||
self.name = repertoire.name.clone();
|
||||
self.lines = layout::lines(&self.game, |path| repertoire.is_prefix_disabled(path));
|
||||
}
|
||||
self.count(library, learning);
|
||||
}
|
||||
|
||||
fn count(&mut self, library: &Library, learning: &LearningData) {
|
||||
let library = library.clone();
|
||||
let learning = learning.clone();
|
||||
let scope = StatsScope::for_repertoire(self.id.clone(), self.side, layout::now());
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.counting = Some(rx);
|
||||
if let Err(error) = crate::platform::spawn("repertoire-lines-count", move || {
|
||||
let result = active_learning_memberships(&library, &scope)
|
||||
.map(|memberships| {
|
||||
let learnt = memberships
|
||||
.iter()
|
||||
.filter(|membership| {
|
||||
learning
|
||||
.item(&membership.key)
|
||||
.is_some_and(|item| item.is_learnt())
|
||||
})
|
||||
.map(|membership| membership.key.clone())
|
||||
.collect();
|
||||
Counts {
|
||||
moves: memberships
|
||||
.into_iter()
|
||||
.map(|membership| (membership.path, membership.key))
|
||||
.collect(),
|
||||
learnt,
|
||||
}
|
||||
})
|
||||
.map_err(|error| error.to_string());
|
||||
let _ = tx.send(result);
|
||||
}) {
|
||||
self.counting = None;
|
||||
self.error = Some(error.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn poll(&mut self) {
|
||||
let Some(rx) = &self.counting else {
|
||||
return;
|
||||
};
|
||||
match rx.try_recv() {
|
||||
Ok(Ok(counts)) => {
|
||||
self.counts = Some(counts);
|
||||
self.counting = None;
|
||||
}
|
||||
Ok(Err(error)) => {
|
||||
self.error = Some(error);
|
||||
self.counting = None;
|
||||
}
|
||||
Err(mpsc::TryRecvError::Empty) => {}
|
||||
Err(mpsc::TryRecvError::Disconnected) => self.counting = None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The prefix that switches this path off, if any.
|
||||
fn disabled_by(&self, path: &[String]) -> Option<Vec<String>> {
|
||||
self.repertoire
|
||||
.disabled_prefixes
|
||||
.iter()
|
||||
.filter(|prefix| path.starts_with(prefix))
|
||||
.min_by_key(|prefix| prefix.len())
|
||||
.cloned()
|
||||
}
|
||||
|
||||
fn goto(&mut self, node: NodeId) {
|
||||
if self.game.node(node).is_some() {
|
||||
self.cursor = node;
|
||||
self.scroll = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn keyboard(&mut self, ui: &Ui, actions: &mut Vec<LinesAction>) {
|
||||
if ui.ctx().egui_wants_keyboard_input() || crate::app::overlay_open(ui.ctx()) {
|
||||
return;
|
||||
}
|
||||
let mut command = None;
|
||||
ui.input_mut(|input| {
|
||||
for (key, name) in [
|
||||
(Key::ArrowLeft, "back"),
|
||||
(Key::ArrowRight, "forward"),
|
||||
(Key::ArrowUp, "previous"),
|
||||
(Key::ArrowDown, "next"),
|
||||
(Key::Home, "home"),
|
||||
(Key::End, "end"),
|
||||
(Key::F, "flip"),
|
||||
(Key::Enter, "train"),
|
||||
(Key::Escape, "back_screen"),
|
||||
] {
|
||||
if command.is_none()
|
||||
&& (input.consume_key(Modifiers::NONE, key)
|
||||
|| input.consume_key(Modifiers::SHIFT, key))
|
||||
{
|
||||
command = Some(name);
|
||||
}
|
||||
}
|
||||
if command.is_none()
|
||||
&& input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::W))
|
||||
{
|
||||
command = Some("back_screen");
|
||||
}
|
||||
});
|
||||
let game = &self.game;
|
||||
let cursor = self.cursor;
|
||||
match command {
|
||||
Some("back") => {
|
||||
if let Some(parent) = game.parent(cursor) {
|
||||
self.goto(parent);
|
||||
}
|
||||
}
|
||||
Some("forward") => {
|
||||
if let Some(next) = game.main_child(cursor) {
|
||||
self.goto(next);
|
||||
}
|
||||
}
|
||||
Some("previous") => {
|
||||
if let Some(other) = game.prev_sibling(cursor) {
|
||||
self.goto(other);
|
||||
}
|
||||
}
|
||||
Some("next") => {
|
||||
if let Some(other) = game.next_sibling(cursor) {
|
||||
self.goto(other);
|
||||
}
|
||||
}
|
||||
Some("home") => self.goto(NodeId::ROOT),
|
||||
Some("end") => {
|
||||
let end = game.line_end(cursor);
|
||||
self.goto(end);
|
||||
}
|
||||
Some("flip") => self.orientation = self.orientation.other(),
|
||||
Some("train") => actions.push(self.train_action()),
|
||||
Some("back_screen") => actions.push(LinesAction::Back),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn train_action(&self) -> LinesAction {
|
||||
let through = self.cursor_path();
|
||||
let label = self.path_label(self.cursor);
|
||||
LinesAction::Train { through, label }
|
||||
}
|
||||
|
||||
/// "… 4. Ba4 Nf6": the moves to a node in the notation of the application.
|
||||
fn path_label(&self, node: NodeId) -> String {
|
||||
layout::path_text(&self.game, node)
|
||||
}
|
||||
|
||||
fn below(&self, path: &[String]) -> Option<(usize, usize, usize)> {
|
||||
let counts = self.counts.as_ref()?;
|
||||
let lines = self
|
||||
.lines
|
||||
.iter()
|
||||
.filter(|line| line.starts_with(path))
|
||||
.count();
|
||||
let mine: Vec<_> = counts
|
||||
.moves
|
||||
.iter()
|
||||
.filter(|(move_path, _)| move_path.starts_with(path))
|
||||
.collect();
|
||||
let learnt = mine
|
||||
.iter()
|
||||
.filter(|(_, key)| counts.learnt.contains(key))
|
||||
.count();
|
||||
Some((lines, mine.len(), learnt))
|
||||
}
|
||||
|
||||
fn selected_block(&self, ui: &mut Ui, actions: &mut Vec<LinesAction>) {
|
||||
let path = self.cursor_path();
|
||||
let disabled = self.disabled_by(&path);
|
||||
layout::fixed_block(ui, SELECTED_H, |ui| {
|
||||
let inner = layout::card_inner(ui, SELECTED_H);
|
||||
layout::card(ui, false, false).show(ui, |ui| {
|
||||
ui.set_min_size(inner);
|
||||
ui.set_max_size(inner);
|
||||
ui.spacing_mut().item_spacing.y = 4.0;
|
||||
if self.cursor == NodeId::ROOT {
|
||||
layout::line(ui, RichText::new(tr("Start position")).strong());
|
||||
} else {
|
||||
layout::line_left(ui, &self.path_label(self.cursor), true);
|
||||
}
|
||||
if disabled.is_some() {
|
||||
layout::line(
|
||||
ui,
|
||||
RichText::new(tr("Not trained")).color(ui.visuals().warn_fg_color),
|
||||
);
|
||||
} else {
|
||||
let text = match self.below(&path) {
|
||||
Some((lines, mine, learnt)) => trf(
|
||||
"Below: {n} lines · {y} your moves · consolidated {x}",
|
||||
&[("n", &lines), ("y", &mine), ("x", &learnt)],
|
||||
),
|
||||
None => tr("Counting moves…").to_owned(),
|
||||
};
|
||||
layout::line(ui, RichText::new(text).weak());
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
let label = if self.cursor == NodeId::ROOT {
|
||||
tr("Review all lines")
|
||||
} else {
|
||||
tr("Train this branch")
|
||||
};
|
||||
let width = MAIN_W.min(ui.available_width() / 2.0 - 4.0);
|
||||
let can_train = disabled.is_none() && !self.lines.is_empty();
|
||||
if ui
|
||||
.add_enabled_ui(can_train, |ui| {
|
||||
crate::widgets::primary_wide(ui, label, width)
|
||||
})
|
||||
.inner
|
||||
.on_hover_text("Enter")
|
||||
.clicked()
|
||||
{
|
||||
actions.push(self.train_action());
|
||||
}
|
||||
if self.cursor != NodeId::ROOT {
|
||||
let (label, action) = match &disabled {
|
||||
Some(prefix) => (
|
||||
tr("Train again"),
|
||||
LinesAction::SetDisabled {
|
||||
path: prefix.clone(),
|
||||
disabled: false,
|
||||
},
|
||||
),
|
||||
None => (
|
||||
tr("Don't train"),
|
||||
LinesAction::SetDisabled {
|
||||
path: path.clone(),
|
||||
disabled: true,
|
||||
},
|
||||
),
|
||||
};
|
||||
if ui
|
||||
.add(
|
||||
egui::Button::new(label)
|
||||
.truncate()
|
||||
.min_size(vec2(width, 30.0)),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
actions.push(action);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn side(&mut self, ui: &mut Ui, actions: &mut Vec<LinesAction>) {
|
||||
let rect = ui.available_rect_before_wrap();
|
||||
let footer_h = TOOL_H + 12.0;
|
||||
let footer = egui::Rect::from_min_max(
|
||||
egui::pos2(rect.left(), (rect.bottom() - footer_h).max(rect.top())),
|
||||
rect.max,
|
||||
);
|
||||
let body = egui::Rect::from_min_max(rect.min, egui::pos2(rect.right(), footer.top()));
|
||||
let mut clicked = None;
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(body), |ui| {
|
||||
ui.set_clip_rect(body.intersect(ui.clip_rect()));
|
||||
ui.spacing_mut().item_spacing.y = GAP;
|
||||
ui.add_space(4.0);
|
||||
let opening = layout::opening_text(&self.game, self.cursor);
|
||||
layout::fixed_block(ui, 20.0, |ui| {
|
||||
layout::line(ui, RichText::new(opening).weak());
|
||||
});
|
||||
let tree = (ui.available_height() - SELECTED_H - GAP).max(0.0);
|
||||
let scroll = std::mem::take(&mut self.scroll);
|
||||
let game = &self.game;
|
||||
let cursor = self.cursor;
|
||||
let response = layout::fixed_block(ui, tree, |ui| {
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("opening_lines_tree")
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
crate::notation::Notation {
|
||||
game,
|
||||
cursor,
|
||||
scroll_to_cursor: scroll,
|
||||
marks: None,
|
||||
preview: None,
|
||||
translations: None,
|
||||
editor: None,
|
||||
read_only: true,
|
||||
dim_until: None,
|
||||
mistakes: None,
|
||||
shapes: None,
|
||||
}
|
||||
.show(ui)
|
||||
})
|
||||
.inner
|
||||
});
|
||||
clicked = response.clicked;
|
||||
if let Some(error) = &self.error {
|
||||
ui.colored_label(ui.visuals().warn_fg_color, error);
|
||||
}
|
||||
self.selected_block(ui, actions);
|
||||
});
|
||||
if let Some(node) = clicked {
|
||||
self.cursor = node;
|
||||
}
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(footer), |ui| {
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
let icon = |s: &str| {
|
||||
egui::Button::new(RichText::new(s).size(18.0)).min_size(vec2(0.0, TOOL_H))
|
||||
};
|
||||
let game = &self.game;
|
||||
let mut target = None;
|
||||
if ui.add(icon("⏮")).clicked() {
|
||||
target = Some(NodeId::ROOT);
|
||||
}
|
||||
if ui.add(icon("◀")).clicked() {
|
||||
target = game.parent(self.cursor);
|
||||
}
|
||||
if ui.add(icon("▶")).clicked() {
|
||||
target = game.main_child(self.cursor);
|
||||
}
|
||||
if ui.add(icon("⏭")).clicked() {
|
||||
target = Some(game.line_end(self.cursor));
|
||||
}
|
||||
ui.separator();
|
||||
if ui
|
||||
.add(icon("🔃"))
|
||||
.on_hover_text(tr("Flip board (F)"))
|
||||
.clicked()
|
||||
{
|
||||
self.orientation = self.orientation.other();
|
||||
}
|
||||
if let Some(target) = target {
|
||||
self.goto(target);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub fn show(&mut self, ui: &mut Ui, settings: &Settings) -> Vec<LinesAction> {
|
||||
self.poll();
|
||||
if self.counting.is_some() {
|
||||
ui.ctx()
|
||||
.request_repaint_after(std::time::Duration::from_millis(50));
|
||||
}
|
||||
let mut actions = Vec::new();
|
||||
self.keyboard(ui, &mut actions);
|
||||
let back = if ui.available_width() < 600.0 {
|
||||
"⬅"
|
||||
} else {
|
||||
tr("⬅ Repertoires")
|
||||
};
|
||||
let subtitle = trf(
|
||||
"Lines · {n} lines · {y} your moves",
|
||||
&[
|
||||
("n", &self.lines.len()),
|
||||
(
|
||||
"y",
|
||||
&self
|
||||
.counts
|
||||
.as_ref()
|
||||
.map_or_else(|| "…".to_owned(), |counts| counts.moves.len().to_string()),
|
||||
),
|
||||
],
|
||||
);
|
||||
let name = self.name.clone();
|
||||
let mut header = (false, false);
|
||||
layout::screen(
|
||||
ui,
|
||||
self,
|
||||
|_, ui| header = crate::widgets::section_header_sub(ui, back, &name, &subtitle),
|
||||
|this, ui| this.side(ui, &mut actions),
|
||||
|this, ui| {
|
||||
let position = layout::position_of(&this.game, this.cursor);
|
||||
let marks = pgn_annotations_at(&this.game, this.cursor);
|
||||
let last = layout::last_move(&this.game, this.cursor);
|
||||
layout::still_board(
|
||||
ui,
|
||||
&mut this.board,
|
||||
settings,
|
||||
&position,
|
||||
this.orientation,
|
||||
last,
|
||||
&marks,
|
||||
);
|
||||
},
|
||||
);
|
||||
if header.0 {
|
||||
actions.push(LinesAction::Back);
|
||||
}
|
||||
if header.1 {
|
||||
actions.push(LinesAction::OpenSettings);
|
||||
}
|
||||
actions
|
||||
}
|
||||
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
pub fn debug_select(&mut self, path: &[String]) {
|
||||
if let Some(node) = layout::node_at(&self.game, path) {
|
||||
self.goto(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn lines_ui(pgn: &str) -> (Library, OpeningLinesUi) {
|
||||
let mut library = Library::default();
|
||||
let id = library
|
||||
.create("Lines", &chess_core::parse_str(pgn).game)
|
||||
.unwrap();
|
||||
let mut ui = OpeningLinesUi::new(
|
||||
&library,
|
||||
&LearningData::default(),
|
||||
id,
|
||||
LearningSide::White,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let deadline = web_time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
while ui.counting.is_some() && web_time::Instant::now() < deadline {
|
||||
ui.poll();
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
(library, ui)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_below_a_move_and_branches_switched_off() {
|
||||
let (mut library, mut ui) = lines_ui("1. e4 e5 (1... c5 2. Nf3) 2. Nf3 (2. Bc4) *");
|
||||
assert_eq!(ui.below(&[]), Some((3, 4, 0)));
|
||||
let c5 = ["e2e4".to_owned(), "c7c5".to_owned()];
|
||||
assert_eq!(ui.below(&c5), Some((1, 1, 0)));
|
||||
ui.debug_select(&c5);
|
||||
assert_eq!(ui.cursor_path(), c5);
|
||||
assert_eq!(ui.path_label(ui.cursor), "1. e4 c5");
|
||||
assert!(matches!(
|
||||
ui.train_action(),
|
||||
LinesAction::Train { through, .. } if through == c5
|
||||
));
|
||||
let id = ui.id().clone();
|
||||
library
|
||||
.repertoire_mut(&id)
|
||||
.unwrap()
|
||||
.set_prefix_disabled(&c5, true)
|
||||
.unwrap();
|
||||
ui.refresh(&library, &LearningData::default());
|
||||
let deadline = web_time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
while ui.counting.is_some() && web_time::Instant::now() < deadline {
|
||||
ui.poll();
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
assert_eq!(ui.lines.len(), 2);
|
||||
assert_eq!(
|
||||
ui.disabled_by(&[c5[0].clone(), c5[1].clone(), "g1f3".into()]),
|
||||
Some(c5.to_vec())
|
||||
);
|
||||
assert_eq!(ui.below(&[]), Some((2, 3, 0)));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -82,20 +82,8 @@ pub enum AfterCreate {
|
|||
AddGame,
|
||||
/// Add a copy of a record of a table to it.
|
||||
AddRecord { path: PathBuf, index: usize },
|
||||
/// Copy the chosen records of a table into it, in the table's order (task 42): the
|
||||
/// file is made by the copy, only when whole.
|
||||
CopySelection {
|
||||
path: PathBuf,
|
||||
records: Vec<u32>,
|
||||
sort: chess_import::chessbase::base::SortKey,
|
||||
ascending: bool,
|
||||
hidden: usize,
|
||||
},
|
||||
}
|
||||
|
||||
/// From this many chosen games on, the dialog says the copy may take a while.
|
||||
const MANY_GAMES: usize = 50_000;
|
||||
|
||||
pub struct NewBaseDialog {
|
||||
pub name: String,
|
||||
pub dir: PathBuf,
|
||||
|
|
@ -133,7 +121,7 @@ impl NewBaseDialog {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn path(&self) -> PathBuf {
|
||||
fn path(&self) -> PathBuf {
|
||||
self.dir.join(format!("{}.pgn", self.stem()))
|
||||
}
|
||||
|
||||
|
|
@ -155,41 +143,6 @@ impl NewBaseDialog {
|
|||
egui::Modal::new(egui::Id::new("new_base")).show(ctx, |ui| {
|
||||
ui.set_width(440.0);
|
||||
ui.heading(tr("New database"));
|
||||
let copy = matches!(self.after, AfterCreate::CopySelection { .. });
|
||||
if let AfterCreate::CopySelection {
|
||||
path,
|
||||
records,
|
||||
hidden,
|
||||
..
|
||||
} = &self.after
|
||||
{
|
||||
let weak = |ui: &mut egui::Ui, text: String| {
|
||||
ui.add(egui::Label::new(RichText::new(text).weak()).truncate());
|
||||
};
|
||||
weak(
|
||||
ui,
|
||||
trf(
|
||||
"From the selection: {games} from «{src}»",
|
||||
&[
|
||||
("games", &crate::i18n::games(records.len())),
|
||||
("src", &base_name(path)),
|
||||
],
|
||||
),
|
||||
);
|
||||
if *hidden > 0 {
|
||||
weak(
|
||||
ui,
|
||||
trf("{k} of them are hidden by the filter now", &[("k", hidden)]),
|
||||
);
|
||||
}
|
||||
if records.len() >= MANY_GAMES {
|
||||
weak(
|
||||
ui,
|
||||
tr("Many games: writing may take a few minutes; you can cancel it")
|
||||
.to_owned(),
|
||||
);
|
||||
}
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
ui.label(tr("Title"));
|
||||
let check = self.check();
|
||||
|
|
@ -242,21 +195,10 @@ impl NewBaseDialog {
|
|||
let enter = ui.input(|i| i.key_pressed(Key::Enter));
|
||||
match &check {
|
||||
Ok(false) => {
|
||||
let label = if copy {
|
||||
tr("Create and copy")
|
||||
} else {
|
||||
tr("Create")
|
||||
};
|
||||
if crate::widgets::primary(ui, label).clicked() || enter {
|
||||
if crate::widgets::primary(ui, tr("Create")).clicked() || enter {
|
||||
out = Some(NewBaseOutcome::Create(self.path()));
|
||||
}
|
||||
}
|
||||
// The copy goes into a new file only: the one there is not touched.
|
||||
Ok(true) if copy => {
|
||||
ui.add_enabled_ui(false, |ui| {
|
||||
crate::widgets::primary(ui, tr("Create and copy"))
|
||||
});
|
||||
}
|
||||
Ok(true) => {
|
||||
if crate::widgets::primary(ui, tr("Put it on the shelf")).clicked()
|
||||
|| enter
|
||||
|
|
@ -267,12 +209,9 @@ impl NewBaseDialog {
|
|||
// The same main button, only disabled: the row does not jump
|
||||
// when the first letter is typed.
|
||||
Err(_) => {
|
||||
let label = if copy {
|
||||
tr("Create and copy")
|
||||
} else {
|
||||
tr("Create")
|
||||
};
|
||||
ui.add_enabled_ui(false, |ui| crate::widgets::primary(ui, label));
|
||||
ui.add_enabled_ui(false, |ui| {
|
||||
crate::widgets::primary(ui, tr("Create"))
|
||||
});
|
||||
}
|
||||
}
|
||||
if ui.button(tr("Cancel")).clicked() {
|
||||
|
|
|
|||
|
|
@ -51,10 +51,6 @@ pub struct Caps {
|
|||
/// The reference tab (what was played here in the databases) and the search of a
|
||||
/// position in a database (not in the light web version).
|
||||
pub reference: bool,
|
||||
/// Several chosen games copied into a new database in the background (task 42).
|
||||
pub batch_copy: bool,
|
||||
/// The search for great moves over a database's list (task 27).
|
||||
pub great_moves: bool,
|
||||
}
|
||||
|
||||
/// The features of this platform.
|
||||
|
|
@ -70,8 +66,6 @@ pub const CAPS: Caps = Caps {
|
|||
training: true,
|
||||
download_pgn: false,
|
||||
reference: true,
|
||||
batch_copy: true,
|
||||
great_moves: true,
|
||||
};
|
||||
|
||||
/// The features of this platform: the light web version (`docs/decisions.md`, «Веб-версия»).
|
||||
|
|
@ -87,8 +81,6 @@ pub const CAPS: Caps = Caps {
|
|||
training: false,
|
||||
download_pgn: true,
|
||||
reference: false,
|
||||
batch_copy: false,
|
||||
great_moves: false,
|
||||
};
|
||||
|
||||
/// The program's settings (`~/.config/chesspenguin`; in a browser, its storage).
|
||||
|
|
|
|||
|
|
@ -1557,34 +1557,11 @@ impl Dialog {
|
|||
section(ui, tr("Your colour"));
|
||||
ui.horizontal(|ui| {
|
||||
for (c, label) in [
|
||||
(ColorChoice::White, tr("White")),
|
||||
(ColorChoice::White, tr("♔ White")),
|
||||
(ColorChoice::Random, tr("Random")),
|
||||
(ColorChoice::Black, tr("Black")),
|
||||
(ColorChoice::Black, tr("♚ Black")),
|
||||
] {
|
||||
let size = [(W - 2.0 * GAP) / 3.0, TILE_H];
|
||||
let on = self.prefs.color == c;
|
||||
let king = match c {
|
||||
ColorChoice::White => Some(true),
|
||||
ColorChoice::Black => Some(false),
|
||||
ColorChoice::Random => None,
|
||||
};
|
||||
let clicked = match king {
|
||||
Some(white) => ui
|
||||
.add_sized(
|
||||
size,
|
||||
egui::Button::selectable(
|
||||
on,
|
||||
(
|
||||
crate::widgets::side_king(white, 16.0),
|
||||
RichText::new(label).size(14.0),
|
||||
),
|
||||
)
|
||||
.frame_when_inactive(true),
|
||||
)
|
||||
.clicked(),
|
||||
None => choice(ui, on, label, size).clicked(),
|
||||
};
|
||||
if clicked {
|
||||
if choice(ui, self.prefs.color == c, label, [(W - 2.0 * GAP) / 3.0, TILE_H]).clicked() {
|
||||
self.prefs.color = c;
|
||||
}
|
||||
}
|
||||
|
|
@ -1877,7 +1854,6 @@ fn position_block(
|
|||
circles: &[],
|
||||
badge: None,
|
||||
interactive: false,
|
||||
temporary_shapes: false,
|
||||
show_coords: false,
|
||||
theme: settings.board_theme.theme(),
|
||||
pieces: settings.piece_set,
|
||||
|
|
|
|||
|
|
@ -1301,9 +1301,6 @@ fn cache_dir() -> Option<PathBuf> {
|
|||
pub struct PrepScreen {
|
||||
/// This screen's own number (`engine_offer::next_serial`).
|
||||
pub serial: u64,
|
||||
/// The engine is taken by another job (the search for great moves, task 27): the
|
||||
/// search for opening errors does not start, and says why.
|
||||
pub engine_blocked: Option<String>,
|
||||
pub path: PathBuf,
|
||||
db: Arc<Database>,
|
||||
db_name: String,
|
||||
|
|
@ -1679,7 +1676,6 @@ impl PrepScreen {
|
|||
});
|
||||
let mut screen = PrepScreen {
|
||||
serial: crate::engine_offer::next_serial(),
|
||||
engine_blocked: None,
|
||||
db_name: base_name(&start.path),
|
||||
path: start.path,
|
||||
db,
|
||||
|
|
@ -2190,10 +2186,6 @@ impl PrepScreen {
|
|||
if self.job.is_some() {
|
||||
return;
|
||||
}
|
||||
if let Some(why) = &self.engine_blocked {
|
||||
self.error = Some(why.clone());
|
||||
return;
|
||||
}
|
||||
self.error = None;
|
||||
// A start by hand (or by the new report) clears the manual Stop of this one.
|
||||
if let Some(report) = self.report.as_mut()
|
||||
|
|
@ -3585,7 +3577,6 @@ impl PrepScreen {
|
|||
circles: &[],
|
||||
badge: None,
|
||||
interactive: false,
|
||||
temporary_shapes: false,
|
||||
show_coords: settings.show_coords,
|
||||
theme: settings.board_theme.theme(),
|
||||
pieces: settings.piece_set,
|
||||
|
|
|
|||
1070
apps/desktop/src/repertoire_editor.rs
Normal file
1070
apps/desktop/src/repertoire_editor.rs
Normal file
File diff suppressed because it is too large
Load diff
1604
apps/desktop/src/repertoire_training.rs
Normal file
1604
apps/desktop/src/repertoire_training.rs
Normal file
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -194,13 +194,13 @@ pub struct Review {
|
|||
}
|
||||
|
||||
/// The folder of the cached analyses.
|
||||
pub fn cache_dir() -> Option<PathBuf> {
|
||||
fn cache_dir() -> Option<PathBuf> {
|
||||
Settings::cache_dir().map(|d| d.join("analysis"))
|
||||
}
|
||||
|
||||
/// The cached analyses in the program's files (the platform's: a folder of the disk, or
|
||||
/// the browser's storage).
|
||||
pub struct Cache(pub PathBuf);
|
||||
struct Cache(PathBuf);
|
||||
|
||||
impl game_review::CacheStore for Cache {
|
||||
fn read(&self, name: &str) -> Option<Vec<u8>> {
|
||||
|
|
@ -870,7 +870,7 @@ pub const DEFAULT_NPS: f64 = 700_000.0;
|
|||
/// ChessPenguin's Stockfish at `path` for an analysis job: below the program (nice 10),
|
||||
/// so that the program stays smooth while every CPU works.
|
||||
#[cfg(not(web))]
|
||||
pub fn engine_config(path: &Path) -> uci::EngineConfig {
|
||||
fn engine_config(path: &Path) -> uci::EngineConfig {
|
||||
uci::EngineConfig {
|
||||
nice: 10,
|
||||
..uci::EngineConfig::new(path)
|
||||
|
|
@ -936,7 +936,7 @@ pub fn judgement_name(j: Judgement) -> &'static str {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn judgement_plural(j: Judgement) -> &'static str {
|
||||
fn judgement_plural(j: Judgement) -> &'static str {
|
||||
match j {
|
||||
Judgement::Inaccuracy => tr("Inaccuracies"),
|
||||
Judgement::Mistake => tr("Mistakes"),
|
||||
|
|
@ -947,7 +947,7 @@ pub fn judgement_plural(j: Judgement) -> &'static str {
|
|||
}
|
||||
|
||||
/// Accuracy in the colors of the move marks: green, blue, orange, red.
|
||||
pub fn accuracy_color(a: f64, dark: bool) -> Color32 {
|
||||
fn accuracy_color(a: f64, dark: bool) -> Color32 {
|
||||
let j = if a >= 85.0 {
|
||||
Judgement::Great
|
||||
} else if a >= 70.0 {
|
||||
|
|
|
|||
|
|
@ -122,9 +122,6 @@ pub struct Settings {
|
|||
pub sound_set: SoundSet,
|
||||
pub volume: f32,
|
||||
pub dark_mode: bool,
|
||||
/// The width of the opening-training panel dragged by the user, in points; `None`:
|
||||
/// the default for the window.
|
||||
pub opening_side_width: Option<f32>,
|
||||
pub language: Lang,
|
||||
pub engines: Vec<EngineConfig>,
|
||||
pub active_engine: Option<usize>,
|
||||
|
|
@ -177,46 +174,6 @@ pub struct Settings {
|
|||
#[serde(default)]
|
||||
pub repertoire_context_policies:
|
||||
std::collections::HashMap<String, trainer::repertoire::LearningContextPolicy>,
|
||||
/// Hints shown until the user reacts (docs/design/tasks-42-43-2026-11-27.md §43.3).
|
||||
pub hints: Hints,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Hints {
|
||||
/// «Arrows and circles: the right mouse button on the board» above the notation.
|
||||
pub board_shapes: Hint,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Hint {
|
||||
/// Closed, or what it tells was done: never shown again.
|
||||
pub done: bool,
|
||||
/// Games it was shown in without a reaction.
|
||||
pub shown: u32,
|
||||
}
|
||||
|
||||
impl Hint {
|
||||
/// Shown in this many games without a reaction, the hint goes by itself.
|
||||
pub const SHOWS: u32 = 3;
|
||||
|
||||
/// A game opens where the hint can stand: whether it is shown there. A show counts
|
||||
/// once per game (`fresh`: the game was not shown the hint before in this session);
|
||||
/// such a game keeps it, the last counted one too.
|
||||
pub fn offer(&mut self, fresh: bool) -> bool {
|
||||
if self.done {
|
||||
return false;
|
||||
}
|
||||
if !fresh {
|
||||
return true;
|
||||
}
|
||||
if self.shown >= Self::SHOWS {
|
||||
return false;
|
||||
}
|
||||
self.shown += 1;
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Options of the opponent preparation; its engine search is the game analysis's.
|
||||
|
|
@ -264,7 +221,6 @@ impl Default for Settings {
|
|||
sound_set: SoundSet::default(),
|
||||
volume: 0.7,
|
||||
dark_mode: true,
|
||||
opening_side_width: None,
|
||||
language: Lang::default(),
|
||||
engines: Vec::new(),
|
||||
active_engine: None,
|
||||
|
|
@ -289,7 +245,6 @@ impl Default for Settings {
|
|||
repertoire_priorities: Default::default(),
|
||||
repertoire_context_policies: Default::default(),
|
||||
repertoire_flow_version: 0,
|
||||
hints: Hints::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -365,16 +320,6 @@ impl Settings {
|
|||
|
||||
/// Puts the database first on the shelf; a database there already by another path
|
||||
/// to the same file (a link) keeps its path. Returns the path on the shelf.
|
||||
/// Puts `path` at the end of the shelf, unless it is there: a database made in the
|
||||
/// background appears without moving the cards (task 42).
|
||||
pub fn add_database_last(&mut self, path: &Path) {
|
||||
let real = |p: &Path| std::fs::canonicalize(p).ok();
|
||||
let same = |p: &PathBuf| p == path || real(p).is_some_and(|r| Some(r) == real(path));
|
||||
if !self.databases.iter().any(same) {
|
||||
self.databases.push(path.to_path_buf());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn touch_database(&mut self, path: &Path) -> PathBuf {
|
||||
let real = |p: &Path| std::fs::canonicalize(p).ok();
|
||||
let same = |p: &PathBuf| p == path || real(p).is_some_and(|r| Some(r) == real(path));
|
||||
|
|
@ -410,66 +355,6 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
|||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A database made in the background goes to the end; opening it brings it first.
|
||||
#[test]
|
||||
fn a_copied_database_goes_to_the_end_of_the_shelf() {
|
||||
let mut s = Settings {
|
||||
databases: vec![PathBuf::from("/a.pgn"), PathBuf::from("/b.pgn")],
|
||||
..Default::default()
|
||||
};
|
||||
s.add_database_last(Path::new("/new.pgn"));
|
||||
s.add_database_last(Path::new("/a.pgn"));
|
||||
assert_eq!(
|
||||
s.databases,
|
||||
[
|
||||
PathBuf::from("/a.pgn"),
|
||||
PathBuf::from("/b.pgn"),
|
||||
PathBuf::from("/new.pgn")
|
||||
]
|
||||
);
|
||||
s.touch_database(Path::new("/new.pgn"));
|
||||
assert_eq!(s.databases[0], PathBuf::from("/new.pgn"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hint_goes_after_three_games_without_a_reaction() {
|
||||
let mut hint = Hint::default();
|
||||
assert!(hint.offer(true));
|
||||
// The same game opened again in the session: shown, not counted.
|
||||
assert!(hint.offer(false));
|
||||
assert!(hint.offer(true));
|
||||
assert!(hint.offer(true));
|
||||
assert_eq!(hint.shown, 3);
|
||||
// A fourth game: gone; a game already shown in the session keeps it.
|
||||
assert!(!hint.offer(true));
|
||||
assert!(hint.offer(false));
|
||||
assert_eq!(hint.shown, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hint_done_is_never_shown() {
|
||||
let mut hint = Hint {
|
||||
done: true,
|
||||
shown: 0,
|
||||
};
|
||||
assert!(!hint.offer(true));
|
||||
assert_eq!(hint.shown, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hints_survive_saving_and_old_settings_have_none() {
|
||||
let mut s = Settings::default();
|
||||
s.hints.board_shapes = Hint {
|
||||
done: false,
|
||||
shown: 2,
|
||||
};
|
||||
let json = serde_json::to_string(&s).unwrap();
|
||||
let back: Settings = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back.hints, s.hints);
|
||||
let old: Settings = serde_json::from_str(r#"{"show_coords": false}"#).unwrap();
|
||||
assert_eq!(old.hints, Hints::default());
|
||||
}
|
||||
|
||||
/// A database put on the shelf again by a link to its file stays itself, once.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -86,17 +86,7 @@ impl SettingsWindow {
|
|||
let mut actions = Vec::new();
|
||||
let mut changed = false;
|
||||
let mut open = self.open;
|
||||
// A real, unpainted click target: the opening click belongs to its
|
||||
// original widget, and the dismissing click never belongs to the board.
|
||||
let backdrop = open.then(|| {
|
||||
let rect = ctx.viewport_rect();
|
||||
egui::Area::new(egui::Id::new("settings_backdrop"))
|
||||
.fixed_pos(rect.min)
|
||||
.sense(Sense::click())
|
||||
.show(ctx, |ui| ui.set_min_size(rect.size()))
|
||||
.response
|
||||
});
|
||||
let window = egui::Window::new(tr("Settings"))
|
||||
egui::Window::new(tr("Settings"))
|
||||
.open(&mut open)
|
||||
.default_size(vec2(560.0, 680.0))
|
||||
// Open at the right edge so the board stays visible for live preview.
|
||||
|
|
@ -207,12 +197,6 @@ impl SettingsWindow {
|
|||
}
|
||||
});
|
||||
});
|
||||
if let (Some(backdrop), Some(window)) = (backdrop, window) {
|
||||
ctx.set_sublayer(backdrop.layer_id, window.response.layer_id);
|
||||
if backdrop.clicked_by(egui::PointerButton::Primary) {
|
||||
open = false;
|
||||
}
|
||||
}
|
||||
self.open = open;
|
||||
(actions, changed)
|
||||
}
|
||||
|
|
@ -535,13 +519,6 @@ fn board_tab(ui: &mut Ui, s: &mut Settings, changed: &mut bool) {
|
|||
notation_section(ui, s, changed);
|
||||
ui.add_space(8.0);
|
||||
ui.label(RichText::new(tr("Board")).strong());
|
||||
// The hint above the notation goes away; what it told stays here, in sight.
|
||||
ui.label(
|
||||
RichText::new(tr(
|
||||
"Arrows and circles: right mouse button on the board; Shift — red, Alt — blue, Shift+Alt — yellow. Saved in the move's comment ([%cal], [%csl]).",
|
||||
))
|
||||
.weak(),
|
||||
);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for id in BoardThemeId::ALL {
|
||||
let t = id.theme();
|
||||
|
|
@ -891,135 +868,3 @@ fn browser_data(ui: &mut Ui, actions: &mut Vec<SettingsAction>) {
|
|||
.weak(),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use egui::{Event, Modifiers, PointerButton, Pos2, Rect};
|
||||
|
||||
struct Screen {
|
||||
ctx: egui::Context,
|
||||
window: SettingsWindow,
|
||||
settings: Settings,
|
||||
opener: Rect,
|
||||
clicks: usize,
|
||||
}
|
||||
|
||||
impl Screen {
|
||||
fn new() -> Self {
|
||||
let mut screen = Self {
|
||||
ctx: Default::default(),
|
||||
window: SettingsWindow::new(),
|
||||
settings: Settings {
|
||||
language: Lang::En,
|
||||
..Default::default()
|
||||
},
|
||||
opener: Rect::NOTHING,
|
||||
clicks: 0,
|
||||
};
|
||||
screen.window.tab = Tab::Sound;
|
||||
screen.frame(vec![]);
|
||||
screen.click(screen.opener.center());
|
||||
screen.frame(vec![]);
|
||||
assert!(screen.window.open);
|
||||
assert_eq!(screen.clicks, 1);
|
||||
screen
|
||||
}
|
||||
|
||||
fn frame(&mut self, events: Vec<Event>) -> egui::FullOutput {
|
||||
let mut output = self.ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1280.0, 900.0))),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
let r = ui.button("Open settings");
|
||||
self.opener = r.rect;
|
||||
if r.clicked() {
|
||||
self.clicks += 1;
|
||||
self.window.open = true;
|
||||
}
|
||||
self.window
|
||||
.show(ui.ctx(), &mut self.settings, &mut Default::default());
|
||||
},
|
||||
);
|
||||
output.textures_delta.clear();
|
||||
output
|
||||
}
|
||||
|
||||
fn pointer(&mut self, pos: Pos2, button: PointerButton, pressed: bool) {
|
||||
self.frame(vec![
|
||||
Event::PointerMoved(pos),
|
||||
Event::PointerButton {
|
||||
pos,
|
||||
button,
|
||||
pressed,
|
||||
modifiers: Modifiers::NONE,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
fn click(&mut self, pos: Pos2) {
|
||||
self.pointer(pos, PointerButton::Primary, true);
|
||||
self.pointer(pos, PointerButton::Primary, false);
|
||||
}
|
||||
|
||||
fn text(&mut self, label: &str) -> Pos2 {
|
||||
self.frame(vec![])
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|shape| match &shape.shape {
|
||||
egui::Shape::Text(t) if t.galley.text() == label => {
|
||||
Some(t.pos + 0.5 * t.galley.size())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| panic!("missing visible label: {label}"))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_an_outside_primary_click_dismisses_and_it_never_reaches_the_opener() {
|
||||
let mut s = Screen::new();
|
||||
let outside = s.opener.center();
|
||||
s.pointer(outside, PointerButton::Secondary, true);
|
||||
s.pointer(outside, PointerButton::Secondary, false);
|
||||
assert!(s.window.open);
|
||||
|
||||
let inside = s.text(tr("Move sounds"));
|
||||
s.pointer(inside, PointerButton::Primary, true);
|
||||
s.frame(vec![Event::PointerMoved(outside)]);
|
||||
s.pointer(outside, PointerButton::Primary, false);
|
||||
assert!(s.window.open);
|
||||
s.pointer(outside, PointerButton::Primary, true);
|
||||
assert!(s.window.open);
|
||||
s.pointer(outside, PointerButton::Primary, false);
|
||||
assert!(!s.window.open);
|
||||
assert_eq!(s.clicks, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_tabs_popup_items_and_titlebar_close_still_receive_clicks() {
|
||||
let mut s = Screen::new();
|
||||
let interface = s.text(tr("Interface"));
|
||||
s.click(interface);
|
||||
assert!(s.window.tab == Tab::Interface);
|
||||
let combo = s.text(Lang::En.label());
|
||||
let layer = s.ctx.layer_id_at(combo).unwrap();
|
||||
let rect = s.ctx.memory(|m| m.area_rect(layer.id)).unwrap();
|
||||
s.click(combo);
|
||||
let choice = s.text(Lang::Kk.label());
|
||||
assert!(!rect.contains(choice), "exercise the overhanging popup");
|
||||
s.click(choice);
|
||||
assert_eq!(s.settings.language, Lang::Kk);
|
||||
assert!(s.window.open);
|
||||
|
||||
s.frame(vec![]);
|
||||
let title = s.text(tr("Settings"));
|
||||
let layer = s.ctx.layer_id_at(title).unwrap();
|
||||
let rect = s.ctx.memory(|m| m.area_rect(layer.id)).unwrap();
|
||||
s.click(egui::pos2(rect.right() - 15.0, title.y));
|
||||
assert!(!s.window.open);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,6 @@ pub fn settings_button(ui: &mut Ui, compact: bool) -> egui::Response {
|
|||
|
||||
/// A section header: reserve global actions before laying out a long title.
|
||||
/// Returns (back, settings).
|
||||
#[allow(dead_code)]
|
||||
pub fn section_header(ui: &mut Ui, back: &str, title: &str) -> (bool, bool) {
|
||||
let mut clicked = (false, false);
|
||||
let compact = ui.available_width() < 600.0;
|
||||
|
|
@ -30,43 +29,6 @@ pub fn section_header(ui: &mut Ui, back: &str, title: &str) -> (bool, bool) {
|
|||
clicked
|
||||
}
|
||||
|
||||
/// A two-line section header in the places of the game's (title and a quiet line under
|
||||
/// it; an empty subtitle keeps its line, so the header never changes height).
|
||||
/// Returns (back, settings).
|
||||
pub fn section_header_sub(ui: &mut Ui, back: &str, title: &str, subtitle: &str) -> (bool, bool) {
|
||||
let mut clicked = (false, false);
|
||||
let compact = ui.available_width() < 600.0;
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
clicked.0 = ui.button(back).clicked();
|
||||
ui.separator();
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
clicked.1 = settings_button(ui, compact).clicked();
|
||||
ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| {
|
||||
// The rows of the game screen's header (game_view.rs): the same height.
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(
|
||||
egui::Label::new(egui::RichText::new(title).strong().size(16.0)).truncate(),
|
||||
)
|
||||
.on_hover_text(title);
|
||||
});
|
||||
let sub = ui.add(
|
||||
egui::Label::new(
|
||||
egui::RichText::new(if subtitle.is_empty() { " " } else { subtitle })
|
||||
.weak(),
|
||||
)
|
||||
.truncate(),
|
||||
);
|
||||
if !subtitle.is_empty() {
|
||||
sub.on_hover_text(subtitle);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
clicked
|
||||
}
|
||||
|
||||
/// A dev check (`CP_PANEL_CHECK=1`): a panel whose content is wider than the panel. egui
|
||||
/// then moves a right panel out (its left part under the central panel, its right part
|
||||
/// off the window); the content of every panel must fit its least width
|
||||
|
|
@ -151,23 +113,6 @@ pub fn primary(ui: &mut egui::Ui, label: &str) -> egui::Response {
|
|||
primary_wide(ui, label, 0.0)
|
||||
}
|
||||
|
||||
/// The king of a side, `size` points square: White's light with a dark outline,
|
||||
/// Black's dark with a light one, the same in both themes (task 45; a font's ♔/♚ read
|
||||
/// the other way round on a dark background). From the classic set, whatever the board's.
|
||||
pub fn side_king(white: bool, size: f32) -> egui::Image<'static> {
|
||||
let color = if white {
|
||||
shakmaty::Color::White
|
||||
} else {
|
||||
shakmaty::Color::Black
|
||||
};
|
||||
crate::assets::PieceSet::Cburnett
|
||||
.image(shakmaty::Piece {
|
||||
color,
|
||||
role: shakmaty::Role::King,
|
||||
})
|
||||
.fit_to_exact_size(egui::vec2(size, size))
|
||||
}
|
||||
|
||||
/// `primary()` at least `width` wide (a button whose label changes keeps its place).
|
||||
pub fn primary_wide(ui: &mut egui::Ui, label: &str, width: f32) -> egui::Response {
|
||||
ui.add(
|
||||
|
|
|
|||
|
|
@ -232,66 +232,44 @@ pub fn write_utf8_copy(db: &PgnDatabase, dest: &Path) -> io::Result<()> {
|
|||
write_atomic(dest, &out)
|
||||
}
|
||||
|
||||
/// What makes two records the same game for [`find_same_game`]: the players (without
|
||||
/// case) and the date, the start position and the moves of the main line.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct SameGame {
|
||||
white: String,
|
||||
black: String,
|
||||
date: String,
|
||||
fen: Option<String>,
|
||||
moves: Vec<String>,
|
||||
}
|
||||
|
||||
fn same_name(v: Option<&str>) -> String {
|
||||
v.unwrap_or("?").trim().to_lowercase()
|
||||
}
|
||||
|
||||
fn same_date(v: Option<&str>) -> String {
|
||||
// An unknown date in any spelling is one value.
|
||||
match v.map(str::trim) {
|
||||
None | Some("" | "?") => "????.??.??".to_owned(),
|
||||
Some(d) => d.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The identity of `game` for finding the same game (see [`SameGame`]).
|
||||
pub fn same_game(game: &crate::Game) -> SameGame {
|
||||
SameGame {
|
||||
white: same_name(game.tag("White")),
|
||||
black: same_name(game.tag("Black")),
|
||||
date: same_date(game.tag("Date")),
|
||||
fen: game.tag("FEN").map(str::to_owned),
|
||||
moves: game
|
||||
.mainline()
|
||||
.iter()
|
||||
.filter_map(|id| game.game_move(*id).map(|m| m.san.clone()))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes an append writes for `record` into a file that holds only records written
|
||||
/// so (starting empty): a new database filled in one go has the same bytes as one
|
||||
/// filled by [`append`] record after record.
|
||||
pub fn record_for_new_file(record: &str) -> Vec<u8> {
|
||||
record_bytes(record, "\n")
|
||||
}
|
||||
|
||||
/// The record of `db` that is the same game as `game`: the same players and date, and
|
||||
/// the same moves of the main line. `None` when there is none.
|
||||
pub fn find_same_game(db: &PgnDatabase, game: &crate::Game) -> Option<usize> {
|
||||
let key = same_game(game);
|
||||
// Names compared without case; an unknown date in any spelling is one value.
|
||||
let name = |v: Option<&str>| v.unwrap_or("?").trim().to_lowercase();
|
||||
let date = |v: Option<&str>| match v.map(str::trim) {
|
||||
None | Some("" | "?") => "????.??.??".to_owned(),
|
||||
Some(d) => d.to_owned(),
|
||||
};
|
||||
let (white, black, when) = (
|
||||
name(game.tag("White")),
|
||||
name(game.tag("Black")),
|
||||
date(game.tag("Date")),
|
||||
);
|
||||
let sans: Vec<&str> = game
|
||||
.mainline()
|
||||
.iter()
|
||||
.filter_map(|id| game.game_move(*id).map(|m| m.san.as_str()))
|
||||
.collect();
|
||||
(0..db.len()).find(|&i| {
|
||||
let e = &db.entries()[i];
|
||||
if same_name(e.white()) != key.white
|
||||
|| same_name(e.black()) != key.black
|
||||
|| same_date(e.date()) != key.date
|
||||
{
|
||||
if name(e.white()) != white || name(e.black()) != black || date(e.date()) != when {
|
||||
return false;
|
||||
}
|
||||
let Some(parsed) = db.load_game(i) else {
|
||||
return false;
|
||||
};
|
||||
// Two studies from different positions are different games.
|
||||
db.load_game(i)
|
||||
.is_some_and(|parsed| same_game(&parsed.game) == key)
|
||||
if parsed.game.tag("FEN") != game.tag("FEN") {
|
||||
return false;
|
||||
}
|
||||
let other: Vec<String> = parsed
|
||||
.game
|
||||
.mainline()
|
||||
.iter()
|
||||
.filter_map(|id| parsed.game.game_move(*id).map(|m| m.san.clone()))
|
||||
.collect();
|
||||
other.len() == sans.len() && other.iter().zip(&sans).all(|(a, b)| a == b)
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -73,8 +73,6 @@ pub(crate) struct Names {
|
|||
folded: Vec<String>,
|
||||
rank: Vec<u32>,
|
||||
games: Vec<u32>,
|
||||
white_games: Vec<u32>,
|
||||
black_games: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Names {
|
||||
|
|
@ -92,15 +90,11 @@ impl Names {
|
|||
};
|
||||
}
|
||||
let games = vec![0; shown.len()];
|
||||
let white_games = vec![0; shown.len()];
|
||||
let black_games = vec![0; shown.len()];
|
||||
Names {
|
||||
shown,
|
||||
folded,
|
||||
rank,
|
||||
games,
|
||||
white_games,
|
||||
black_games,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -110,30 +104,6 @@ impl Names {
|
|||
}
|
||||
}
|
||||
|
||||
/// Counts one game of a player. A player on both sides still has one game in
|
||||
/// total, while each colour has that game in its own count.
|
||||
pub(crate) fn count_player_game(&mut self, white: u32, black: u32) {
|
||||
self.count(white);
|
||||
if black != white {
|
||||
self.count(black);
|
||||
}
|
||||
if let Some(n) = self.white_games.get_mut(white as usize) {
|
||||
*n += 1;
|
||||
}
|
||||
if let Some(n) = self.black_games.get_mut(black as usize) {
|
||||
*n += 1;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn player_counts(&self, id: u32) -> (u32, u32, u32) {
|
||||
let at = |values: &[u32]| values.get(id as usize).copied().unwrap_or(0);
|
||||
(
|
||||
at(&self.games),
|
||||
at(&self.white_games),
|
||||
at(&self.black_games),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn get(&self, id: u32) -> &str {
|
||||
self.shown.get(id as usize).map_or("", String::as_str)
|
||||
}
|
||||
|
|
@ -159,35 +129,19 @@ impl Names {
|
|||
/// Up to `limit` names containing every word of `query`: names starting with
|
||||
/// the first word first, then by number of games. Also the number of matches.
|
||||
pub(crate) fn suggest(&self, query: &str, limit: usize) -> (Vec<Suggestion>, usize) {
|
||||
self.suggest_page(query, 0, limit, false)
|
||||
}
|
||||
|
||||
/// A page of suggestions. With `all_when_empty`, an empty query lists every
|
||||
/// non-empty name alphabetically (the Android player picker); otherwise it has
|
||||
/// the old behaviour and returns no suggestions.
|
||||
pub(crate) fn suggest_page(
|
||||
&self,
|
||||
query: &str,
|
||||
start: usize,
|
||||
limit: usize,
|
||||
all_when_empty: bool,
|
||||
) -> (Vec<Suggestion>, usize) {
|
||||
let words = words(query);
|
||||
let all = words.is_empty() && all_when_empty;
|
||||
if words.is_empty() && !all {
|
||||
if words.is_empty() {
|
||||
return (Vec::new(), 0);
|
||||
}
|
||||
let mut hits: Vec<(bool, u32, u32)> = self
|
||||
.folded
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, n)| {
|
||||
!n.trim().is_empty() && (all || words.iter().all(|w| n.contains(w.as_str())))
|
||||
})
|
||||
.filter(|(_, n)| words.iter().all(|w| n.contains(w.as_str())))
|
||||
.map(|(id, n)| {
|
||||
let id = id as u32;
|
||||
(
|
||||
!all && !n.starts_with(words[0].as_str()),
|
||||
!n.starts_with(words[0].as_str()),
|
||||
id,
|
||||
self.games[id as usize],
|
||||
)
|
||||
|
|
@ -195,18 +149,12 @@ impl Names {
|
|||
.collect();
|
||||
let total = hits.len();
|
||||
hits.sort_by(|a, b| {
|
||||
if all {
|
||||
self.rank(a.1).cmp(&self.rank(b.1)).then(a.1.cmp(&b.1))
|
||||
} else {
|
||||
a.0.cmp(&b.0)
|
||||
.then(b.2.cmp(&a.2))
|
||||
.then(self.rank(a.1).cmp(&self.rank(b.1)))
|
||||
.then(a.1.cmp(&b.1))
|
||||
}
|
||||
a.0.cmp(&b.0)
|
||||
.then(b.2.cmp(&a.2))
|
||||
.then(self.rank(a.1).cmp(&self.rank(b.1)))
|
||||
});
|
||||
let list = hits
|
||||
.into_iter()
|
||||
.skip(start)
|
||||
.take(limit)
|
||||
.map(|(_, id, games)| Suggestion {
|
||||
id,
|
||||
|
|
@ -557,7 +505,8 @@ impl Base {
|
|||
if u(0x23, 2) >= 64576 {
|
||||
chess960 += 1;
|
||||
}
|
||||
base.players.count_player_game(u(0x09, 3), u(0x0c, 3));
|
||||
base.players.count(u(0x09, 3));
|
||||
base.players.count(u(0x0c, 3));
|
||||
base.tournaments.count(u(0x0f, 3));
|
||||
}
|
||||
base.games = games;
|
||||
|
|
@ -1057,21 +1006,6 @@ impl Base {
|
|||
self.players.suggest(query, limit)
|
||||
}
|
||||
|
||||
/// A page of player names; an empty query lists every named player.
|
||||
pub fn suggest_players_page(
|
||||
&self,
|
||||
query: &str,
|
||||
start: usize,
|
||||
limit: usize,
|
||||
) -> (Vec<Suggestion>, usize) {
|
||||
self.players.suggest_page(query, start, limit, true)
|
||||
}
|
||||
|
||||
/// Total, white and black games of a player (a self-game counts once in total).
|
||||
pub fn player_counts(&self, id: u32) -> (u32, u32, u32) {
|
||||
self.players.player_counts(id)
|
||||
}
|
||||
|
||||
/// Tournament names ("Title (Place)") for a filter being typed.
|
||||
pub fn suggest_events(&self, query: &str, limit: usize) -> (Vec<Suggestion>, usize) {
|
||||
self.tournaments.suggest(query, limit)
|
||||
|
|
|
|||
|
|
@ -32,18 +32,11 @@ pub(super) const CBB_RECORD: usize = 52;
|
|||
/// booster is left out (it would read its whole file to rule out almost nothing).
|
||||
const SAMPLE: usize = 4096;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum SearchMode {
|
||||
Explorer,
|
||||
PlayedLine,
|
||||
}
|
||||
|
||||
/// Games among `candidates` (record indices in ascending order; `None`: all records)
|
||||
/// whose main line reaches the position. `scanned` counts the candidates looked at.
|
||||
/// `None` when cancelled.
|
||||
fn search_inner(
|
||||
pub fn search(
|
||||
base: &Base,
|
||||
mode: SearchMode,
|
||||
candidates: Option<&[u32]>,
|
||||
query: &PositionQuery,
|
||||
scanned: &AtomicUsize,
|
||||
|
|
@ -51,12 +44,11 @@ fn search_inner(
|
|||
) -> Option<PositionOutcome> {
|
||||
// A position of the opening: the index knows its games, except those from a
|
||||
// set-up position, which the pass looks at.
|
||||
if mode == SearchMode::Explorer
|
||||
&& let Some(index) = base.openings()
|
||||
if let Some(index) = base.openings()
|
||||
&& index.answers(query, candidates)
|
||||
{
|
||||
let others = index.set_up_games(candidates);
|
||||
let mut out = collect(base, Some(&others), query, scanned, cancel, false)?;
|
||||
let mut out = collect(base, Some(&others), query, scanned, cancel)?;
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return None;
|
||||
}
|
||||
|
|
@ -65,51 +57,7 @@ fn search_inner(
|
|||
scanned.fetch_add(total.saturating_sub(others.len()), Ordering::Relaxed);
|
||||
return Some(out.finish(&query.position));
|
||||
}
|
||||
collect(
|
||||
base,
|
||||
candidates,
|
||||
query,
|
||||
scanned,
|
||||
cancel,
|
||||
mode == SearchMode::PlayedLine,
|
||||
)
|
||||
.map(|c| c.finish(&query.position))
|
||||
}
|
||||
|
||||
/// The position explorer: it may use the opening index.
|
||||
pub fn search(
|
||||
base: &Base,
|
||||
candidates: Option<&[u32]>,
|
||||
query: &PositionQuery,
|
||||
scanned: &AtomicUsize,
|
||||
cancel: &AtomicBool,
|
||||
) -> Option<PositionOutcome> {
|
||||
search_inner(
|
||||
base,
|
||||
SearchMode::Explorer,
|
||||
candidates,
|
||||
query,
|
||||
scanned,
|
||||
cancel,
|
||||
)
|
||||
}
|
||||
|
||||
/// The played-line preparation: never take the bounded opening index shortcut.
|
||||
pub fn search_first(
|
||||
base: &Base,
|
||||
candidates: Option<&[u32]>,
|
||||
query: &PositionQuery,
|
||||
scanned: &AtomicUsize,
|
||||
cancel: &AtomicBool,
|
||||
) -> Option<PositionOutcome> {
|
||||
search_inner(
|
||||
base,
|
||||
SearchMode::PlayedLine,
|
||||
candidates,
|
||||
query,
|
||||
scanned,
|
||||
cancel,
|
||||
)
|
||||
collect(base, candidates, query, scanned, cancel).map(|c| c.finish(&query.position))
|
||||
}
|
||||
|
||||
/// The pass of [`search`]: the matches in record order and the statistics, not yet
|
||||
|
|
@ -120,13 +68,12 @@ fn collect(
|
|||
query: &PositionQuery,
|
||||
scanned: &AtomicUsize,
|
||||
cancel: &AtomicBool,
|
||||
played_line: bool,
|
||||
) -> Option<Collector> {
|
||||
let total = candidates.map_or(base.records(), <[u32]>::len);
|
||||
if total == 0 {
|
||||
return Some(Collector::default());
|
||||
}
|
||||
let target = Target::new(query, played_line);
|
||||
let target = Target::new(query);
|
||||
let cbb = base
|
||||
.cbb_path()
|
||||
.filter(|p| booster_helps(p, &target.signature));
|
||||
|
|
@ -209,11 +156,10 @@ struct Target {
|
|||
line: Option<Vec<UciMove>>,
|
||||
start: Chess,
|
||||
signature: Signature,
|
||||
played_line: bool,
|
||||
}
|
||||
|
||||
impl Target {
|
||||
fn new(query: &PositionQuery, played_line: bool) -> Target {
|
||||
fn new(query: &PositionQuery) -> Target {
|
||||
let b = query.position.board();
|
||||
let side = |c: Color| b.by_color(c);
|
||||
let pawns = |c: Color| side(c) & b.pawns();
|
||||
|
|
@ -229,7 +175,6 @@ impl Target {
|
|||
line: query.line.as_ref().map(|l| l.iter().map(uci).collect()),
|
||||
start: Chess::default(),
|
||||
signature: Signature::new(b),
|
||||
played_line,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -249,15 +194,8 @@ impl Target {
|
|||
fn find(&self, cbg: &[u8], offset: u32, fast: bool) -> Result<Option<Hit>, WalkError> {
|
||||
let mut ply = 0u32;
|
||||
let mut in_order = self.line.is_some();
|
||||
let mut after_null = false;
|
||||
let mut hit = None;
|
||||
moves::main_line(cbg, offset, fast, |pos, step| {
|
||||
if self.played_line && after_null {
|
||||
return false;
|
||||
}
|
||||
if self.played_line && matches!(step, Step::Null) {
|
||||
after_null = true;
|
||||
}
|
||||
if ply == 0 && in_order && !same_position(pos, &self.start) {
|
||||
in_order = false;
|
||||
}
|
||||
|
|
@ -778,31 +716,6 @@ mod tests {
|
|||
assert_eq!(continuations as usize + nulls, want.len());
|
||||
let ended = want.iter().filter(|w| w.2.is_none()).count();
|
||||
assert_eq!(out.ended.games as usize, ended);
|
||||
let first = search_first(
|
||||
&base,
|
||||
candidates,
|
||||
&query,
|
||||
&AtomicUsize::new(0),
|
||||
&AtomicBool::new(false),
|
||||
)
|
||||
.expect("played-line search");
|
||||
let actual: Vec<(u32, u32, Option<UciMove>)> = first
|
||||
.matches
|
||||
.iter()
|
||||
.map(|m| (m.index, m.ply, m.next))
|
||||
.collect();
|
||||
let expected: Vec<(u32, u32, Option<UciMove>)> = want
|
||||
.iter()
|
||||
.filter(|(index, ply, _)| {
|
||||
!lines[*index as usize].as_ref().is_some_and(|line| {
|
||||
line[..*ply as usize]
|
||||
.iter()
|
||||
.any(|(_, next)| *next == Some(UciMove::Null))
|
||||
})
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
assert_eq!(actual, expected, "{name}: played-line first occurrence");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -309,25 +309,6 @@ impl Database {
|
|||
}
|
||||
}
|
||||
|
||||
/// Search the main line, counting each played game once at its first occurrence.
|
||||
pub fn search_position_first(
|
||||
&self,
|
||||
candidates: Option<&[u32]>,
|
||||
query: &position::PositionQuery,
|
||||
progress: &AtomicUsize,
|
||||
cancel: &AtomicBool,
|
||||
) -> Option<position::PositionOutcome> {
|
||||
match self {
|
||||
Database::Pgn(db) => {
|
||||
let table = db.positions(progress, cancel)?;
|
||||
table.search_first(&db.db, candidates, query, cancel)
|
||||
}
|
||||
Database::ChessBase(b) => {
|
||||
chessbase::search::search_first(b, candidates, query, progress, cancel)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Memory a position search would need first and does not have (a PGN
|
||||
/// database's table, see [`PgnDb::positions_blocked`]).
|
||||
pub fn positions_blocked(&self) -> Option<u64> {
|
||||
|
|
|
|||
|
|
@ -225,8 +225,8 @@ impl Catalog {
|
|||
let white: Vec<u32> = ids.iter().step_by(2).copied().collect();
|
||||
let black: Vec<u32> = ids.iter().skip(1).step_by(2).copied().collect();
|
||||
let mut players = Names::new(names);
|
||||
for sides in ids.as_chunks::<2>().0 {
|
||||
players.count_player_game(sides[0], sides[1]);
|
||||
for &id in &ids {
|
||||
players.count(id);
|
||||
}
|
||||
let (event_names, event) = intern(entries.iter().map(event_name));
|
||||
let mut events = Names::new(event_names);
|
||||
|
|
@ -311,55 +311,6 @@ impl Catalog {
|
|||
self.players.suggest(query, limit)
|
||||
}
|
||||
|
||||
/// A page of player names; an empty query lists every named player.
|
||||
pub fn suggest_players_page(
|
||||
&self,
|
||||
query: &str,
|
||||
start: usize,
|
||||
limit: usize,
|
||||
) -> (Vec<Suggestion>, usize) {
|
||||
self.players.suggest_page(query, start, limit, true)
|
||||
}
|
||||
|
||||
/// Total, white and black games of a player (a self-game counts once in total).
|
||||
pub fn player_counts(&self, id: u32) -> (u32, u32, u32) {
|
||||
self.players.player_counts(id)
|
||||
}
|
||||
|
||||
/// Games of exactly player `id` on one side, in record order. Ids come from
|
||||
/// [`Catalog::suggest_players_page`] and represent normalized distinct names;
|
||||
/// a self-game is returned once for either selected side.
|
||||
pub fn player_games(
|
||||
&self,
|
||||
id: u32,
|
||||
side: Side,
|
||||
scanned: &AtomicUsize,
|
||||
cancel: &AtomicBool,
|
||||
) -> Option<Vec<u32>> {
|
||||
if self.player_name(id).is_empty() || !matches!(side, Side::White | Side::Black) {
|
||||
return Some(Vec::new());
|
||||
}
|
||||
let mut games = Vec::new();
|
||||
for i in 0..self.white.len() {
|
||||
if i % 4096 == 0 {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return None;
|
||||
}
|
||||
scanned.store(i, Ordering::Relaxed);
|
||||
}
|
||||
let player = match side {
|
||||
Side::White => self.white[i],
|
||||
Side::Black => self.black[i],
|
||||
Side::Any => continue,
|
||||
};
|
||||
if !self.text[i] && player == id {
|
||||
games.push(i as u32);
|
||||
}
|
||||
}
|
||||
scanned.store(self.white.len(), Ordering::Relaxed);
|
||||
(!cancel.load(Ordering::Relaxed)).then_some(games)
|
||||
}
|
||||
|
||||
pub fn suggest_events(&self, query: &str, limit: usize) -> (Vec<Suggestion>, usize) {
|
||||
self.events.suggest(query, limit)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -262,54 +262,6 @@ impl PositionTable {
|
|||
Some(collector.finish(&query.position))
|
||||
}
|
||||
|
||||
/// The first main-line occurrence of every game, not a variation or a repetition.
|
||||
pub fn search_first(
|
||||
&self,
|
||||
db: &PgnDatabase,
|
||||
candidates: Option<&[u32]>,
|
||||
query: &PositionQuery,
|
||||
cancel: &AtomicBool,
|
||||
) -> Option<PositionOutcome> {
|
||||
let _ = db;
|
||||
let key = query.key();
|
||||
let lo = self.keys.partition_point(|&k| k < key);
|
||||
let hi = lo + self.keys[lo..].partition_point(|&k| k == key);
|
||||
let line: Option<Vec<u16>> = query
|
||||
.line
|
||||
.as_ref()
|
||||
.map(|l| l.iter().map(|m| encode(position::uci(m))).collect());
|
||||
let mut collector = Collector::default();
|
||||
let mut cand = 0;
|
||||
let mut game = 0;
|
||||
let mut i = lo;
|
||||
while i < hi {
|
||||
if (i - lo) % 4096 == 0 && cancel.load(Ordering::Relaxed) {
|
||||
return None;
|
||||
}
|
||||
let node = self.refs[i] >> 1;
|
||||
if node >= self.starts[game + 1] {
|
||||
game += self.starts[game..].partition_point(|&s| s <= node) - 1;
|
||||
}
|
||||
let end = self.starts[game + 1];
|
||||
let mut j = i + 1;
|
||||
while j < hi && self.refs[j] >> 1 < end {
|
||||
j += 1;
|
||||
}
|
||||
let wanted = match candidates {
|
||||
None => true,
|
||||
Some(c) => {
|
||||
cand += c[cand..].partition_point(|&g| (g as usize) < game);
|
||||
c.get(cand).is_some_and(|&g| g as usize == game)
|
||||
}
|
||||
};
|
||||
if wanted {
|
||||
self.collect_first(game, &self.refs[i..j], line.as_deref(), &mut collector);
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
Some(collector.finish(&query.position))
|
||||
}
|
||||
|
||||
/// Adds game `game` whose entries for the position are `refs`.
|
||||
fn collect(&self, game: usize, refs: &[u32], line: Option<&[u16]>, out: &mut Collector) {
|
||||
let meta = self.meta[game];
|
||||
|
|
@ -386,59 +338,6 @@ impl PositionTable {
|
|||
}
|
||||
}
|
||||
|
||||
fn collect_first(&self, game: usize, refs: &[u32], line: Option<&[u16]>, out: &mut Collector) {
|
||||
let meta = self.meta[game];
|
||||
let mut occurrences = refs.iter().filter_map(|&r| {
|
||||
let node = (r >> 1) as usize;
|
||||
(!self.nodes[node].in_variation()).then_some((node, r & 1 == 1))
|
||||
});
|
||||
let Some((raw_at, ended)) = occurrences.next() else {
|
||||
return;
|
||||
};
|
||||
let at = if ended {
|
||||
raw_at
|
||||
} else {
|
||||
self.nodes[raw_at].parent().unwrap_or(raw_at)
|
||||
};
|
||||
let next = if ended {
|
||||
None
|
||||
} else {
|
||||
Some(decode(self.nodes[raw_at].mv))
|
||||
};
|
||||
if self.after_teaching_null(at) {
|
||||
return;
|
||||
}
|
||||
let same_order = self.same_order(at, meta, line);
|
||||
let index = game as u32;
|
||||
out.add(
|
||||
Match {
|
||||
index,
|
||||
ply: u32::from(self.nodes[at].ply),
|
||||
same_order,
|
||||
in_variation: false,
|
||||
next,
|
||||
},
|
||||
next,
|
||||
meta.result,
|
||||
meta.white_elo,
|
||||
meta.black_elo,
|
||||
meta.year,
|
||||
);
|
||||
}
|
||||
|
||||
/// A position after a teaching null move is not part of the played opening line.
|
||||
fn after_teaching_null(&self, at: usize) -> bool {
|
||||
let mut current = Some(at);
|
||||
while let Some(node) = current {
|
||||
let n = self.nodes[node];
|
||||
if n.parent().is_some() && n.mv == NULL_MOVE {
|
||||
return true;
|
||||
}
|
||||
current = n.parent();
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The move of the first child of node `at` among the entries `refs` of its game
|
||||
/// (children come in text order, so the smallest node is the main continuation).
|
||||
fn first_child_move(&self, at: usize, refs: &[u32]) -> Option<u16> {
|
||||
|
|
@ -749,90 +648,6 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_played_line_counts_only_its_first_occurrence() {
|
||||
let db = db(PGN);
|
||||
let t = table(&db);
|
||||
let out = t
|
||||
.search_first(
|
||||
&db,
|
||||
None,
|
||||
&query(&["d4", "d5", "Nf3"]),
|
||||
&AtomicBool::new(false),
|
||||
)
|
||||
.unwrap();
|
||||
let found: Vec<(u32, u32)> = out.matches.iter().map(|m| (m.index, m.ply)).collect();
|
||||
assert_eq!(found, vec![(0, 3), (1, 3), (3, 3), (4, 0), (6, 3)]);
|
||||
assert_eq!(
|
||||
out.moves
|
||||
.iter()
|
||||
.map(|m| (m.san.as_str(), m.tally.games, m.main_line_games))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![("Nf6", 3, 3), ("e6", 1, 1)]
|
||||
);
|
||||
assert_eq!(out.ended.games, 1);
|
||||
assert_eq!(out.ended.draws, 1);
|
||||
let nf6 = &out.moves[0];
|
||||
assert_eq!((nf6.tally.white_wins, nf6.tally.black_wins), (2, 1));
|
||||
assert!(out.matches.iter().all(|m| !m.in_variation));
|
||||
assert_eq!(
|
||||
out.matches
|
||||
.iter()
|
||||
.map(|m| m.index)
|
||||
.filter(|&i| i == 2)
|
||||
.count(),
|
||||
0
|
||||
);
|
||||
assert_eq!(out.matches[0].next, Some(nf6.uci));
|
||||
assert_eq!(out.matches[2].next, None);
|
||||
let candidates = t
|
||||
.search_first(
|
||||
&db,
|
||||
Some(&[0, 2, 6]),
|
||||
&query(&["d4", "d5", "Nf3"]),
|
||||
&AtomicBool::new(false),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
candidates
|
||||
.matches
|
||||
.iter()
|
||||
.map(|m| m.index)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![0, 6]
|
||||
);
|
||||
let after_null: Chess = "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2"
|
||||
.parse::<shakmaty::fen::Fen>()
|
||||
.unwrap()
|
||||
.into_position(shakmaty::CastlingMode::Standard)
|
||||
.unwrap();
|
||||
let after_null = t
|
||||
.search_first(
|
||||
&db,
|
||||
None,
|
||||
&PositionQuery::new(after_null, None),
|
||||
&AtomicBool::new(false),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
after_null.matches.is_empty(),
|
||||
"a teaching null move is not a played continuation"
|
||||
);
|
||||
// A repeated position must not choose a later transposition branch.
|
||||
let repeat = crate::pgn_positions::tests::db(
|
||||
"[Event \"repeat\"]\n1. Nf3 d5 2. d4 Nf6 3. Ng1 Ng8 4. Nf3 e6 *\n",
|
||||
);
|
||||
let table = table(&repeat);
|
||||
let q = query(&["Nf3", "d5", "d4", "Nf6", "Ng1", "Ng8", "Nf3"]);
|
||||
let out = table
|
||||
.search_first(&repeat, None, &q, &AtomicBool::new(false))
|
||||
.unwrap();
|
||||
assert_eq!(out.matches[0].ply, 3);
|
||||
assert!(!out.matches[0].same_order);
|
||||
assert_eq!(out.moves[0].san, "Nf6");
|
||||
assert_eq!(out.moves.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_move_belongs_to_the_chosen_occurrence() {
|
||||
// The main line ends in the position; a variation reaches it and goes on.
|
||||
|
|
|
|||
|
|
@ -585,12 +585,6 @@ impl GameAnalysis {
|
|||
// ----- cache -----------------------------------------------------------------
|
||||
|
||||
/// The name of the cache file of this main line.
|
||||
/// The name of this main line's file in the cache: equal for equal main lines (the
|
||||
/// same positions), whatever the rest of the game.
|
||||
pub fn cache_key(&self) -> String {
|
||||
self.cache_name()
|
||||
}
|
||||
|
||||
fn cache_name(&self) -> String {
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for k in &self.keys {
|
||||
|
|
|
|||
|
|
@ -15,7 +15,6 @@ use shakmaty::Position;
|
|||
mod engine;
|
||||
mod online;
|
||||
mod play;
|
||||
mod prep;
|
||||
mod review;
|
||||
mod session;
|
||||
mod train;
|
||||
|
|
@ -31,10 +30,6 @@ pub use play::{
|
|||
RodentStyle, computer_game_tags, hopeless_turns, maia_range, move_pause_ms, rival_label,
|
||||
rival_name, rodent_book_pack, rodent_range, rodent_styles, rodent_version,
|
||||
};
|
||||
pub use prep::{
|
||||
PlayerSuggestion, PlayerSuggestions, PrepContinuation, PrepMatch, PrepPhase, PrepResult,
|
||||
PrepSearch, PrepState,
|
||||
};
|
||||
pub use review::{GameReview, MoveJudgement, ReviewMove, ReviewPoint, ReviewState, SideReview};
|
||||
pub use session::{Edited, GameSession, own_create, own_remove, own_save};
|
||||
pub use train::{TrainState, TrainStats, TrainVerdict, Trainer, trainer_set_file};
|
||||
|
|
@ -96,11 +91,9 @@ impl From<chess_import::ImportError> for ApiError {
|
|||
/// An open database.
|
||||
#[derive(uniffi::Object)]
|
||||
pub struct Database {
|
||||
db: Arc<chess_import::Database>,
|
||||
db: chess_import::Database,
|
||||
format: String,
|
||||
notes: Vec<String>,
|
||||
/// At most one opponent-preparation worker per open database.
|
||||
prep: std::sync::Mutex<Option<std::sync::Weak<prep::Shared>>>,
|
||||
}
|
||||
|
||||
/// One line of the game list.
|
||||
|
|
@ -189,10 +182,9 @@ fn never() -> AtomicBool {
|
|||
|
||||
fn wrap(opened: chess_import::Opened) -> Arc<Database> {
|
||||
Arc::new(Database {
|
||||
db: Arc::new(opened.db),
|
||||
db: opened.db,
|
||||
format: opened.format.label().to_owned(),
|
||||
notes: opened.notes,
|
||||
prep: std::sync::Mutex::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,812 +0,0 @@
|
|||
//! Simple opponent preparation: exact players, their games on one colour, and the
|
||||
//! continuations from the first main-line occurrence of a position. Searches run on
|
||||
//! one worker per database and never start an engine or change the source database.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use chess_core::StartPosition;
|
||||
use chess_import::chessbase::base::{Filter, NameFilter, Side, SortKey};
|
||||
use chess_import::position::{GameResult, PositionOutcome, PositionQuery};
|
||||
use shakmaty::uci::UciMove;
|
||||
use shakmaty::{Chess, Color, Position, san::SanPlus};
|
||||
|
||||
use crate::{ApiError, Database, GameRow};
|
||||
|
||||
/// Keeps a search response bounded even when the position occurs in a whole book.
|
||||
const MATCH_LIMIT: usize = 100;
|
||||
const SUGGESTION_LIMIT: u32 = 200;
|
||||
|
||||
/// One exact player name from the database catalogue.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
|
||||
pub struct PlayerSuggestion {
|
||||
/// Stable within this open database; used by [`Database::prepare_position`].
|
||||
pub id: u32,
|
||||
pub name: String,
|
||||
/// Distinct games. A game with this name on both sides counts once here.
|
||||
pub games: u32,
|
||||
pub white_games: u32,
|
||||
pub black_games: u32,
|
||||
}
|
||||
|
||||
/// A page of [`PlayerSuggestion`] and the total number of matching names.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
|
||||
pub struct PlayerSuggestions {
|
||||
pub players: Vec<PlayerSuggestion>,
|
||||
pub total: u32,
|
||||
}
|
||||
|
||||
/// A move played next, with the selected player's results (not the mover's).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
|
||||
pub struct PrepContinuation {
|
||||
pub uci: String,
|
||||
pub san: String,
|
||||
pub count: u32,
|
||||
pub wins: u32,
|
||||
pub draws: u32,
|
||||
pub losses: u32,
|
||||
/// Games with `Result "*"` (or another unknown result); not a loss.
|
||||
pub unknown: u32,
|
||||
}
|
||||
|
||||
/// One matching game. `ply` opens its first main-line occurrence of the position.
|
||||
#[derive(Debug, Clone, PartialEq, uniffi::Record)]
|
||||
pub struct PrepMatch {
|
||||
pub index: u32,
|
||||
pub ply: u32,
|
||||
pub row: GameRow,
|
||||
}
|
||||
|
||||
/// Continuations and results at one position.
|
||||
#[derive(Debug, Clone, PartialEq, uniffi::Record)]
|
||||
pub struct PrepResult {
|
||||
/// Matching games, each counted once at its first main-line occurrence.
|
||||
pub games: u32,
|
||||
pub wins: u32,
|
||||
pub draws: u32,
|
||||
pub losses: u32,
|
||||
pub unknown: u32,
|
||||
/// Whether the selected player (rather than their opponents) moves here.
|
||||
pub player_to_move: bool,
|
||||
/// By count descending, then SAN ascending.
|
||||
pub continuations: Vec<PrepContinuation>,
|
||||
pub ended: u32,
|
||||
/// A teaching null move or a continuation that is not a normal legal move.
|
||||
pub no_normal_continuation: u32,
|
||||
/// At most 100 rows in record order; `matches_total` is the unpaginated count.
|
||||
pub matches: Vec<PrepMatch>,
|
||||
pub matches_total: u32,
|
||||
}
|
||||
|
||||
/// The phase of a [`PrepSearch`]. Terminal phases are `Ready`, `Cancelled`,
|
||||
/// `NoMemory` and `Failed`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
|
||||
pub enum PrepPhase {
|
||||
Games,
|
||||
Index,
|
||||
Search,
|
||||
Ready,
|
||||
Cancelled,
|
||||
NoMemory,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// A snapshot of a preparation worker.
|
||||
#[derive(Debug, Clone, PartialEq, uniffi::Record)]
|
||||
pub struct PrepState {
|
||||
pub phase: PrepPhase,
|
||||
/// Progress inside the current phase (`total == 0` means not applicable).
|
||||
pub done: u32,
|
||||
pub total: u32,
|
||||
pub running: bool,
|
||||
pub result: Option<PrepResult>,
|
||||
/// Empty except for `Failed` and `NoMemory`.
|
||||
pub failure: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct Score {
|
||||
count: u32,
|
||||
wins: u32,
|
||||
draws: u32,
|
||||
losses: u32,
|
||||
unknown: u32,
|
||||
}
|
||||
|
||||
impl Score {
|
||||
fn add(&mut self, result: &str, selected_white: bool) {
|
||||
self.count = self.count.saturating_add(1);
|
||||
match GameResult::from_tag(result) {
|
||||
GameResult::WhiteWins => {
|
||||
if selected_white {
|
||||
self.wins = self.wins.saturating_add(1);
|
||||
} else {
|
||||
self.losses = self.losses.saturating_add(1);
|
||||
}
|
||||
}
|
||||
GameResult::BlackWins => {
|
||||
if selected_white {
|
||||
self.losses = self.losses.saturating_add(1);
|
||||
} else {
|
||||
self.wins = self.wins.saturating_add(1);
|
||||
}
|
||||
}
|
||||
GameResult::Draw => self.draws = self.draws.saturating_add(1),
|
||||
GameResult::Unknown => self.unknown = self.unknown.saturating_add(1),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Snapshot {
|
||||
phase: PrepPhase,
|
||||
total: u32,
|
||||
result: Option<PrepResult>,
|
||||
failure: String,
|
||||
}
|
||||
|
||||
pub(crate) struct Shared {
|
||||
cancel: AtomicBool,
|
||||
progress: AtomicUsize,
|
||||
snapshot: Mutex<Snapshot>,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
fn new(total: usize) -> Self {
|
||||
Self {
|
||||
cancel: AtomicBool::new(false),
|
||||
progress: AtomicUsize::new(0),
|
||||
snapshot: Mutex::new(Snapshot {
|
||||
phase: PrepPhase::Games,
|
||||
total: as_u32(total),
|
||||
result: None,
|
||||
failure: String::new(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn phase(&self, phase: PrepPhase, total: usize) {
|
||||
if self.cancel.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
self.progress.store(0, Ordering::Relaxed);
|
||||
let mut snapshot = lock(&self.snapshot);
|
||||
snapshot.phase = phase;
|
||||
snapshot.total = as_u32(total);
|
||||
}
|
||||
|
||||
fn ready(&self, result: PrepResult) {
|
||||
if self.cancel.load(Ordering::Relaxed) {
|
||||
self.cancelled();
|
||||
return;
|
||||
}
|
||||
let mut snapshot = lock(&self.snapshot);
|
||||
self.progress
|
||||
.store(snapshot.total as usize, Ordering::Relaxed);
|
||||
snapshot.phase = PrepPhase::Ready;
|
||||
snapshot.result = Some(result);
|
||||
}
|
||||
|
||||
fn cancelled(&self) {
|
||||
let mut snapshot = lock(&self.snapshot);
|
||||
if matches!(
|
||||
snapshot.phase,
|
||||
PrepPhase::Games | PrepPhase::Index | PrepPhase::Search
|
||||
) {
|
||||
snapshot.phase = PrepPhase::Cancelled;
|
||||
snapshot.result = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn failed(&self, phase: PrepPhase, failure: String) {
|
||||
if self.cancel.load(Ordering::Relaxed) {
|
||||
self.cancelled();
|
||||
return;
|
||||
}
|
||||
let mut snapshot = lock(&self.snapshot);
|
||||
snapshot.phase = phase;
|
||||
snapshot.failure = failure;
|
||||
snapshot.result = None;
|
||||
}
|
||||
|
||||
fn cancel(&self) {
|
||||
self.cancel.store(true, Ordering::Relaxed);
|
||||
self.cancelled();
|
||||
}
|
||||
|
||||
fn state(&self) -> PrepState {
|
||||
let snapshot = lock(&self.snapshot).clone();
|
||||
let running = matches!(
|
||||
snapshot.phase,
|
||||
PrepPhase::Games | PrepPhase::Index | PrepPhase::Search
|
||||
);
|
||||
PrepState {
|
||||
phase: snapshot.phase,
|
||||
done: as_u32(
|
||||
self.progress
|
||||
.load(Ordering::Relaxed)
|
||||
.min(snapshot.total as usize),
|
||||
),
|
||||
total: snapshot.total,
|
||||
running,
|
||||
result: snapshot.result,
|
||||
failure: snapshot.failure,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One running or finished position search. Dropping it requests cancellation.
|
||||
#[derive(uniffi::Object)]
|
||||
pub struct PrepSearch {
|
||||
shared: Arc<Shared>,
|
||||
}
|
||||
|
||||
#[uniffi::export]
|
||||
impl PrepSearch {
|
||||
pub fn state(&self) -> PrepState {
|
||||
self.shared.state()
|
||||
}
|
||||
|
||||
/// Stops soon; an old worker cannot publish its result afterwards.
|
||||
pub fn cancel(&self) {
|
||||
self.shared.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PrepSearch {
|
||||
fn drop(&mut self) {
|
||||
self.shared.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Database {
|
||||
fn drop(&mut self) {
|
||||
if let Some(shared) = lock(&self.prep).as_ref().and_then(|old| old.upgrade()) {
|
||||
shared.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||
mutex.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn as_u32(n: usize) -> u32 {
|
||||
u32::try_from(n).unwrap_or(u32::MAX)
|
||||
}
|
||||
|
||||
#[uniffi::export]
|
||||
impl Database {
|
||||
/// Exact-name suggestions, `count` at most 200. An empty query lists all named
|
||||
/// players alphabetically; a non-empty one keeps the catalogue's prefix/games order.
|
||||
pub fn suggest_players(&self, query: String, start: u32, count: u32) -> PlayerSuggestions {
|
||||
let limit = count.min(SUGGESTION_LIMIT) as usize;
|
||||
let (list, total) = match self.db.as_ref() {
|
||||
chess_import::Database::Pgn(db) => {
|
||||
db.catalog()
|
||||
.suggest_players_page(&query, start as usize, limit)
|
||||
}
|
||||
chess_import::Database::ChessBase(db) => {
|
||||
db.suggest_players_page(&query, start as usize, limit)
|
||||
}
|
||||
};
|
||||
let players = list
|
||||
.into_iter()
|
||||
.map(|suggestion| {
|
||||
let (games, white_games, black_games) = match self.db.as_ref() {
|
||||
chess_import::Database::Pgn(db) => db.catalog().player_counts(suggestion.id),
|
||||
chess_import::Database::ChessBase(db) => db.player_counts(suggestion.id),
|
||||
};
|
||||
PlayerSuggestion {
|
||||
id: suggestion.id,
|
||||
name: suggestion.name,
|
||||
games,
|
||||
white_games,
|
||||
black_games,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
PlayerSuggestions {
|
||||
players,
|
||||
total: as_u32(total),
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts preparation for an exact player and colour at `query_fen` (empty means
|
||||
/// the usual initial position). Only the first main-line occurrence in each game
|
||||
/// counts; transpositions count and variations in the database do not. The thread
|
||||
/// is bounded to one active request per database: a new request cancels the old one.
|
||||
pub fn prepare_position(
|
||||
&self,
|
||||
player_id: u32,
|
||||
white: bool,
|
||||
query_fen: String,
|
||||
) -> Result<Arc<PrepSearch>, ApiError> {
|
||||
let position = parse_position(&query_fen)?;
|
||||
let shared = Arc::new(Shared::new(self.db.len()));
|
||||
let previous = lock(&self.prep).replace(Arc::downgrade(&shared));
|
||||
if let Some(previous) = previous.and_then(|old| old.upgrade()) {
|
||||
previous.cancel();
|
||||
}
|
||||
|
||||
let worker = shared.clone();
|
||||
let db = self.db.clone();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("opponent-prep".into())
|
||||
.spawn(move || run(db, player_id, white, position, worker));
|
||||
if let Err(error) = spawned {
|
||||
shared.failed(PrepPhase::Failed, error.to_string());
|
||||
}
|
||||
Ok(Arc::new(PrepSearch { shared }))
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_position(fen: &str) -> Result<Chess, ApiError> {
|
||||
if fen.trim().is_empty() {
|
||||
return Ok(Chess::default());
|
||||
}
|
||||
StartPosition::from_fen(fen)
|
||||
.map(|start| start.position().clone())
|
||||
.map_err(|error| ApiError::Edit {
|
||||
detail: error.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn player_games(
|
||||
db: &chess_import::Database,
|
||||
player_id: u32,
|
||||
white: bool,
|
||||
progress: &AtomicUsize,
|
||||
cancel: &AtomicBool,
|
||||
) -> Option<Vec<u32>> {
|
||||
let side = if white { Side::White } else { Side::Black };
|
||||
match db {
|
||||
chess_import::Database::Pgn(db) => {
|
||||
db.catalog().player_games(player_id, side, progress, cancel)
|
||||
}
|
||||
chess_import::Database::ChessBase(db) => db.query(
|
||||
&Filter {
|
||||
player: NameFilter {
|
||||
text: String::new(),
|
||||
exact: Some(player_id),
|
||||
},
|
||||
side,
|
||||
games_only: true,
|
||||
..Filter::default()
|
||||
},
|
||||
SortKey::Number,
|
||||
true,
|
||||
progress,
|
||||
cancel,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn run(
|
||||
db: Arc<chess_import::Database>,
|
||||
player_id: u32,
|
||||
white: bool,
|
||||
position: Chess,
|
||||
shared: Arc<Shared>,
|
||||
) {
|
||||
if shared.cancel.load(Ordering::Relaxed) {
|
||||
shared.cancelled();
|
||||
return;
|
||||
}
|
||||
// This may build the PGN catalogue; it deliberately runs here, not on the caller's
|
||||
// thread. An invalid id is a failed request, not a valid empty repertoire.
|
||||
if db.player_name(player_id).trim().is_empty() {
|
||||
shared.failed(PrepPhase::Failed, format!("unknown player {player_id}"));
|
||||
return;
|
||||
}
|
||||
let Some(games) = player_games(&db, player_id, white, &shared.progress, &shared.cancel) else {
|
||||
shared.cancelled();
|
||||
return;
|
||||
};
|
||||
if games.is_empty() {
|
||||
shared.phase(PrepPhase::Search, 0);
|
||||
shared.ready(result(&db, &position, white, PositionOutcome::default()));
|
||||
return;
|
||||
}
|
||||
if let Some(needed) = db.positions_blocked() {
|
||||
shared.failed(
|
||||
PrepPhase::NoMemory,
|
||||
format!("not enough memory for the position index ({needed} bytes needed)"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let preparing = !db.positions_ready();
|
||||
shared.phase(
|
||||
if preparing {
|
||||
PrepPhase::Index
|
||||
} else {
|
||||
PrepPhase::Search
|
||||
},
|
||||
if preparing { db.len() } else { games.len() },
|
||||
);
|
||||
let query = PositionQuery::new(position.clone(), None);
|
||||
let outcome = db.search_position_first(Some(&games), &query, &shared.progress, &shared.cancel);
|
||||
match outcome {
|
||||
Some(outcome) => shared.ready(result(&db, &position, white, outcome)),
|
||||
None if shared.cancel.load(Ordering::Relaxed) => shared.cancelled(),
|
||||
None => shared.failed(
|
||||
PrepPhase::Failed,
|
||||
"position search ended without a result".into(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn result(
|
||||
db: &chess_import::Database,
|
||||
position: &Chess,
|
||||
selected_white: bool,
|
||||
outcome: PositionOutcome,
|
||||
) -> PrepResult {
|
||||
let mut total = Score::default();
|
||||
let mut continuations: HashMap<UciMove, Score> = HashMap::new();
|
||||
let mut ended = 0u32;
|
||||
let mut no_normal = 0u32;
|
||||
let mut matches = Vec::with_capacity(outcome.matches.len().min(MATCH_LIMIT));
|
||||
|
||||
for (place, found) in outcome.matches.iter().enumerate() {
|
||||
let row = game_row(db, found.index);
|
||||
total.add(&row.result, selected_white);
|
||||
match found.next {
|
||||
None => ended = ended.saturating_add(1),
|
||||
Some(UciMove::Null) => no_normal = no_normal.saturating_add(1),
|
||||
Some(uci) => match uci.to_move(position) {
|
||||
Ok(_) => continuations
|
||||
.entry(uci)
|
||||
.or_default()
|
||||
.add(&row.result, selected_white),
|
||||
Err(_) => no_normal = no_normal.saturating_add(1),
|
||||
},
|
||||
}
|
||||
if place < MATCH_LIMIT {
|
||||
matches.push(PrepMatch {
|
||||
index: found.index,
|
||||
ply: found.ply,
|
||||
row,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let mut continuations: Vec<PrepContinuation> = continuations
|
||||
.into_iter()
|
||||
.filter_map(|(uci, score)| {
|
||||
let mv = uci.to_move(position).ok()?;
|
||||
let san = SanPlus::from_move(position.clone(), mv).to_string();
|
||||
Some(PrepContinuation {
|
||||
uci: uci.to_string(),
|
||||
san,
|
||||
count: score.count,
|
||||
wins: score.wins,
|
||||
draws: score.draws,
|
||||
losses: score.losses,
|
||||
unknown: score.unknown,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
continuations.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.san.cmp(&b.san)));
|
||||
let continuation_games = continuations.iter().fold(0u32, |sum, continuation| {
|
||||
sum.saturating_add(continuation.count)
|
||||
});
|
||||
debug_assert_eq!(
|
||||
continuation_games
|
||||
.saturating_add(ended)
|
||||
.saturating_add(no_normal),
|
||||
total.count
|
||||
);
|
||||
PrepResult {
|
||||
games: total.count,
|
||||
wins: total.wins,
|
||||
draws: total.draws,
|
||||
losses: total.losses,
|
||||
unknown: total.unknown,
|
||||
player_to_move: position.turn()
|
||||
== if selected_white {
|
||||
Color::White
|
||||
} else {
|
||||
Color::Black
|
||||
},
|
||||
continuations,
|
||||
ended,
|
||||
no_normal_continuation: no_normal,
|
||||
matches_total: total.count,
|
||||
matches,
|
||||
}
|
||||
}
|
||||
|
||||
fn game_row(db: &chess_import::Database, index: u32) -> GameRow {
|
||||
let row = db.row(index as usize);
|
||||
let elo = |value: u16| {
|
||||
if value == 0 {
|
||||
String::new()
|
||||
} else {
|
||||
value.to_string()
|
||||
}
|
||||
};
|
||||
GameRow {
|
||||
index,
|
||||
white: row.white,
|
||||
black: row.black,
|
||||
result: row.result.to_owned(),
|
||||
date: row.date,
|
||||
event: row.event,
|
||||
eco: row.eco.unwrap_or_default(),
|
||||
white_elo: elo(row.white_elo),
|
||||
black_elo: elo(row.black_elo),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use shakmaty::EnPassantMode;
|
||||
use shakmaty::fen::Fen;
|
||||
use shakmaty::san::San;
|
||||
|
||||
use crate::open_bytes;
|
||||
|
||||
fn database(pgn: &str) -> Arc<Database> {
|
||||
open_bytes("prep.pgn".into(), pgn.as_bytes().to_vec()).expect("fixture opens")
|
||||
}
|
||||
|
||||
fn fen(line: &[&str]) -> String {
|
||||
let mut position = Chess::default();
|
||||
for san in line {
|
||||
let mv = san
|
||||
.parse::<San>()
|
||||
.expect("fixture SAN")
|
||||
.to_move(&position)
|
||||
.expect("legal fixture move");
|
||||
position.play_unchecked(mv);
|
||||
}
|
||||
Fen::from_position(&position, EnPassantMode::Legal).to_string()
|
||||
}
|
||||
|
||||
fn player(db: &Database, name: &str) -> PlayerSuggestion {
|
||||
db.suggest_players(name.into(), 0, SUGGESTION_LIMIT)
|
||||
.players
|
||||
.into_iter()
|
||||
.find(|player| player.name == name)
|
||||
.expect("exact fixture player")
|
||||
}
|
||||
|
||||
fn search(db: &Database, player_id: u32, white: bool, fen: String) -> PrepState {
|
||||
let search = db
|
||||
.prepare_position(player_id, white, fen)
|
||||
.expect("search starts");
|
||||
for _ in 0..1000 {
|
||||
let state = search.state();
|
||||
if !state.running {
|
||||
return state;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
panic!("preparation did not finish")
|
||||
}
|
||||
|
||||
fn ready(state: PrepState) -> PrepResult {
|
||||
assert_eq!(state.phase, PrepPhase::Ready, "{}", state.failure);
|
||||
assert_eq!(state.done, state.total);
|
||||
state.result.expect("ready result")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggestions_are_paged_normalized_and_count_each_colour() {
|
||||
let db = database(concat!(
|
||||
"[White \"Vafin Radel\"][Black \"Other A\"][Result \"1-0\"]\n\n1. e4 c5 1-0\n\n",
|
||||
"[White \"Other B\"][Black \"Vafin Radel\"][Result \"0-1\"]\n\n1. e4 c5 0-1\n\n",
|
||||
"[White \"Vafin Radel\"][Black \"Vafin Radel\"][Result \"0-1\"]\n\n1. e4 e5 0-1\n\n",
|
||||
"[White \"Vafina Rayana\"][Black \"Other C\"][Result \"*\"]\n\n1. e4 c5 *\n",
|
||||
));
|
||||
let first = db.suggest_players("vafin".into(), 0, 1);
|
||||
assert_eq!(first.total, 2);
|
||||
assert_eq!(first.players.len(), 1);
|
||||
let vafin = &first.players[0];
|
||||
assert_eq!(vafin.name, "Vafin Radel");
|
||||
assert_eq!(
|
||||
(vafin.games, vafin.white_games, vafin.black_games),
|
||||
(3, 2, 2)
|
||||
);
|
||||
let second = db.suggest_players("vafin".into(), 1, 1);
|
||||
assert_eq!(second.players[0].name, "Vafina Rayana");
|
||||
assert!(db.suggest_players("vafin".into(), 2, 1).players.is_empty());
|
||||
let all = db.suggest_players(String::new(), 0, 200);
|
||||
assert_eq!(all.total, 5);
|
||||
assert!(
|
||||
all.players
|
||||
.windows(2)
|
||||
.all(|pair| pair[0].name <= pair[1].name)
|
||||
);
|
||||
|
||||
let after_e4 = fen(&["e4"]);
|
||||
let white = ready(search(&db, vafin.id, true, after_e4.clone()));
|
||||
assert_eq!((white.games, white.wins, white.losses), (2, 1, 1));
|
||||
assert_eq!(
|
||||
white.matches.iter().map(|m| m.index).collect::<Vec<_>>(),
|
||||
[0, 2]
|
||||
);
|
||||
let black = ready(search(&db, vafin.id, false, after_e4));
|
||||
assert_eq!((black.games, black.wins, black.losses), (2, 2, 0));
|
||||
assert_eq!(
|
||||
black.matches.iter().map(|m| m.index).collect::<Vec<_>>(),
|
||||
[1, 2]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_main_line_occurrence_wins_over_repetition_and_rav() {
|
||||
let db = database(concat!(
|
||||
"[White \"Repeat\"][Black \"X\"][Result \"1-0\"]\n\n",
|
||||
"1. Nf3 (1. e4 e5) Nf6 2. Ng1 Ng8 3. d4 d5 1-0\n",
|
||||
));
|
||||
let id = player(&db, "Repeat").id;
|
||||
let result = ready(search(&db, id, true, fen(&[])));
|
||||
assert_eq!(result.games, 1);
|
||||
assert_eq!(result.matches[0].ply, 0);
|
||||
assert_eq!(result.continuations.len(), 1);
|
||||
assert_eq!(result.continuations[0].san, "Nf3");
|
||||
assert_eq!(result.continuations[0].count, 1);
|
||||
assert_eq!(result.ended, 0);
|
||||
|
||||
let db = database(concat!(
|
||||
"[White \"Main\"][Black \"X\"][Result \"1-0\"]\n\n",
|
||||
"1. e4 c5 (1... e5) 2. Nf3 1-0\n\n",
|
||||
"[White \"Main\"][Black \"X\"][Result \"0-1\"]\n\n",
|
||||
"1. e4 e5 (1... c5 2. Nf3) 2. Nf3 0-1\n",
|
||||
));
|
||||
let id = player(&db, "Main").id;
|
||||
let result = ready(search(&db, id, true, fen(&["e4", "c5"])));
|
||||
assert_eq!(
|
||||
result.games, 1,
|
||||
"a RAV-only occurrence is not a played game"
|
||||
);
|
||||
assert_eq!(result.matches[0].index, 0);
|
||||
assert_eq!(result.matches[0].ply, 2);
|
||||
assert_eq!(result.continuations.len(), 1);
|
||||
assert_eq!(result.continuations[0].san, "Nf3");
|
||||
assert_eq!((result.wins, result.losses), (1, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transpositions_have_the_same_games_and_continuations() {
|
||||
let db = database(concat!(
|
||||
"[White \"T\"][Black \"X\"][Result \"1-0\"]\n\n1. Nf3 d5 2. d4 e6 1-0\n\n",
|
||||
"[White \"T\"][Black \"X\"][Result \"0-1\"]\n\n1. d4 d5 2. Nf3 c6 0-1\n",
|
||||
));
|
||||
let id = player(&db, "T").id;
|
||||
let a = ready(search(&db, id, true, fen(&["Nf3", "d5", "d4"])));
|
||||
let b = ready(search(&db, id, true, fen(&["d4", "d5", "Nf3"])));
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(a.games, 2);
|
||||
assert_eq!(a.matches.iter().map(|m| m.ply).collect::<Vec<_>>(), [3, 3]);
|
||||
assert_eq!(
|
||||
a.continuations
|
||||
.iter()
|
||||
.map(|m| m.san.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["c6", "e6"]
|
||||
);
|
||||
assert_eq!((a.wins, a.losses), (1, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn continuation_results_belong_to_the_selected_player() {
|
||||
let db = database(concat!(
|
||||
"[White \"W1\"][Black \"B\"][Result \"0-1\"]\n\n1. e4 c5 0-1\n\n",
|
||||
"[White \"W2\"][Black \"B\"][Result \"0-1\"]\n\n1. e4 c5 0-1\n\n",
|
||||
"[White \"W3\"][Black \"B\"][Result \"1-0\"]\n\n1. e4 c5 1-0\n\n",
|
||||
"[White \"W4\"][Black \"B\"][Result \"*\"]\n\n1. e4 c5 *\n",
|
||||
));
|
||||
let id = player(&db, "B").id;
|
||||
let result = ready(search(&db, id, false, fen(&["e4"])));
|
||||
assert_eq!(
|
||||
(
|
||||
result.games,
|
||||
result.wins,
|
||||
result.draws,
|
||||
result.losses,
|
||||
result.unknown
|
||||
),
|
||||
(4, 2, 0, 1, 1)
|
||||
);
|
||||
let c5 = &result.continuations[0];
|
||||
assert_eq!(c5.san, "c5");
|
||||
assert_eq!(
|
||||
(c5.count, c5.wins, c5.draws, c5.losses, c5.unknown),
|
||||
(4, 2, 0, 1, 1)
|
||||
);
|
||||
assert!(
|
||||
result.player_to_move,
|
||||
"Black moves after 1.e4, so the selected player moves here"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fen_game_starts_at_ply_zero_with_black_to_move() {
|
||||
let query = "8/3k4/8/3K4/3P4/8/8/8 b - - 0 0";
|
||||
let pgn = format!(
|
||||
"[White \"X\"][Black \"FEN player\"][Result \"*\"][SetUp \"1\"][FEN \"{query}\"]\n\n1... Kc7 *\n"
|
||||
);
|
||||
let db = database(&pgn);
|
||||
let id = player(&db, "FEN player").id;
|
||||
let result = ready(search(&db, id, false, query.into()));
|
||||
assert_eq!(result.games, 1);
|
||||
assert_eq!(result.matches[0].ply, 0);
|
||||
assert_eq!(result.continuations[0].san, "Kc7");
|
||||
assert!(result.player_to_move);
|
||||
assert_eq!(
|
||||
(result.wins, result.draws, result.losses, result.unknown),
|
||||
(0, 0, 0, 1)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ended_and_teaching_null_moves_balance_the_game_count() {
|
||||
let db = database(concat!(
|
||||
"[White \"N\"][Black \"X\"][Result \"*\"]\n\n1. e4 *\n\n",
|
||||
"[White \"N\"][Black \"X\"][Result \"*\"]\n\n1. e4 -- *\n",
|
||||
));
|
||||
let id = player(&db, "N").id;
|
||||
let result = ready(search(&db, id, true, fen(&["e4"])));
|
||||
assert_eq!(result.games, 2);
|
||||
assert!(result.continuations.is_empty());
|
||||
assert_eq!(result.ended, 1);
|
||||
assert_eq!(result.no_normal_continuation, 1);
|
||||
assert_eq!(result.unknown, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_are_bounded_and_a_new_request_cancels_the_old_one() {
|
||||
let pgn = std::iter::repeat_n(
|
||||
"[White \"Many\"][Black \"X\"][Result \"*\"]\n\n1. e4 *\n\n",
|
||||
105,
|
||||
)
|
||||
.collect::<String>();
|
||||
let db = database(&pgn);
|
||||
let id = player(&db, "Many").id;
|
||||
let first = db
|
||||
.prepare_position(id, true, fen(&[]))
|
||||
.expect("first starts");
|
||||
let second = db
|
||||
.prepare_position(id, true, fen(&[]))
|
||||
.expect("second starts");
|
||||
assert!(first.shared.cancel.load(Ordering::Relaxed));
|
||||
let mut state = second.state();
|
||||
for _ in 0..1000 {
|
||||
if !state.running {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
state = second.state();
|
||||
}
|
||||
let result = ready(state);
|
||||
assert_eq!(result.games, 105);
|
||||
assert_eq!(result.matches_total, 105);
|
||||
assert_eq!(result.matches.len(), MATCH_LIMIT);
|
||||
assert_eq!(result.unknown, 105);
|
||||
|
||||
let cancelled = Arc::new(Shared::new(db.db.len()));
|
||||
cancelled.cancel();
|
||||
run(db.db.clone(), id, true, Chess::default(), cancelled.clone());
|
||||
assert_eq!(cancelled.state().phase, PrepPhase::Cancelled);
|
||||
assert!(cancelled.state().result.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_fen_is_an_input_error_not_a_worker_panic() {
|
||||
let db = database("[White \"P\"][Black \"X\"] *\n");
|
||||
let id = player(&db, "P").id;
|
||||
assert!(matches!(
|
||||
db.prepare_position(id, true, "not a fen".into()),
|
||||
Err(ApiError::Edit { .. })
|
||||
));
|
||||
let unknown = search(&db, u32::MAX, true, fen(&[]));
|
||||
assert_eq!(unknown.phase, PrepPhase::Failed);
|
||||
assert!(unknown.failure.contains("unknown player"));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,450 +0,0 @@
|
|||
//! Daily sessions (due + N new), mistakes coming back in the same session, one-pass
|
||||
//! review and sessions limited to a branch.
|
||||
|
||||
use super::*;
|
||||
|
||||
const NOW: i64 = 1_800_000_000;
|
||||
const PGN: &str = "1. e4 e5 2. Nf3 Nc6 3. Bb5 (3. Bc4 Bc5) a6 4. Ba4 *";
|
||||
|
||||
fn library(pgn: &str) -> (Library, RepertoireId) {
|
||||
let mut library = Library::default();
|
||||
let id = library
|
||||
.create("Test", &chess_core::parse_str(pgn).game)
|
||||
.unwrap();
|
||||
(library, id)
|
||||
}
|
||||
|
||||
fn key_for(library: &Library, scope: &StatsScope, expected_uci: &str) -> LearningItemKey {
|
||||
active_learning_memberships(library, scope)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.find(|membership| membership.key.expected_uci == expected_uci)
|
||||
.unwrap()
|
||||
.key
|
||||
}
|
||||
|
||||
fn queue_moves(session: &LearningSessionSnapshot) -> Vec<&str> {
|
||||
session
|
||||
.queue
|
||||
.iter()
|
||||
.skip(session.current_index)
|
||||
.filter(|target| !session.completed_keys.contains(&target.key))
|
||||
.map(|target| target.key.expected_uci.as_str())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Plays the automatic context up to the question, applying every event.
|
||||
fn to_question(
|
||||
session: &mut LearningSessionSnapshot,
|
||||
library: &Library,
|
||||
learning: &mut LearningData,
|
||||
) {
|
||||
let mut step = 0;
|
||||
while session
|
||||
.presentation_with_learning(library, learning)
|
||||
.unwrap()
|
||||
.phase
|
||||
== LearningSessionPhase::AdvancingContext
|
||||
{
|
||||
step += 1;
|
||||
let attempt = session
|
||||
.advance_context_with_learning(
|
||||
library,
|
||||
learning,
|
||||
format!("ctx-{step}-{}", session.revision),
|
||||
NOW,
|
||||
)
|
||||
.unwrap();
|
||||
session.revision += 1;
|
||||
learning
|
||||
.apply_attempt(attempt, &SrsSettings::default())
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn answer(
|
||||
session: &mut LearningSessionSnapshot,
|
||||
library: &Library,
|
||||
learning: &mut LearningData,
|
||||
uci: &str,
|
||||
id: &str,
|
||||
) -> TrainingAttempt {
|
||||
let attempt = session
|
||||
.play_uci_with_learning(library, learning, uci, id, NOW, Some(1000))
|
||||
.unwrap();
|
||||
learning
|
||||
.apply_attempt(attempt.clone(), &SrsSettings::default())
|
||||
.unwrap();
|
||||
attempt
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daily_queue_takes_every_due_move_and_at_most_n_new_in_pgn_order() {
|
||||
let (library, id) = library(PGN);
|
||||
let scope = StatsScope::for_repertoire(id, LearningSide::White, NOW);
|
||||
let mut learning = LearningData::default();
|
||||
// Due deep in the line, known and not due early in it.
|
||||
for (uci, next) in [("f1b5", NOW - 10), ("e2e4", NOW + 3600)] {
|
||||
let item = learning.ensure_item(key_for(&library, &scope, uci));
|
||||
item.introduced = true;
|
||||
item.next_review_at = Some(next);
|
||||
}
|
||||
let session = LearningSessionSnapshot::new_daily(
|
||||
"daily",
|
||||
&library,
|
||||
&learning,
|
||||
scope.clone(),
|
||||
SrsSettings::default(),
|
||||
2,
|
||||
)
|
||||
.unwrap();
|
||||
// Own moves in PGN order: e4 Nf3 Bb5 Ba4 Bc4. Due: Bb5. New: Nf3, Ba4 (2 of 3).
|
||||
assert_eq!(queue_moves(&session), ["g1f3", "f1b5", "b5a4"]);
|
||||
assert!(session.return_mistakes);
|
||||
assert_eq!(session.session.mode, QueueMode::SpacedRepetition);
|
||||
let all = LearningSessionSnapshot::new_daily(
|
||||
"daily-all",
|
||||
&library,
|
||||
&learning,
|
||||
scope.clone(),
|
||||
SrsSettings::default(),
|
||||
10,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(queue_moves(&all), ["g1f3", "f1b5", "b5a4", "f1c4"]);
|
||||
let none = LearningSessionSnapshot::new_daily(
|
||||
"daily-none",
|
||||
&library,
|
||||
&learning,
|
||||
scope,
|
||||
SrsSettings::default(),
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(queue_moves(&none), ["f1b5"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mistake_comes_back_in_the_same_session_and_a_shown_new_move_does_not() {
|
||||
let (library, id) = library("1. e4 e5 2. Nf3 Nc6 *");
|
||||
let scope = StatsScope::for_repertoire(id, LearningSide::White, NOW);
|
||||
let mut learning = LearningData::default();
|
||||
let e4 = key_for(&library, &scope, "e2e4");
|
||||
let item = learning.ensure_item(e4.clone());
|
||||
item.introduced = true;
|
||||
item.next_review_at = Some(NOW);
|
||||
let mut session = LearningSessionSnapshot::new_daily(
|
||||
"return",
|
||||
&library,
|
||||
&learning,
|
||||
scope,
|
||||
SrsSettings::default(),
|
||||
10,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(queue_moves(&session), ["e2e4", "g1f3"]);
|
||||
assert_eq!(session.remaining(), 2);
|
||||
assert!(!session.current_is_new(&learning));
|
||||
|
||||
let wrong = answer(&mut session, &library, &mut learning, "d2d4", "wrong");
|
||||
assert_eq!(wrong.event_type, TrainingEventType::IncorrectIndependent);
|
||||
assert_eq!(
|
||||
session.phase,
|
||||
LearningSessionPhase::AwaitingReplayAfterError
|
||||
);
|
||||
assert_eq!(session.remaining(), 2);
|
||||
let replay = answer(&mut session, &library, &mut learning, "e2e4", "replay");
|
||||
assert_eq!(replay.event_type, TrainingEventType::ReplayAfterError);
|
||||
// e4 is not done: it waits behind Nf3.
|
||||
assert_eq!(queue_moves(&session), ["g1f3", "e2e4"]);
|
||||
assert_eq!(session.remaining(), 2);
|
||||
assert!(!session.completed_keys.contains(&e4));
|
||||
session.validate(&library).unwrap();
|
||||
|
||||
to_question(&mut session, &library, &mut learning);
|
||||
assert!(session.current_is_new(&learning));
|
||||
let shown = session.preview_new("show-nf3", NOW).unwrap().unwrap();
|
||||
assert_eq!(shown.event_type, TrainingEventType::Previewed);
|
||||
assert!(session.showing_new);
|
||||
learning
|
||||
.apply_attempt(shown, &SrsSettings::default())
|
||||
.unwrap();
|
||||
let played = answer(&mut session, &library, &mut learning, "g1f3", "play-nf3");
|
||||
assert_eq!(played.event_type, TrainingEventType::AutoContext);
|
||||
// A shown new move is played once and counts as done.
|
||||
assert_eq!(queue_moves(&session), ["e2e4"]);
|
||||
assert_eq!(session.remaining(), 1);
|
||||
assert!(!session.showing_new);
|
||||
|
||||
let correct = answer(&mut session, &library, &mut learning, "e2e4", "second-try");
|
||||
assert_eq!(correct.event_type, TrainingEventType::CorrectIndependent);
|
||||
assert_eq!(session.phase, LearningSessionPhase::Finished);
|
||||
assert_eq!(session.remaining(), 0);
|
||||
let item = learning.item(&e4).unwrap();
|
||||
assert_eq!((item.wrong_count, item.correct_count), (1, 1));
|
||||
session.validate(&library).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hint_comes_back_but_not_in_a_one_pass_review() {
|
||||
let (library, id) = library("1. e4 e5 2. Nf3 *");
|
||||
let scope = StatsScope::for_repertoire(id, LearningSide::White, NOW);
|
||||
let mut learning = LearningData::default();
|
||||
for uci in ["e2e4", "g1f3"] {
|
||||
let item = learning.ensure_item(key_for(&library, &scope, uci));
|
||||
item.introduced = true;
|
||||
item.next_review_at = Some(NOW);
|
||||
}
|
||||
let mut daily = LearningSessionSnapshot::new_daily(
|
||||
"hint-daily",
|
||||
&library,
|
||||
&learning,
|
||||
scope.clone(),
|
||||
SrsSettings::default(),
|
||||
10,
|
||||
)
|
||||
.unwrap();
|
||||
daily.preview("hint", NOW).unwrap().unwrap();
|
||||
assert!(!daily.showing_new);
|
||||
answer(&mut daily, &library, &mut learning, "e2e4", "after-hint");
|
||||
assert_eq!(queue_moves(&daily), ["g1f3", "e2e4"]);
|
||||
|
||||
let mut review = LearningSessionSnapshot::new_single_pass_review(
|
||||
"hint-review",
|
||||
&library,
|
||||
&learning,
|
||||
scope,
|
||||
SrsSettings::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!review.return_mistakes);
|
||||
answer(&mut review, &library, &mut learning, "d2d4", "review-wrong");
|
||||
answer(
|
||||
&mut review,
|
||||
&library,
|
||||
&mut learning,
|
||||
"e2e4",
|
||||
"review-replay",
|
||||
);
|
||||
assert_eq!(queue_moves(&review), ["g1f3"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_pass_review_finishes_instead_of_starting_a_new_cycle() {
|
||||
let (library, id) = library("1. e4 e5 2. Nf3 *");
|
||||
let scope = StatsScope::for_repertoire(id, LearningSide::White, NOW);
|
||||
let mut learning = LearningData::default();
|
||||
let mut review = LearningSessionSnapshot::new_single_pass_review(
|
||||
"single",
|
||||
&library,
|
||||
&learning,
|
||||
scope.clone(),
|
||||
SrsSettings::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(review.session.mode, QueueMode::ReviewInOrder);
|
||||
assert_eq!(queue_moves(&review), ["e2e4", "g1f3"]);
|
||||
answer(&mut review, &library, &mut learning, "e2e4", "single-e4");
|
||||
to_question(&mut review, &library, &mut learning);
|
||||
answer(&mut review, &library, &mut learning, "g1f3", "single-nf3");
|
||||
assert_eq!(review.phase, LearningSessionPhase::Finished);
|
||||
assert_eq!(review.cycle, 0);
|
||||
review.validate(&library).unwrap();
|
||||
|
||||
// The old looping review is unchanged.
|
||||
let mut looping = LearningSessionSnapshot::new_with_mode(
|
||||
"loop",
|
||||
&library,
|
||||
&learning,
|
||||
scope,
|
||||
SrsSettings::default(),
|
||||
QueueMode::ReviewInOrder,
|
||||
)
|
||||
.unwrap();
|
||||
answer(&mut looping, &library, &mut learning, "e2e4", "loop-e4");
|
||||
to_question(&mut looping, &library, &mut learning);
|
||||
answer(&mut looping, &library, &mut learning, "g1f3", "loop-nf3");
|
||||
assert_eq!(looping.cycle, 1);
|
||||
assert_ne!(looping.phase, LearningSessionPhase::Finished);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn introduce_more_takes_the_next_unseen_moves_only() {
|
||||
let (library, id) = library(PGN);
|
||||
let scope = StatsScope::for_repertoire(id, LearningSide::White, NOW);
|
||||
let mut learning = LearningData::default();
|
||||
let mut session = LearningSessionSnapshot::new_daily(
|
||||
"more",
|
||||
&library,
|
||||
&learning,
|
||||
scope.clone(),
|
||||
SrsSettings::default(),
|
||||
2,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(queue_moves(&session), ["e2e4", "g1f3"]);
|
||||
assert_eq!(
|
||||
session.introduce_more(&library, &learning, 2),
|
||||
Err(LearningSessionError::IntroductionRequiresFinished)
|
||||
);
|
||||
for uci in ["e2e4", "g1f3"] {
|
||||
to_question(&mut session, &library, &mut learning);
|
||||
let shown = session
|
||||
.preview_new(format!("show-{uci}"), NOW)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
learning
|
||||
.apply_attempt(shown, &SrsSettings::default())
|
||||
.unwrap();
|
||||
answer(
|
||||
&mut session,
|
||||
&library,
|
||||
&mut learning,
|
||||
uci,
|
||||
&format!("play-{uci}"),
|
||||
);
|
||||
}
|
||||
assert_eq!(session.phase, LearningSessionPhase::Finished);
|
||||
// The two shown moves are due again in a minute, yet "more" means new ones only.
|
||||
assert_eq!(session.introduce_more(&library, &learning, 2), Ok(2));
|
||||
assert_eq!(queue_moves(&session), ["f1b5", "b5a4"]);
|
||||
assert_eq!(
|
||||
session.introduce_more(&library, &learning, 2),
|
||||
Err(LearningSessionError::IntroductionRequiresFinished)
|
||||
);
|
||||
let mut review = LearningSessionSnapshot::new_single_pass_review(
|
||||
"more-review",
|
||||
&library,
|
||||
&learning,
|
||||
scope,
|
||||
SrsSettings::default(),
|
||||
)
|
||||
.unwrap();
|
||||
while review.current_target().is_some() {
|
||||
review.current_index += 1;
|
||||
}
|
||||
review.phase = LearningSessionPhase::Finished;
|
||||
assert_eq!(
|
||||
review.introduce_more(&library, &learning, 2),
|
||||
Err(LearningSessionError::UnsupportedMode(
|
||||
QueueMode::ReviewInOrder
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn branch_session_asks_only_moves_of_the_branch_from_the_start_of_the_game() {
|
||||
let (library, id) = library(PGN);
|
||||
let through = ["e2e4", "e7e5", "g1f3", "b8c6", "f1c4"].map(str::to_owned);
|
||||
let scope = StatsScope::for_repertoire(id.clone(), LearningSide::White, NOW);
|
||||
let mut learning = LearningData::default();
|
||||
// Through an own move: that move is asked, its sibling Bb5 is not.
|
||||
let mut session = LearningSessionSnapshot::new_branch_review(
|
||||
"branch",
|
||||
&library,
|
||||
&learning,
|
||||
scope.clone(),
|
||||
SrsSettings::default(),
|
||||
&through,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(queue_moves(&session), ["f1c4"]);
|
||||
assert_eq!(
|
||||
session.stats_scope.branch_root.as_deref(),
|
||||
Some(&through[..4])
|
||||
);
|
||||
assert!(session.single_pass);
|
||||
let target = session.current_target().unwrap();
|
||||
assert_eq!(target.path, through);
|
||||
// The context is played from the start of the game, not from the branch.
|
||||
let presentation = session
|
||||
.presentation_with_learning(&library, &learning)
|
||||
.unwrap();
|
||||
assert_eq!(presentation.automatic_context.len(), 4);
|
||||
assert_eq!(presentation.automatic_context[0].uci, "e2e4");
|
||||
to_question(&mut session, &library, &mut learning);
|
||||
answer(&mut session, &library, &mut learning, "f1c4", "branch-bc4");
|
||||
assert_eq!(session.phase, LearningSessionPhase::Finished);
|
||||
session.validate(&library).unwrap();
|
||||
|
||||
// Through an opponent's move: every own move below it.
|
||||
let below = LearningSessionSnapshot::new_branch_review(
|
||||
"branch-below",
|
||||
&library,
|
||||
&LearningData::default(),
|
||||
scope.clone(),
|
||||
SrsSettings::default(),
|
||||
&through[..4],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(queue_moves(&below), ["f1b5", "b5a4", "f1c4"]);
|
||||
assert!(
|
||||
below
|
||||
.queue
|
||||
.iter()
|
||||
.all(|target| target.path.starts_with(&through[..4]))
|
||||
);
|
||||
|
||||
// The whole repertoire, and a daily session limited by a branch root.
|
||||
let whole = LearningSessionSnapshot::new_branch_review(
|
||||
"branch-whole",
|
||||
&library,
|
||||
&LearningData::default(),
|
||||
scope.clone(),
|
||||
SrsSettings::default(),
|
||||
&[],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(queue_moves(&whole).len(), 5);
|
||||
let daily = LearningSessionSnapshot::new_daily(
|
||||
"branch-daily",
|
||||
&library,
|
||||
&LearningData::default(),
|
||||
scope.with_branch_root(through[..4].to_vec()),
|
||||
SrsSettings::default(),
|
||||
10,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(queue_moves(&daily), ["f1b5", "b5a4", "f1c4"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_flags_are_optional_in_the_file_and_survive_a_roundtrip() {
|
||||
let (library, id) = library("1. e4 *");
|
||||
let scope = StatsScope::for_repertoire(id, LearningSide::White, NOW);
|
||||
let learning = LearningData::default();
|
||||
let plain = LearningSessionSnapshot::new(
|
||||
"plain",
|
||||
&library,
|
||||
&learning,
|
||||
scope.clone(),
|
||||
SrsSettings::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let json = serde_json::to_value(&plain).unwrap();
|
||||
// 2.3.0 snapshots stay byte-compatible when no new behaviour is used.
|
||||
for field in ["return_mistakes", "single_pass", "showing_new"] {
|
||||
assert!(
|
||||
json.get(field).is_none(),
|
||||
"{field} written for an old-style session"
|
||||
);
|
||||
}
|
||||
let read: LearningSessionSnapshot = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(read, plain);
|
||||
|
||||
let mut daily = LearningSessionSnapshot::new_daily(
|
||||
"flags",
|
||||
&library,
|
||||
&learning,
|
||||
scope,
|
||||
SrsSettings::default(),
|
||||
10,
|
||||
)
|
||||
.unwrap();
|
||||
daily.preview_new("show", NOW).unwrap();
|
||||
daily.single_pass = true;
|
||||
let json = serde_json::to_string(&daily).unwrap();
|
||||
let read: LearningSessionSnapshot = serde_json::from_str(&json).unwrap();
|
||||
assert!(read.return_mistakes && read.single_pass && read.showing_new);
|
||||
read.validate(&library).unwrap();
|
||||
}
|
||||
|
|
@ -85,24 +85,10 @@ pub struct LearningSessionSnapshot {
|
|||
/// Per-session optimistic revision, independent from the store revision.
|
||||
#[serde(default)]
|
||||
pub revision: u64,
|
||||
/// A move answered after a mistake or a hint goes to the end of this session's
|
||||
/// queue instead of being completed (daily sessions).
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub return_mistakes: bool,
|
||||
/// Review in order ends after one pass instead of starting the next cycle.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub single_pass: bool,
|
||||
/// The pending preview is the first showing of a new move, not a hint.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub showing_new: bool,
|
||||
#[serde(skip)]
|
||||
runtime: SessionRuntime,
|
||||
}
|
||||
|
||||
fn is_false(value: &bool) -> bool {
|
||||
!*value
|
||||
}
|
||||
|
||||
// Derived data only: clones share it, persistence and snapshot equality do not.
|
||||
#[derive(Clone, Default, Debug)]
|
||||
struct SessionRuntime(Arc<Mutex<RuntimeData>>);
|
||||
|
|
@ -309,114 +295,12 @@ impl LearningSessionSnapshot {
|
|||
completed_keys: BTreeSet::new(),
|
||||
cycle: 0,
|
||||
revision: 0,
|
||||
return_mistakes: false,
|
||||
single_pass: false,
|
||||
showing_new: false,
|
||||
runtime: SessionRuntime::default(),
|
||||
};
|
||||
snapshot.reset_current_target_with_library(library)?;
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
/// A daily session: every move due at `stats_scope.as_of` and at most `max_new`
|
||||
/// moves never shown before, in the scope's priority order. A move answered after a
|
||||
/// mistake or a hint comes back later in the same session.
|
||||
pub fn new_daily(
|
||||
id: impl Into<String>,
|
||||
library: &Library,
|
||||
learning: &LearningData,
|
||||
stats_scope: StatsScope,
|
||||
settings: SrsSettings,
|
||||
max_new: usize,
|
||||
) -> Result<Self, LearningSessionError> {
|
||||
let mut snapshot = Self::new_with_mode(
|
||||
id,
|
||||
library,
|
||||
learning,
|
||||
stats_scope,
|
||||
settings,
|
||||
QueueMode::SpacedRepetition,
|
||||
)?;
|
||||
snapshot.queue = daily_targets(library, learning, &snapshot.stats_scope, true, max_new)?;
|
||||
snapshot.return_mistakes = true;
|
||||
snapshot.reset_current_target_with_library(library)?;
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
/// One pass over every active move in the scope's order, then `Finished`.
|
||||
pub fn new_single_pass_review(
|
||||
id: impl Into<String>,
|
||||
library: &Library,
|
||||
learning: &LearningData,
|
||||
stats_scope: StatsScope,
|
||||
settings: SrsSettings,
|
||||
) -> Result<Self, LearningSessionError> {
|
||||
let mut snapshot = Self::new_with_mode(
|
||||
id,
|
||||
library,
|
||||
learning,
|
||||
stats_scope,
|
||||
settings,
|
||||
QueueMode::ReviewInOrder,
|
||||
)?;
|
||||
snapshot.single_pass = true;
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
/// One pass over the lines through the move at `through` (a PGN path; empty: every
|
||||
/// line). The move itself is asked when it is the trained side's.
|
||||
pub fn new_branch_review(
|
||||
id: impl Into<String>,
|
||||
library: &Library,
|
||||
learning: &LearningData,
|
||||
stats_scope: StatsScope,
|
||||
settings: SrsSettings,
|
||||
through: &[String],
|
||||
) -> Result<Self, LearningSessionError> {
|
||||
let stats_scope = match through.split_last() {
|
||||
Some((_, root)) => stats_scope.with_branch_root(root.to_vec()),
|
||||
None => stats_scope,
|
||||
};
|
||||
let mut snapshot =
|
||||
Self::new_single_pass_review(id, library, learning, stats_scope, settings)?;
|
||||
snapshot
|
||||
.queue
|
||||
.retain(|target| target.path.starts_with(through));
|
||||
snapshot.reset_current_target_with_library(library)?;
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
/// After a finished daily session: the next `max_new` unseen moves only.
|
||||
pub fn introduce_more(
|
||||
&mut self,
|
||||
library: &Library,
|
||||
learning: &LearningData,
|
||||
max_new: usize,
|
||||
) -> Result<usize, LearningSessionError> {
|
||||
self.validate_configuration()?;
|
||||
if self.session.mode != QueueMode::SpacedRepetition {
|
||||
return Err(LearningSessionError::UnsupportedMode(self.session.mode));
|
||||
}
|
||||
if self.phase != LearningSessionPhase::Finished {
|
||||
return Err(LearningSessionError::IntroductionRequiresFinished);
|
||||
}
|
||||
self.queue = daily_targets(library, learning, &self.stats_scope, false, max_new)?;
|
||||
self.current_index = 0;
|
||||
self.completed_keys.clear();
|
||||
self.reset_current_target_with_library(library)?;
|
||||
Ok(self.queue.len())
|
||||
}
|
||||
|
||||
/// The current move has never been shown: true when it has no learning state or was
|
||||
/// never introduced.
|
||||
pub fn current_is_new(&self, learning: &LearningData) -> bool {
|
||||
self.current_target().is_some_and(|target| {
|
||||
learning
|
||||
.item(&target.key)
|
||||
.is_none_or(|item| !item.introduced)
|
||||
})
|
||||
}
|
||||
|
||||
/// Explicitly replaces a finished queue with the currently unseen items. No item is
|
||||
/// introduced into SRS until an independent answer or preview is recorded.
|
||||
pub fn introduce_new(
|
||||
|
|
@ -693,25 +577,6 @@ impl LearningSessionSnapshot {
|
|||
&mut self,
|
||||
client_attempt_id: impl Into<String>,
|
||||
happened_at: i64,
|
||||
) -> Result<Option<TrainingAttempt>, LearningSessionError> {
|
||||
self.preview_impl(client_attempt_id, happened_at, false)
|
||||
}
|
||||
|
||||
/// Shows a new move before asking it. The move is recorded as `PREVIEWED`, but in a
|
||||
/// daily session it does not come back as a mistake would.
|
||||
pub fn preview_new(
|
||||
&mut self,
|
||||
client_attempt_id: impl Into<String>,
|
||||
happened_at: i64,
|
||||
) -> Result<Option<TrainingAttempt>, LearningSessionError> {
|
||||
self.preview_impl(client_attempt_id, happened_at, true)
|
||||
}
|
||||
|
||||
fn preview_impl(
|
||||
&mut self,
|
||||
client_attempt_id: impl Into<String>,
|
||||
happened_at: i64,
|
||||
new: bool,
|
||||
) -> Result<Option<TrainingAttempt>, LearningSessionError> {
|
||||
let client_attempt_id = checked_attempt_id(client_attempt_id.into())?;
|
||||
self.validate_configuration()?;
|
||||
|
|
@ -733,7 +598,6 @@ impl LearningSessionSnapshot {
|
|||
"preview has no current target",
|
||||
))?;
|
||||
self.phase = LearningSessionPhase::PreviewedReplay;
|
||||
self.showing_new = new;
|
||||
Ok(Some(self.attempt(
|
||||
&target.key,
|
||||
TrainingEventType::Previewed,
|
||||
|
|
@ -970,8 +834,6 @@ impl LearningSessionSnapshot {
|
|||
{
|
||||
if context {
|
||||
self.complete_context(challenge_key, library, learning)?;
|
||||
} else if self.return_mistakes && !self.showing_new {
|
||||
self.return_current(library)?;
|
||||
} else {
|
||||
self.complete_current(library)?;
|
||||
}
|
||||
|
|
@ -1106,7 +968,6 @@ impl LearningSessionSnapshot {
|
|||
self.current_index += 1;
|
||||
}
|
||||
if self.session.mode == QueueMode::ReviewInOrder
|
||||
&& !self.single_pass
|
||||
&& self.current_index >= self.queue.len()
|
||||
&& !self.queue.is_empty()
|
||||
{
|
||||
|
|
@ -1117,22 +978,6 @@ impl LearningSessionSnapshot {
|
|||
self.reset_current_target_with_library(library)
|
||||
}
|
||||
|
||||
/// Moves the current target behind the rest of the queue: it is asked again later
|
||||
/// in this session, from the start of its line.
|
||||
fn return_current(&mut self, library: &Library) -> Result<(), LearningSessionError> {
|
||||
if self.current_index < self.queue.len() {
|
||||
let target = self.queue.remove(self.current_index);
|
||||
self.queue.push(target);
|
||||
}
|
||||
while self
|
||||
.current_target()
|
||||
.is_some_and(|target| self.completed_keys.contains(&target.key))
|
||||
{
|
||||
self.current_index += 1;
|
||||
}
|
||||
self.reset_current_target_with_library(library)
|
||||
}
|
||||
|
||||
fn complete_context(
|
||||
&mut self,
|
||||
key: LearningItemKey,
|
||||
|
|
@ -1292,7 +1137,6 @@ impl LearningSessionSnapshot {
|
|||
|
||||
fn reset_current_target(&mut self) {
|
||||
self.context_index = 0;
|
||||
self.showing_new = false;
|
||||
self.phase = match self.current_target() {
|
||||
None => LearningSessionPhase::Finished,
|
||||
Some(target) if target.path.len() > 1 => LearningSessionPhase::AdvancingContext,
|
||||
|
|
@ -1346,38 +1190,6 @@ fn select_queue(
|
|||
}
|
||||
}
|
||||
|
||||
fn daily_targets(
|
||||
library: &Library,
|
||||
learning: &LearningData,
|
||||
scope: &StatsScope,
|
||||
include_due: bool,
|
||||
max_new: usize,
|
||||
) -> Result<Vec<LearningSessionTarget>, LearningSessionError> {
|
||||
let mut new = 0usize;
|
||||
Ok(select_memberships(
|
||||
library,
|
||||
learning,
|
||||
scope,
|
||||
|item| {
|
||||
item.is_none_or(|item| !item.introduced)
|
||||
|| item.is_some_and(|item| item.is_due(scope.as_of))
|
||||
},
|
||||
scope.learning_priority,
|
||||
)?
|
||||
.into_iter()
|
||||
.filter(|membership| {
|
||||
let item = learning.item(&membership.key);
|
||||
if item.is_none_or(|item| !item.introduced) {
|
||||
new += 1;
|
||||
new <= max_new
|
||||
} else {
|
||||
include_due
|
||||
}
|
||||
})
|
||||
.map(LearningSessionTarget::from)
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn select_targets(
|
||||
library: &Library,
|
||||
learning: &LearningData,
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ mod learning_session;
|
|||
mod line_analytics;
|
||||
mod model;
|
||||
mod scope;
|
||||
mod session;
|
||||
mod srs;
|
||||
mod stats;
|
||||
mod store;
|
||||
|
|
@ -50,6 +51,10 @@ pub use model::{
|
|||
Repertoire, RepertoireError, RepertoireId,
|
||||
};
|
||||
pub use scope::{TrainingScope, TrainingScopeKey};
|
||||
pub use session::{
|
||||
FirstMoveChooser, MoveChooser, PlayedMove, PreparedNextPath, SessionAttempt, SessionError,
|
||||
TrainingSession, TrainingVerdict,
|
||||
};
|
||||
pub use srs::{
|
||||
DEFAULT_GROWTH_FACTOR, FIRST_CORRECT_DELAY_SECONDS, MIN_PRACTICAL_INTERVAL_SECONDS,
|
||||
MISTAKE_DELAY_SECONDS, PREVIEW_DELAY_SECONDS, SRS_MAX_INTERVAL_SECONDS, SrsSettings,
|
||||
|
|
@ -57,15 +62,16 @@ pub use srs::{
|
|||
apply_independent_correct, apply_independent_wrong, apply_preview,
|
||||
};
|
||||
pub use stats::{
|
||||
AttemptRecord, MoveKey, MoveStats, PathKey, PathStats, QueueMode, RunRecord, RunStats,
|
||||
STATS_VERSION, StatsData, TrainingMode,
|
||||
AttemptRecord, INITIAL_INTERVAL_SECONDS, INTRODUCTION_BATCH_SIZE, MAX_INTERVAL_SECONDS,
|
||||
MISTAKE_INTERVAL_SECONDS, MoveKey, MoveStats, PathKey, PathStats, QueueMode, RunRecord,
|
||||
RunStats, STATS_VERSION, SrsPolicy, StatsData, TrainingMode,
|
||||
};
|
||||
pub use store::{
|
||||
LEARNING_STORE_VERSION, LearningSession, LearningStore, LearningStoreData, LibraryStore,
|
||||
MigrationReport, PersistedAttempt, PersistedLearningReset, PersistedLearningSnapshot,
|
||||
PersistedSessionAttempt, StatsStore, StoreError,
|
||||
};
|
||||
pub use tree::{Candidate, RepertoireTree, fen4};
|
||||
pub use tree::{Candidate, RepertoireTree, TrainingPath, TrainingTarget, fen4};
|
||||
|
||||
#[cfg(test)]
|
||||
mod acceptance_tests;
|
||||
|
|
@ -76,8 +82,6 @@ mod analytics_tests;
|
|||
#[cfg(test)]
|
||||
mod branch_tests;
|
||||
#[cfg(test)]
|
||||
mod daily_tests;
|
||||
#[cfg(test)]
|
||||
mod graph_tests;
|
||||
#[cfg(test)]
|
||||
mod line_tests;
|
||||
|
|
|
|||
|
|
@ -16,6 +16,33 @@ impl TrainingScope {
|
|||
Self::default()
|
||||
}
|
||||
|
||||
pub fn from_prefix(prefix: Vec<String>) -> Self {
|
||||
Self {
|
||||
prefix,
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn between(prefix: Vec<String>, end_prefix: Vec<String>) -> Self {
|
||||
Self {
|
||||
prefix,
|
||||
end_prefix: Some(end_prefix),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_context(mut self, include_context: bool) -> Self {
|
||||
self.include_context = include_context;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn key(&self) -> TrainingScopeKey {
|
||||
TrainingScopeKey {
|
||||
prefix: self.prefix.clone(),
|
||||
end_prefix: self.end_prefix.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parent_prefix(&self) -> &[String] {
|
||||
self.prefix
|
||||
.get(..self.prefix.len().saturating_sub(1))
|
||||
|
|
|
|||
1162
crates/trainer/src/repertoire/session.rs
Normal file
1162
crates/trainer/src/repertoire/session.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1,11 +1,14 @@
|
|||
use chess_core::shakmaty::Color;
|
||||
use chess_core::shakmaty::{Color, Position};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::model::RepertoireId;
|
||||
use super::scope::TrainingScopeKey;
|
||||
use super::scope::{TrainingScope, TrainingScopeKey};
|
||||
use super::tree::{RepertoireTree, TrainingPath, TrainingTarget};
|
||||
|
||||
pub const STATS_VERSION: u32 = 2;
|
||||
/// Recent attempts kept per move in a v2 file.
|
||||
pub const INITIAL_INTERVAL_SECONDS: i64 = 24 * 60 * 60;
|
||||
pub const MISTAKE_INTERVAL_SECONDS: i64 = 10 * 60;
|
||||
pub const MAX_INTERVAL_SECONDS: i64 = 365 * 24 * 60 * 60;
|
||||
const RECENT: usize = 10;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
|
|
@ -33,6 +36,15 @@ pub enum QueueMode {
|
|||
LeastRecent,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum SrsPolicy {
|
||||
Due,
|
||||
Introduce,
|
||||
EarlyReview,
|
||||
}
|
||||
|
||||
pub const INTRODUCTION_BATCH_SIZE: usize = 10;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct MoveKey {
|
||||
pub repertoire_id: RepertoireId,
|
||||
|
|
@ -91,7 +103,6 @@ impl Default for MoveStats {
|
|||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl MoveStats {
|
||||
pub fn new(key: MoveKey) -> Self {
|
||||
Self {
|
||||
|
|
@ -99,6 +110,88 @@ impl MoveStats {
|
|||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unseen(&self) -> bool {
|
||||
self.attempts == 0
|
||||
}
|
||||
|
||||
pub fn is_due(&self, now: i64) -> bool {
|
||||
self.due.is_some_and(|due| due <= now)
|
||||
}
|
||||
|
||||
fn push_recent(&mut self, attempt: AttemptRecord) {
|
||||
self.recent.push(attempt);
|
||||
if self.recent.len() > RECENT {
|
||||
self.recent.remove(0);
|
||||
}
|
||||
}
|
||||
|
||||
fn wrong(&mut self, now: i64, actual_uci: &str, schedule: bool) {
|
||||
self.attempts = self.attempts.saturating_add(1);
|
||||
self.wrong = self.wrong.saturating_add(1);
|
||||
self.streak = if self.streak < 0 {
|
||||
self.streak.saturating_sub(1)
|
||||
} else {
|
||||
-1
|
||||
};
|
||||
self.last_attempt = Some(now);
|
||||
self.last_seen = Some(now);
|
||||
if schedule {
|
||||
self.due = Some(now.saturating_add(MISTAKE_INTERVAL_SECONDS));
|
||||
self.interval_seconds = Some(MISTAKE_INTERVAL_SECONDS);
|
||||
}
|
||||
self.push_recent(AttemptRecord {
|
||||
at: now,
|
||||
correct: false,
|
||||
hinted: false,
|
||||
actual_uci: actual_uci.to_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
fn correct(&mut self, now: i64, actual_uci: &str, hinted: bool, schedule: bool) {
|
||||
let previous_interval =
|
||||
self.interval_seconds
|
||||
.unwrap_or_else(|| match (self.due, self.last_seen) {
|
||||
(Some(due), Some(last)) if due > last => due.saturating_sub(last),
|
||||
_ => INITIAL_INTERVAL_SECONDS,
|
||||
});
|
||||
let clean_streak = self.streak;
|
||||
let retry = hinted || clean_streak < 0;
|
||||
self.attempts = self.attempts.saturating_add(1);
|
||||
self.correct = self.correct.saturating_add(1);
|
||||
self.streak = if retry {
|
||||
0
|
||||
} else {
|
||||
clean_streak.saturating_add(1).max(1)
|
||||
};
|
||||
if schedule {
|
||||
let interval = if retry {
|
||||
MISTAKE_INTERVAL_SECONDS
|
||||
} else if clean_streak > 0 {
|
||||
previous_interval
|
||||
.saturating_mul(2)
|
||||
.clamp(INITIAL_INTERVAL_SECONDS, MAX_INTERVAL_SECONDS)
|
||||
} else {
|
||||
INITIAL_INTERVAL_SECONDS
|
||||
};
|
||||
self.due = Some(now.saturating_add(interval));
|
||||
self.interval_seconds = Some(interval);
|
||||
}
|
||||
self.last_attempt = Some(now);
|
||||
self.last_seen = Some(now);
|
||||
self.push_recent(AttemptRecord {
|
||||
at: now,
|
||||
correct: true,
|
||||
hinted,
|
||||
actual_uci: actual_uci.to_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
fn hint(&mut self, now: i64) {
|
||||
self.streak = 0;
|
||||
self.hints = self.hints.saturating_add(1);
|
||||
self.last_seen = Some(now);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
|
@ -182,6 +275,11 @@ struct RandomPracticeCursor {
|
|||
fingerprint: Option<u64>,
|
||||
}
|
||||
|
||||
pub(crate) struct RandomPracticePath {
|
||||
pub path: TrainingPath,
|
||||
pub start: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct StatsData {
|
||||
|
|
@ -216,6 +314,616 @@ impl Default for StatsData {
|
|||
}
|
||||
|
||||
impl StatsData {
|
||||
/// Removes modern statistics and queue positions for one repertoire. Legacy line
|
||||
/// aggregates have independent identities and remain untouched.
|
||||
pub fn remove_repertoire(&mut self, repertoire_id: &RepertoireId) {
|
||||
self.move_stats
|
||||
.retain(|entry| &entry.key.repertoire_id != repertoire_id);
|
||||
self.runs
|
||||
.retain(|entry| &entry.repertoire_id != repertoire_id);
|
||||
self.path_stats
|
||||
.retain(|entry| &entry.key.repertoire_id != repertoire_id);
|
||||
self.review_cursors
|
||||
.retain(|entry| &entry.repertoire_id != repertoire_id);
|
||||
self.path_review_cursors
|
||||
.retain(|entry| &entry.repertoire_id != repertoire_id);
|
||||
self.practice_path_cursors
|
||||
.retain(|entry| &entry.repertoire_id != repertoire_id);
|
||||
self.random_practice_cursors
|
||||
.retain(|entry| &entry.repertoire_id != repertoire_id);
|
||||
}
|
||||
|
||||
pub fn remove_repertoire_mode(&mut self, repertoire_id: &RepertoireId, mode: TrainingMode) {
|
||||
self.move_stats
|
||||
.retain(|entry| &entry.key.repertoire_id != repertoire_id || entry.key.mode != mode);
|
||||
self.runs
|
||||
.retain(|entry| &entry.repertoire_id != repertoire_id || entry.mode != mode);
|
||||
self.review_cursors
|
||||
.retain(|entry| &entry.repertoire_id != repertoire_id || entry.mode != mode);
|
||||
self.practice_path_cursors
|
||||
.retain(|entry| &entry.repertoire_id != repertoire_id || entry.mode != mode);
|
||||
self.random_practice_cursors
|
||||
.retain(|entry| &entry.repertoire_id != repertoire_id || entry.mode != mode);
|
||||
if mode == TrainingMode::Both {
|
||||
self.path_stats
|
||||
.retain(|entry| &entry.key.repertoire_id != repertoire_id);
|
||||
self.path_review_cursors
|
||||
.retain(|entry| &entry.repertoire_id != repertoire_id);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get(&self, key: &MoveKey) -> Option<&MoveStats> {
|
||||
self.move_stats.iter().find(|stats| &stats.key == key)
|
||||
}
|
||||
|
||||
pub fn runs(&self, repertoire_id: &RepertoireId, mode: TrainingMode) -> Option<&RunStats> {
|
||||
self.runs
|
||||
.iter()
|
||||
.find(|runs| &runs.repertoire_id == repertoire_id && runs.mode == mode)
|
||||
}
|
||||
|
||||
/// Compatibility queue used by the existing desktop summary. SRS sessions use the
|
||||
/// more specific `srs_queue` policies below and never automatically exhaust this list.
|
||||
pub fn queue(
|
||||
&self,
|
||||
tree: &RepertoireTree,
|
||||
repertoire_id: &RepertoireId,
|
||||
mode: TrainingMode,
|
||||
queue_mode: QueueMode,
|
||||
now: i64,
|
||||
) -> Vec<TrainingTarget> {
|
||||
self.scoped_queue(
|
||||
tree,
|
||||
repertoire_id,
|
||||
mode,
|
||||
queue_mode,
|
||||
now,
|
||||
&TrainingScope::whole(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn scoped_queue(
|
||||
&self,
|
||||
tree: &RepertoireTree,
|
||||
repertoire_id: &RepertoireId,
|
||||
mode: TrainingMode,
|
||||
queue_mode: QueueMode,
|
||||
now: i64,
|
||||
scope: &TrainingScope,
|
||||
) -> Vec<TrainingTarget> {
|
||||
let Some(color) = mode.user_color() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let targets = tree.scoped_targets(color, scope);
|
||||
let key = |target: &TrainingTarget| MoveKey {
|
||||
repertoire_id: repertoire_id.clone(),
|
||||
mode,
|
||||
position_fen4: target.position_fen4.clone(),
|
||||
expected_uci: target.expected_uci.clone(),
|
||||
};
|
||||
let mut indexed: Vec<(usize, TrainingTarget)> = targets.into_iter().enumerate().collect();
|
||||
match queue_mode {
|
||||
QueueMode::SpacedRepetition => {
|
||||
let mut due = Vec::new();
|
||||
let mut unseen = Vec::new();
|
||||
let mut unscheduled = Vec::new();
|
||||
for (order, target) in indexed {
|
||||
match self.get(&key(&target)) {
|
||||
Some(stats) if stats.is_due(now) => due.push((stats.due, order, target)),
|
||||
Some(stats) if stats.due.is_none() => {
|
||||
unscheduled.push((order, target));
|
||||
}
|
||||
Some(_) => {}
|
||||
None => unseen.push((order, target)),
|
||||
}
|
||||
}
|
||||
due.sort_by_key(|(due, order, _)| (*due, *order));
|
||||
due.into_iter()
|
||||
.map(|(_, _, target)| target)
|
||||
.chain(unseen.into_iter().map(|(_, target)| target))
|
||||
.chain(unscheduled.into_iter().map(|(_, target)| target))
|
||||
.collect()
|
||||
}
|
||||
QueueMode::LeastRecent => {
|
||||
indexed.sort_by_key(|(order, target)| {
|
||||
let stats = self.get(&key(target));
|
||||
(
|
||||
!stats.is_none_or(MoveStats::unseen),
|
||||
stats.and_then(|stats| stats.last_seen).unwrap_or(i64::MIN),
|
||||
*order,
|
||||
)
|
||||
});
|
||||
indexed.into_iter().map(|(_, target)| target).collect()
|
||||
}
|
||||
QueueMode::Practice | QueueMode::ReviewInOrder => {
|
||||
let scope_key = scope.key();
|
||||
let cursor = self
|
||||
.review_cursors
|
||||
.iter()
|
||||
.find(|cursor| {
|
||||
&cursor.repertoire_id == repertoire_id
|
||||
&& cursor.mode == mode
|
||||
&& cursor.scope == scope_key
|
||||
})
|
||||
.map_or(0, |cursor| cursor.next);
|
||||
if indexed.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let offset = cursor % indexed.len();
|
||||
indexed.rotate_left(offset);
|
||||
indexed.into_iter().map(|(_, target)| target).collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn srs_queue(
|
||||
&self,
|
||||
tree: &RepertoireTree,
|
||||
repertoire_id: &RepertoireId,
|
||||
mode: TrainingMode,
|
||||
now: i64,
|
||||
scope: &TrainingScope,
|
||||
policy: SrsPolicy,
|
||||
) -> Vec<TrainingTarget> {
|
||||
let Some(color) = mode.user_color() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let key = |target: &TrainingTarget| MoveKey {
|
||||
repertoire_id: repertoire_id.clone(),
|
||||
mode,
|
||||
position_fen4: target.position_fen4.clone(),
|
||||
expected_uci: target.expected_uci.clone(),
|
||||
};
|
||||
let mut due = Vec::new();
|
||||
let mut future = Vec::new();
|
||||
let mut unseen = Vec::new();
|
||||
let mut unscheduled = Vec::new();
|
||||
for (order, target) in tree.scoped_targets(color, scope).into_iter().enumerate() {
|
||||
match self.get(&key(&target)) {
|
||||
Some(stats) if stats.is_due(now) => due.push((stats.due, order, target)),
|
||||
Some(stats) if stats.due.is_some() => future.push((stats.due, order, target)),
|
||||
Some(stats) if stats.unseen() => unseen.push((order, target)),
|
||||
Some(_) => unscheduled.push((order, target)),
|
||||
None => unseen.push((order, target)),
|
||||
}
|
||||
}
|
||||
due.sort_by_key(|(due, order, _)| (*due, *order));
|
||||
future.sort_by_key(|(due, order, _)| (*due, *order));
|
||||
match policy {
|
||||
SrsPolicy::Due => due.into_iter().map(|(_, _, target)| target).collect(),
|
||||
SrsPolicy::Introduce => unseen
|
||||
.into_iter()
|
||||
.chain(unscheduled)
|
||||
.take(INTRODUCTION_BATCH_SIZE)
|
||||
.map(|(_, target)| target)
|
||||
.collect(),
|
||||
SrsPolicy::EarlyReview => future.into_iter().map(|(_, _, target)| target).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn path_stats(&self, key: &PathKey) -> Option<&PathStats> {
|
||||
self.path_stats.iter().find(|stats| &stats.key == key)
|
||||
}
|
||||
|
||||
pub fn path_queue(
|
||||
&self,
|
||||
tree: &RepertoireTree,
|
||||
repertoire_id: &RepertoireId,
|
||||
scope: &TrainingScope,
|
||||
queue_mode: QueueMode,
|
||||
) -> Result<Vec<TrainingPath>, String> {
|
||||
let scope_key = scope.key();
|
||||
let mut paths = tree.training_paths(scope)?;
|
||||
if queue_mode == QueueMode::LeastRecent {
|
||||
paths.sort_by_key(|path| {
|
||||
let key = PathKey {
|
||||
repertoire_id: repertoire_id.clone(),
|
||||
scope: scope_key.clone(),
|
||||
path: path.moves.clone(),
|
||||
};
|
||||
let stats = self.path_stats(&key);
|
||||
(
|
||||
stats.is_some_and(|stats| stats.completions > 0),
|
||||
stats
|
||||
.and_then(|stats| stats.last_completion)
|
||||
.unwrap_or(i64::MIN),
|
||||
)
|
||||
});
|
||||
return Ok(paths);
|
||||
}
|
||||
if paths.is_empty() {
|
||||
return Ok(paths);
|
||||
}
|
||||
let cursor = self
|
||||
.path_review_cursors
|
||||
.iter()
|
||||
.find(|cursor| &cursor.repertoire_id == repertoire_id && cursor.scope == scope_key)
|
||||
.map_or(0, |cursor| cursor.next);
|
||||
let offset = cursor % paths.len();
|
||||
paths.rotate_left(offset);
|
||||
Ok(paths)
|
||||
}
|
||||
|
||||
pub(crate) fn next_practice_path(
|
||||
&mut self,
|
||||
tree: &RepertoireTree,
|
||||
repertoire_id: &RepertoireId,
|
||||
mode: TrainingMode,
|
||||
scope: &TrainingScope,
|
||||
) -> Result<Option<TrainingPath>, String> {
|
||||
use std::ops::ControlFlow;
|
||||
let scope_key = scope.key();
|
||||
let index = match self.practice_path_cursors.iter().position(|c| {
|
||||
&c.repertoire_id == repertoire_id && c.mode == mode && c.scope == scope_key
|
||||
}) {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
self.practice_path_cursors.push(ReviewCursor {
|
||||
repertoire_id: repertoire_id.clone(),
|
||||
mode,
|
||||
scope: scope_key,
|
||||
next: 0,
|
||||
});
|
||||
self.practice_path_cursors.len() - 1
|
||||
}
|
||||
};
|
||||
let cursor = self.practice_path_cursors[index].next;
|
||||
let mut count = 0usize;
|
||||
let mut chosen = None;
|
||||
tree.visit_training_paths(scope, |moves| {
|
||||
if count == cursor {
|
||||
chosen = Some(TrainingPath {
|
||||
moves: moves.to_vec(),
|
||||
});
|
||||
return ControlFlow::Break(());
|
||||
}
|
||||
count += 1;
|
||||
ControlFlow::Continue(())
|
||||
})?;
|
||||
if chosen.is_none() && count > 0 {
|
||||
let offset = cursor % count;
|
||||
let mut order = 0;
|
||||
tree.visit_training_paths(scope, |moves| {
|
||||
if order == offset {
|
||||
chosen = Some(TrainingPath {
|
||||
moves: moves.to_vec(),
|
||||
});
|
||||
return ControlFlow::Break(());
|
||||
}
|
||||
order += 1;
|
||||
ControlFlow::Continue(())
|
||||
})?;
|
||||
self.practice_path_cursors[index].next = offset;
|
||||
}
|
||||
if chosen.is_some() {
|
||||
self.practice_path_cursors[index].next =
|
||||
self.practice_path_cursors[index].next.saturating_add(1);
|
||||
}
|
||||
Ok(chosen)
|
||||
}
|
||||
|
||||
pub(crate) fn next_random_practice_path(
|
||||
&mut self,
|
||||
tree: &RepertoireTree,
|
||||
repertoire_id: &RepertoireId,
|
||||
mode: TrainingMode,
|
||||
scope: &TrainingScope,
|
||||
repertoire_fingerprint: u64,
|
||||
initial_seed: u64,
|
||||
) -> Result<Option<RandomPracticePath>, String> {
|
||||
use std::ops::ControlFlow;
|
||||
|
||||
let anchor = tree.scope_anchor(scope)?;
|
||||
let start_turn = tree
|
||||
.position(anchor)
|
||||
.map(|position| position.turn())
|
||||
.ok_or_else(|| "scope start position is missing".to_owned())?;
|
||||
let mut count = Some(0usize);
|
||||
tree.visit_source_paths(scope, |moves| {
|
||||
if eligible_target_count(mode, start_turn, moves.len()) == 0 {
|
||||
return ControlFlow::Continue(());
|
||||
}
|
||||
count = count.and_then(|count| count.checked_add(1));
|
||||
if count.is_none() {
|
||||
ControlFlow::Break(())
|
||||
} else {
|
||||
ControlFlow::Continue(())
|
||||
}
|
||||
})?;
|
||||
let count =
|
||||
count.ok_or_else(|| "training path count exceeds the platform limit".to_owned())?;
|
||||
let scope_key = scope.key();
|
||||
let existing = self.random_practice_cursors.iter().position(|cursor| {
|
||||
&cursor.repertoire_id == repertoire_id
|
||||
&& cursor.mode == mode
|
||||
&& cursor.scope == scope_key
|
||||
});
|
||||
let is_new = existing.is_none();
|
||||
let index = existing.unwrap_or_else(|| {
|
||||
self.random_practice_cursors.push(RandomPracticeCursor {
|
||||
repertoire_id: repertoire_id.clone(),
|
||||
mode,
|
||||
scope: scope_key,
|
||||
seed: initial_seed,
|
||||
position: 0,
|
||||
count: 0,
|
||||
fingerprint: Some(repertoire_fingerprint),
|
||||
});
|
||||
self.random_practice_cursors.len() - 1
|
||||
});
|
||||
let cursor = &mut self.random_practice_cursors[index];
|
||||
if !is_new
|
||||
&& (cursor.fingerprint != Some(repertoire_fingerprint)
|
||||
|| cursor.count != count
|
||||
|| cursor.position >= count)
|
||||
{
|
||||
cursor.seed = next_cycle_seed(cursor.seed);
|
||||
cursor.position = 0;
|
||||
}
|
||||
cursor.fingerprint = Some(repertoire_fingerprint);
|
||||
cursor.count = count;
|
||||
if count == 0 {
|
||||
cursor.position = 0;
|
||||
return Ok(None);
|
||||
}
|
||||
if cursor.position >= count {
|
||||
cursor.position = 0;
|
||||
}
|
||||
|
||||
let position = cursor.position;
|
||||
let seed = cursor.seed;
|
||||
let step = coprime_step(seed ^ 0xa076_1d64_78bd_642f, count);
|
||||
let offset = (mix64(seed ^ 0xe703_7ed1_a0b4_28db) as u128 % count as u128) as usize;
|
||||
let selected_index =
|
||||
((step as u128 * position as u128 + offset as u128) % count as u128) as usize;
|
||||
let start_seed = mix64(seed ^ (position as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15));
|
||||
let mut order = 0usize;
|
||||
let mut chosen = None;
|
||||
tree.visit_source_paths(scope, |moves| {
|
||||
let eligible = eligible_target_count(mode, start_turn, moves.len());
|
||||
if eligible == 0 {
|
||||
return ControlFlow::Continue(());
|
||||
}
|
||||
if order == selected_index {
|
||||
let start_order = (start_seed as usize) % eligible;
|
||||
chosen = eligible_target_index(mode, start_turn, moves.len(), start_order).map(
|
||||
|start| RandomPracticePath {
|
||||
path: TrainingPath {
|
||||
moves: moves.to_vec(),
|
||||
},
|
||||
start,
|
||||
},
|
||||
);
|
||||
return ControlFlow::Break(());
|
||||
}
|
||||
order += 1;
|
||||
ControlFlow::Continue(())
|
||||
})?;
|
||||
if chosen.is_some() {
|
||||
cursor.position = cursor.position.saturating_add(1);
|
||||
Ok(chosen)
|
||||
} else {
|
||||
Err("random training path selection is inconsistent".to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects one route without materializing the complete path queue. Ordered
|
||||
/// review stops as soon as its cursor is reached; only wrapping needs a second pass.
|
||||
pub fn next_training_path(
|
||||
&self,
|
||||
tree: &RepertoireTree,
|
||||
repertoire_id: &RepertoireId,
|
||||
scope: &TrainingScope,
|
||||
queue_mode: QueueMode,
|
||||
) -> Result<Option<TrainingPath>, String> {
|
||||
use std::ops::ControlFlow;
|
||||
let scope_key = scope.key();
|
||||
if queue_mode == QueueMode::LeastRecent {
|
||||
let mut best = None;
|
||||
let mut best_rank = None;
|
||||
tree.visit_training_paths(scope, |moves| {
|
||||
let stats = self.path_stats.iter().find(|stats| {
|
||||
&stats.key.repertoire_id == repertoire_id
|
||||
&& stats.key.scope == scope_key
|
||||
&& stats.key.path == moves
|
||||
});
|
||||
let rank = (
|
||||
stats.is_some_and(|stats| stats.completions > 0),
|
||||
stats
|
||||
.and_then(|stats| stats.last_completion)
|
||||
.unwrap_or(i64::MIN),
|
||||
);
|
||||
if best_rank.is_none_or(|old| rank < old) {
|
||||
best_rank = Some(rank);
|
||||
best = Some(TrainingPath {
|
||||
moves: moves.to_vec(),
|
||||
});
|
||||
}
|
||||
// This is the minimum possible rank. Keeping its first occurrence
|
||||
// preserves the stable PGN order used by path_queue's sort.
|
||||
if rank == (false, i64::MIN) {
|
||||
ControlFlow::Break(())
|
||||
} else {
|
||||
ControlFlow::Continue(())
|
||||
}
|
||||
})?;
|
||||
return Ok(best);
|
||||
}
|
||||
let cursor = self
|
||||
.path_review_cursors
|
||||
.iter()
|
||||
.find(|cursor| &cursor.repertoire_id == repertoire_id && cursor.scope == scope_key)
|
||||
.map_or(0, |cursor| cursor.next);
|
||||
let mut count = 0usize;
|
||||
let mut selected = None;
|
||||
tree.visit_training_paths(scope, |moves| {
|
||||
if count == cursor {
|
||||
selected = Some(TrainingPath {
|
||||
moves: moves.to_vec(),
|
||||
});
|
||||
return ControlFlow::Break(());
|
||||
}
|
||||
count += 1;
|
||||
ControlFlow::Continue(())
|
||||
})?;
|
||||
if selected.is_some() || count == 0 {
|
||||
return Ok(selected);
|
||||
}
|
||||
let offset = cursor % count;
|
||||
let mut index = 0;
|
||||
tree.visit_training_paths(scope, |moves| {
|
||||
if index == offset {
|
||||
selected = Some(TrainingPath {
|
||||
moves: moves.to_vec(),
|
||||
});
|
||||
return ControlFlow::Break(());
|
||||
}
|
||||
index += 1;
|
||||
ControlFlow::Continue(())
|
||||
})?;
|
||||
Ok(selected)
|
||||
}
|
||||
|
||||
pub(crate) fn record_wrong(
|
||||
&mut self,
|
||||
key: MoveKey,
|
||||
now: i64,
|
||||
actual_uci: &str,
|
||||
schedule: bool,
|
||||
) {
|
||||
self.entry(key).wrong(now, actual_uci, schedule);
|
||||
}
|
||||
|
||||
pub(crate) fn record_correct(
|
||||
&mut self,
|
||||
key: MoveKey,
|
||||
now: i64,
|
||||
actual_uci: &str,
|
||||
hinted: bool,
|
||||
schedule: bool,
|
||||
) {
|
||||
self.entry(key).correct(now, actual_uci, hinted, schedule);
|
||||
}
|
||||
|
||||
pub(crate) fn record_hint(&mut self, key: MoveKey, now: i64) {
|
||||
self.entry(key).hint(now);
|
||||
}
|
||||
|
||||
pub(crate) fn target_completed(
|
||||
&mut self,
|
||||
repertoire_id: &RepertoireId,
|
||||
mode: TrainingMode,
|
||||
queue_mode: QueueMode,
|
||||
scope: &TrainingScope,
|
||||
) {
|
||||
if queue_mode != QueueMode::ReviewInOrder {
|
||||
return;
|
||||
}
|
||||
let scope = scope.key();
|
||||
let index = match self.review_cursors.iter().position(|cursor| {
|
||||
&cursor.repertoire_id == repertoire_id && cursor.mode == mode && cursor.scope == scope
|
||||
}) {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
self.review_cursors.push(ReviewCursor {
|
||||
repertoire_id: repertoire_id.clone(),
|
||||
mode,
|
||||
scope,
|
||||
next: 0,
|
||||
});
|
||||
self.review_cursors.len() - 1
|
||||
}
|
||||
};
|
||||
self.review_cursors[index].next = self.review_cursors[index].next.saturating_add(1);
|
||||
}
|
||||
|
||||
pub(crate) fn path_presented(
|
||||
&mut self,
|
||||
repertoire_id: &RepertoireId,
|
||||
scope: &TrainingScope,
|
||||
queue_mode: QueueMode,
|
||||
) {
|
||||
if queue_mode == QueueMode::LeastRecent {
|
||||
return;
|
||||
}
|
||||
let scope = scope.key();
|
||||
let index = match self
|
||||
.path_review_cursors
|
||||
.iter()
|
||||
.position(|cursor| &cursor.repertoire_id == repertoire_id && cursor.scope == scope)
|
||||
{
|
||||
Some(index) => index,
|
||||
None => {
|
||||
self.path_review_cursors.push(PathReviewCursor {
|
||||
repertoire_id: repertoire_id.clone(),
|
||||
scope,
|
||||
next: 0,
|
||||
});
|
||||
self.path_review_cursors.len() - 1
|
||||
}
|
||||
};
|
||||
self.path_review_cursors[index].next =
|
||||
self.path_review_cursors[index].next.saturating_add(1);
|
||||
}
|
||||
|
||||
pub(crate) fn record_run(
|
||||
&mut self,
|
||||
repertoire_id: &RepertoireId,
|
||||
mode: TrainingMode,
|
||||
record: RunRecord,
|
||||
) {
|
||||
let index = match self
|
||||
.runs
|
||||
.iter()
|
||||
.position(|runs| &runs.repertoire_id == repertoire_id && runs.mode == mode)
|
||||
{
|
||||
Some(index) => index,
|
||||
None => {
|
||||
self.runs.push(RunStats {
|
||||
repertoire_id: repertoire_id.clone(),
|
||||
mode,
|
||||
..RunStats::default()
|
||||
});
|
||||
self.runs.len() - 1
|
||||
}
|
||||
};
|
||||
let runs = &mut self.runs[index];
|
||||
runs.completions = runs.completions.saturating_add(1);
|
||||
runs.last = Some(record.at);
|
||||
runs.recent.push(record);
|
||||
if runs.recent.len() > RECENT {
|
||||
runs.recent.remove(0);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record_path_run(&mut self, key: PathKey, record: RunRecord) {
|
||||
let index = match self.path_stats.iter().position(|stats| stats.key == key) {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
self.path_stats.push(PathStats {
|
||||
key,
|
||||
completions: 0,
|
||||
mistakes: 0,
|
||||
hints: 0,
|
||||
last_seen: None,
|
||||
last_completion: None,
|
||||
recent: Vec::new(),
|
||||
});
|
||||
self.path_stats.len() - 1
|
||||
}
|
||||
};
|
||||
let stats = &mut self.path_stats[index];
|
||||
stats.completions = stats.completions.saturating_add(1);
|
||||
stats.mistakes = stats.mistakes.saturating_add(record.mistakes);
|
||||
stats.hints = stats.hints.saturating_add(record.hints);
|
||||
stats.last_seen = Some(record.at);
|
||||
stats.last_completion = Some(record.at);
|
||||
stats.recent.push(record);
|
||||
if stats.recent.len() > RECENT {
|
||||
stats.recent.remove(0);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn migrate_position_stats(&mut self) {
|
||||
let mut merged: Vec<MoveStats> = Vec::new();
|
||||
for mut entry in self.move_stats.drain(..) {
|
||||
|
|
@ -272,4 +980,91 @@ impl StatsData {
|
|||
self.path_review_cursors
|
||||
.sort_by(|a, b| (&a.repertoire_id, &a.scope).cmp(&(&b.repertoire_id, &b.scope)));
|
||||
}
|
||||
|
||||
fn entry(&mut self, key: MoveKey) -> &mut MoveStats {
|
||||
let index = match self.move_stats.iter().position(|stats| stats.key == key) {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
self.move_stats.push(MoveStats::new(key));
|
||||
self.move_stats.len() - 1
|
||||
}
|
||||
};
|
||||
&mut self.move_stats[index]
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const MIN_RANDOM_CONTINUATION_PLIES: usize = 7;
|
||||
|
||||
fn random_max_start(plies: usize) -> usize {
|
||||
plies.saturating_sub(MIN_RANDOM_CONTINUATION_PLIES)
|
||||
}
|
||||
|
||||
fn eligible_target_count(mode: TrainingMode, start_turn: Color, plies: usize) -> usize {
|
||||
if plies == 0 {
|
||||
return 0;
|
||||
}
|
||||
let max_start = random_max_start(plies);
|
||||
let Some(user_color) = mode.user_color() else {
|
||||
return usize::from(plies > 0) * (max_start + 1);
|
||||
};
|
||||
let first = usize::from(start_turn != user_color);
|
||||
if max_start < first {
|
||||
0
|
||||
} else {
|
||||
(max_start - first) / 2 + 1
|
||||
}
|
||||
}
|
||||
|
||||
fn eligible_target_index(
|
||||
mode: TrainingMode,
|
||||
start_turn: Color,
|
||||
plies: usize,
|
||||
order: usize,
|
||||
) -> Option<usize> {
|
||||
let mut remaining = order;
|
||||
for index in 0..=random_max_start(plies) {
|
||||
let turn = if index % 2 == 0 {
|
||||
start_turn
|
||||
} else {
|
||||
start_turn.other()
|
||||
};
|
||||
if mode.user_color().is_none_or(|color| color == turn) {
|
||||
if remaining == 0 {
|
||||
return Some(index);
|
||||
}
|
||||
remaining -= 1;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn coprime_step(seed: u64, count: usize) -> usize {
|
||||
if count == 1 {
|
||||
return 0;
|
||||
}
|
||||
let mut step = (mix64(seed) % count as u64) as usize;
|
||||
while gcd(step, count) != 1 {
|
||||
step = (step + 1) % count;
|
||||
}
|
||||
step
|
||||
}
|
||||
|
||||
fn gcd(mut left: usize, mut right: usize) -> usize {
|
||||
while right != 0 {
|
||||
let remainder = left % right;
|
||||
left = right;
|
||||
right = remainder;
|
||||
}
|
||||
left
|
||||
}
|
||||
|
||||
fn next_cycle_seed(seed: u64) -> u64 {
|
||||
mix64(seed ^ 0x8ebc_6af0_9c88_c6e3)
|
||||
}
|
||||
|
||||
fn mix64(mut value: u64) -> u64 {
|
||||
value = value.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
value ^ (value >> 31)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,6 +13,12 @@ fn game(pgn: &str) -> Game {
|
|||
chess_core::parse_str(pgn).game
|
||||
}
|
||||
|
||||
fn repertoire(pgn: &str) -> Repertoire {
|
||||
let mut library = Library::default();
|
||||
let id = library.create("Test", &game(pgn)).unwrap();
|
||||
library.repertoire(&id).unwrap().clone()
|
||||
}
|
||||
|
||||
fn play(game: &Game, line: &[&str]) -> Vec<Move> {
|
||||
let mut position = game.start().position().clone();
|
||||
line.iter()
|
||||
|
|
@ -252,6 +258,348 @@ fn library_crud_depth_and_disable_are_persistent_data() {
|
|||
assert!(library.repertoire(&id).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_accepts_every_enabled_branch_and_rejects_outside_disabled_and_depth() {
|
||||
let rep = repertoire("1. e4 (1. d4 d5) e5 (1... c5) 2. Nf3 *");
|
||||
let mut session = TrainingSession::new(
|
||||
&rep,
|
||||
TrainingMode::Both,
|
||||
QueueMode::ReviewInOrder,
|
||||
StatsData::default(),
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(session.play_uci("not-a-move", 0).is_err());
|
||||
assert!(session.play_uci("e2e5", 0).is_err());
|
||||
assert!(session.attempts().is_empty());
|
||||
assert_eq!(session.play_uci("c2c4", 1).unwrap(), TrainingVerdict::Wrong);
|
||||
assert_eq!(session.current_node(), NodeId::ROOT);
|
||||
assert_eq!(session.total_mistakes(), 1);
|
||||
assert_eq!(session.play_uci("d2d4", 2).unwrap(), TrainingVerdict::Right);
|
||||
assert_eq!(
|
||||
session.play_uci("d7d5", 3).unwrap(),
|
||||
TrainingVerdict::Finished
|
||||
);
|
||||
let completions = session
|
||||
.stats()
|
||||
.runs(&rep.id, TrainingMode::Both)
|
||||
.unwrap()
|
||||
.completions;
|
||||
assert_eq!(completions, 1);
|
||||
assert_eq!(session.play_uci("d2d4", 4).unwrap(), TrainingVerdict::Done);
|
||||
assert_eq!(
|
||||
session
|
||||
.stats()
|
||||
.runs(&rep.id, TrainingMode::Both)
|
||||
.unwrap()
|
||||
.completions,
|
||||
1
|
||||
);
|
||||
|
||||
session.restart(10).unwrap();
|
||||
assert_eq!(
|
||||
session.play_uci("e2e4", 10).unwrap(),
|
||||
TrainingVerdict::Right
|
||||
);
|
||||
assert_eq!(
|
||||
session.play_uci("c7c5", 11).unwrap(),
|
||||
TrainingVerdict::Finished
|
||||
);
|
||||
|
||||
let mut disabled = rep.clone();
|
||||
disabled
|
||||
.set_prefix_disabled(&["e2e4".into(), "e7e5".into()], true)
|
||||
.unwrap();
|
||||
let mut session = TrainingSession::new(
|
||||
&disabled,
|
||||
TrainingMode::Both,
|
||||
QueueMode::ReviewInOrder,
|
||||
StatsData::default(),
|
||||
20,
|
||||
)
|
||||
.unwrap();
|
||||
session.play_uci("e2e4", 20).unwrap();
|
||||
assert_eq!(
|
||||
session.play_uci("e7e5", 21).unwrap(),
|
||||
TrainingVerdict::Wrong
|
||||
);
|
||||
assert_eq!(
|
||||
session.play_uci("c7c5", 22).unwrap(),
|
||||
TrainingVerdict::Finished
|
||||
);
|
||||
|
||||
let mut shallow = rep.clone();
|
||||
shallow.set_max_plies(1);
|
||||
let mut session = TrainingSession::new(
|
||||
&shallow,
|
||||
TrainingMode::Both,
|
||||
QueueMode::ReviewInOrder,
|
||||
StatsData::default(),
|
||||
30,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
session.play_uci("e2e4", 30).unwrap(),
|
||||
TrainingVerdict::Finished
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_hint_after_three_errors_and_completion_are_recorded_once() {
|
||||
let rep = repertoire("1. e4 e5 *");
|
||||
let mut session = TrainingSession::new(
|
||||
&rep,
|
||||
TrainingMode::Both,
|
||||
QueueMode::SpacedRepetition,
|
||||
StatsData::default(),
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
for now in 1..=3 {
|
||||
assert_eq!(
|
||||
session.play_uci("d2d4", now).unwrap(),
|
||||
TrainingVerdict::Wrong
|
||||
);
|
||||
assert_eq!(session.current_node(), NodeId::ROOT);
|
||||
}
|
||||
assert!(session.may_hint());
|
||||
assert_eq!(session.hint(4).unwrap().uci, "e2e4");
|
||||
assert!(session.hinted());
|
||||
assert_eq!(session.play_uci("e2e4", 5).unwrap(), TrainingVerdict::Right);
|
||||
assert_eq!(
|
||||
session.play_uci("e7e5", 6).unwrap(),
|
||||
TrainingVerdict::Finished
|
||||
);
|
||||
assert_eq!(session.play_uci("e7e5", 7).unwrap(), TrainingVerdict::Done);
|
||||
let stats = &session.stats().move_stats;
|
||||
let e4 = stats
|
||||
.iter()
|
||||
.find(|entry| entry.key.position_fen4 == fen4(Game::new().start().position()))
|
||||
.unwrap();
|
||||
assert_eq!((e4.attempts, e4.correct, e4.wrong, e4.hints), (4, 1, 3, 1));
|
||||
assert_eq!(e4.streak, 0);
|
||||
assert_eq!(e4.recent.len(), 4);
|
||||
assert_eq!(e4.recent[0].actual_uci, "d2d4");
|
||||
let runs = session.stats().runs(&rep.id, TrainingMode::Both).unwrap();
|
||||
assert_eq!(runs.completions, 1);
|
||||
assert_eq!(runs.recent[0].mistakes, 3);
|
||||
assert!(runs.recent[0].hinted);
|
||||
assert_eq!(session.errors().count(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_continues_through_a_canonical_transposition_and_shares_stats() {
|
||||
let mut library = Library::default();
|
||||
let id = library.create_empty("Transpositions").unwrap();
|
||||
library
|
||||
.add_game(&id, &game("1. d4 d5 2. Nf3 Nf6 3. g3 *"))
|
||||
.unwrap();
|
||||
library
|
||||
.add_game(&id, &game("1. Nf3 d5 2. d4 Nf6 *"))
|
||||
.unwrap();
|
||||
let rep = library.repertoire(&id).unwrap().clone();
|
||||
let mut first = TrainingSession::new(
|
||||
&rep,
|
||||
TrainingMode::Both,
|
||||
QueueMode::ReviewInOrder,
|
||||
StatsData::default(),
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
for (now, mv) in ["d2d4", "d7d5", "g1f3", "g8f6", "g2g3"]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
first.play_uci(mv, now as i64).unwrap();
|
||||
}
|
||||
let mut second = TrainingSession::new(
|
||||
&rep,
|
||||
TrainingMode::Both,
|
||||
QueueMode::ReviewInOrder,
|
||||
first.into_stats(),
|
||||
10,
|
||||
)
|
||||
.unwrap();
|
||||
second.play_uci("g1f3", 10).unwrap();
|
||||
second.play_uci("d7d5", 11).unwrap();
|
||||
second.play_uci("d2d4", 12).unwrap();
|
||||
second.play_uci("g8f6", 13).unwrap();
|
||||
assert!(second.candidates().iter().any(|c| c.uci == "g2g3"));
|
||||
assert_eq!(
|
||||
second.play_uci("g2g3", 14).unwrap(),
|
||||
TrainingVerdict::Finished
|
||||
);
|
||||
let shared = second
|
||||
.stats()
|
||||
.move_stats
|
||||
.iter()
|
||||
.filter(|entry| {
|
||||
entry
|
||||
.recent
|
||||
.iter()
|
||||
.any(|attempt| attempt.actual_uci == "g2g3")
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(shared.len(), 1);
|
||||
assert_eq!(shared[0].attempts, 2);
|
||||
assert_eq!(shared[0].correct, 2);
|
||||
}
|
||||
|
||||
struct SecondChooser;
|
||||
|
||||
impl MoveChooser for SecondChooser {
|
||||
fn choose(&mut self, candidates: &[Candidate]) -> Option<usize> {
|
||||
(candidates.len() > 1).then_some(1).or(Some(0))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_side_alternative_and_injectable_chooser_do_not_count_auto_moves() {
|
||||
let rep = repertoire("1. e4 (1. d4 d5) e5 (1... c5) 2. Nf3 *");
|
||||
let mut session = TrainingSession::with_chooser(
|
||||
&rep,
|
||||
TrainingMode::White,
|
||||
QueueMode::ReviewInOrder,
|
||||
StatsData::default(),
|
||||
0,
|
||||
Box::new(SecondChooser),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(session.target().unwrap().expected_uci, "e2e4");
|
||||
assert_eq!(session.play_uci("e2e4", 2).unwrap(), TrainingVerdict::Right);
|
||||
assert_eq!(session.path()[0].uci, "e2e4");
|
||||
assert!(!session.path()[0].automatic);
|
||||
assert_eq!(session.path()[1].uci, "c7c5");
|
||||
assert!(session.path()[1].automatic);
|
||||
assert_eq!(session.attempts().len(), 1);
|
||||
assert_eq!(session.stats().move_stats.len(), 1);
|
||||
|
||||
let black = repertoire("1. e4 e5 2. Nf3 *");
|
||||
let mut black_session = TrainingSession::new(
|
||||
&black,
|
||||
TrainingMode::Black,
|
||||
QueueMode::ReviewInOrder,
|
||||
StatsData::default(),
|
||||
10,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(black_session.target().unwrap().expected_uci, "e7e5");
|
||||
assert_eq!(black_session.path()[0].uci, "e2e4");
|
||||
assert!(black_session.path()[0].automatic);
|
||||
assert_eq!(
|
||||
black_session.play_uci("e7e5", 11).unwrap(),
|
||||
TrainingVerdict::Finished
|
||||
);
|
||||
assert_eq!(black_session.attempts().len(), 1);
|
||||
assert!(
|
||||
black_session
|
||||
.path()
|
||||
.iter()
|
||||
.any(|mv| mv.uci == "g1f3" && mv.automatic)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn srs_dates_unseen_review_order_and_least_recent_work() {
|
||||
let rep = repertoire("1. e4 *");
|
||||
let mut first = TrainingSession::new_srs(
|
||||
&rep,
|
||||
TrainingMode::White,
|
||||
StatsData::default(),
|
||||
0,
|
||||
SrsPolicy::Introduce,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
first.play_uci("e2e4", 1_000).unwrap(),
|
||||
TrainingVerdict::Finished
|
||||
);
|
||||
let stats = &first.stats().move_stats[0];
|
||||
assert_eq!(stats.due, Some(1_000 + INITIAL_INTERVAL_SECONDS));
|
||||
assert_eq!(stats.streak, 1);
|
||||
|
||||
let second_now = 1_000 + INITIAL_INTERVAL_SECONDS;
|
||||
let mut second = TrainingSession::new(
|
||||
&rep,
|
||||
TrainingMode::White,
|
||||
QueueMode::SpacedRepetition,
|
||||
first.into_stats(),
|
||||
second_now,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
second.play_uci("e2e4", second_now).unwrap(),
|
||||
TrainingVerdict::Finished
|
||||
);
|
||||
let stats = &second.stats().move_stats[0];
|
||||
assert_eq!(stats.due, Some(1_000 + 3 * INITIAL_INTERVAL_SECONDS));
|
||||
assert_eq!(stats.streak, 2);
|
||||
assert!(
|
||||
second
|
||||
.stats()
|
||||
.queue(
|
||||
&RepertoireTree::new(&rep),
|
||||
&rep.id,
|
||||
TrainingMode::White,
|
||||
QueueMode::SpacedRepetition,
|
||||
3_000,
|
||||
)
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
let wrong_rep = repertoire("1. e4 *");
|
||||
let mut wrong = TrainingSession::new_srs(
|
||||
&wrong_rep,
|
||||
TrainingMode::White,
|
||||
StatsData::default(),
|
||||
0,
|
||||
SrsPolicy::Introduce,
|
||||
)
|
||||
.unwrap();
|
||||
wrong.play_uci("d2d4", 100).unwrap();
|
||||
let key = wrong
|
||||
.target()
|
||||
.map(|target| MoveKey {
|
||||
repertoire_id: wrong_rep.id.clone(),
|
||||
mode: TrainingMode::White,
|
||||
position_fen4: target.position_fen4.clone(),
|
||||
expected_uci: target.expected_uci.clone(),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(wrong.stats().get(&key).unwrap().due, Some(700));
|
||||
wrong.play_uci("e2e4", 101).unwrap();
|
||||
assert_eq!(wrong.stats().get(&key).unwrap().due, Some(701));
|
||||
assert_eq!(wrong.stats().get(&key).unwrap().streak, 0);
|
||||
|
||||
let branches = repertoire("1. e4 (1. d4 d5) e5 2. Nf3 *");
|
||||
let mut training = TrainingSession::new(
|
||||
&branches,
|
||||
TrainingMode::White,
|
||||
QueueMode::ReviewInOrder,
|
||||
StatsData::default(),
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
training.play_uci("e2e4", 10).unwrap();
|
||||
let queue = training.stats().queue(
|
||||
&RepertoireTree::new(&branches),
|
||||
&branches.id,
|
||||
TrainingMode::White,
|
||||
QueueMode::LeastRecent,
|
||||
20,
|
||||
);
|
||||
assert_eq!(queue[0].expected_uci, "d2d4");
|
||||
assert_eq!(queue.last().unwrap().expected_uci, "e2e4");
|
||||
let review = training.stats().queue(
|
||||
&RepertoireTree::new(&branches),
|
||||
&branches.id,
|
||||
TrainingMode::White,
|
||||
QueueMode::ReviewInOrder,
|
||||
20,
|
||||
);
|
||||
assert_eq!(review[0].expected_uci, "d2d4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefix_ignores_unparsed_tail_after_the_selected_node() {
|
||||
let source = game("1. e4 e4 2. d4 *");
|
||||
|
|
@ -269,6 +617,146 @@ fn prefix_ignores_unparsed_tail_after_the_selected_node() {
|
|||
assert_eq!(library.repertoire(&id).unwrap().pgn, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn review_queues_record_attempts_without_changing_srs_due() {
|
||||
let rep = repertoire("1. e4 *");
|
||||
let mut srs = TrainingSession::new_srs(
|
||||
&rep,
|
||||
TrainingMode::White,
|
||||
StatsData::default(),
|
||||
0,
|
||||
SrsPolicy::Introduce,
|
||||
)
|
||||
.unwrap();
|
||||
srs.play_uci("e2e4", 100).unwrap();
|
||||
let original_due = srs.stats().move_stats[0].due;
|
||||
assert_eq!(original_due, Some(100 + INITIAL_INTERVAL_SECONDS));
|
||||
|
||||
for queue_mode in [QueueMode::ReviewInOrder, QueueMode::LeastRecent] {
|
||||
let mut review = TrainingSession::new(
|
||||
&rep,
|
||||
TrainingMode::White,
|
||||
queue_mode,
|
||||
srs.stats().clone(),
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
review.play_uci("e2e4", 200).unwrap();
|
||||
let stats = &review.stats().move_stats[0];
|
||||
assert_eq!(stats.attempts, 2);
|
||||
assert_eq!(stats.last_seen, Some(200));
|
||||
assert_eq!(stats.due, original_due);
|
||||
|
||||
review.restart(201).unwrap();
|
||||
review.play_uci("d2d4", 201).unwrap();
|
||||
assert_eq!(review.stats().move_stats[0].due, original_due);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn srs_retry_is_kept_until_the_next_clean_success() {
|
||||
let rep = repertoire("1. e4 *");
|
||||
let mut session = TrainingSession::new_srs(
|
||||
&rep,
|
||||
TrainingMode::White,
|
||||
StatsData::default(),
|
||||
0,
|
||||
SrsPolicy::Introduce,
|
||||
)
|
||||
.unwrap();
|
||||
session.play_uci("d2d4", 100).unwrap();
|
||||
session.play_uci("e2e4", 101).unwrap();
|
||||
let stats = &session.stats().move_stats[0];
|
||||
assert_eq!(stats.due, Some(101 + MISTAKE_INTERVAL_SECONDS));
|
||||
assert_eq!(stats.streak, 0);
|
||||
|
||||
session.restart_with_policy(701, SrsPolicy::Due).unwrap();
|
||||
session.play_uci("e2e4", 701).unwrap();
|
||||
let stats = &session.stats().move_stats[0];
|
||||
assert_eq!(stats.due, Some(701 + INITIAL_INTERVAL_SECONDS));
|
||||
assert_eq!(stats.streak, 1);
|
||||
|
||||
session.restart(701 + INITIAL_INTERVAL_SECONDS).unwrap();
|
||||
session
|
||||
.play_uci("e2e4", 701 + INITIAL_INTERVAL_SECONDS)
|
||||
.unwrap();
|
||||
let stats = &session.stats().move_stats[0];
|
||||
assert_eq!(stats.due, Some(701 + 3 * INITIAL_INTERVAL_SECONDS));
|
||||
assert_eq!(stats.streak, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_attempts_never_create_srs_due() {
|
||||
let rep = repertoire("1. e4 *");
|
||||
let mut session = TrainingSession::new(
|
||||
&rep,
|
||||
TrainingMode::Both,
|
||||
QueueMode::ReviewInOrder,
|
||||
StatsData::default(),
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
session.play_uci("d2d4", 100).unwrap();
|
||||
session.play_uci("e2e4", 101).unwrap();
|
||||
assert!(
|
||||
session
|
||||
.stats()
|
||||
.move_stats
|
||||
.iter()
|
||||
.all(|stats| stats.due.is_none())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stats_are_isolated_by_mode_and_repertoire() {
|
||||
let first_rep = repertoire("1. e4 *");
|
||||
let second_rep = repertoire("1. e4 *");
|
||||
let mut white = TrainingSession::new(
|
||||
&first_rep,
|
||||
TrainingMode::White,
|
||||
QueueMode::ReviewInOrder,
|
||||
StatsData::default(),
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
white.play_uci("e2e4", 1).unwrap();
|
||||
let mut both = TrainingSession::new(
|
||||
&first_rep,
|
||||
TrainingMode::Both,
|
||||
QueueMode::ReviewInOrder,
|
||||
white.into_stats(),
|
||||
2,
|
||||
)
|
||||
.unwrap();
|
||||
both.play_uci("e2e4", 2).unwrap();
|
||||
let mut other = TrainingSession::new(
|
||||
&second_rep,
|
||||
TrainingMode::Both,
|
||||
QueueMode::ReviewInOrder,
|
||||
both.into_stats(),
|
||||
3,
|
||||
)
|
||||
.unwrap();
|
||||
other.play_uci("e2e4", 3).unwrap();
|
||||
assert_eq!(other.stats().move_stats.len(), 3);
|
||||
assert!(
|
||||
other
|
||||
.stats()
|
||||
.move_stats
|
||||
.iter()
|
||||
.any(|entry| entry.key.mode == TrainingMode::White)
|
||||
);
|
||||
assert_eq!(
|
||||
other
|
||||
.stats()
|
||||
.move_stats
|
||||
.iter()
|
||||
.filter(|entry| entry.key.mode == TrainingMode::Both)
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn library_store_roundtrip_errors_and_conflicts_are_visible() {
|
||||
let dir = temp_dir("library-store");
|
||||
|
|
@ -378,7 +866,39 @@ fn stats_store_write_failure_does_not_replace_legacy_or_report_success() {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn adding_and_deleting_never_touches_the_source_file() {
|
||||
fn session_stats_can_be_saved_after_every_run() {
|
||||
let dir = temp_dir("session-save");
|
||||
let store = StatsStore::new(dir.join("stats.json"));
|
||||
let rep = repertoire("1. e4 *");
|
||||
let mut session = TrainingSession::new(
|
||||
&rep,
|
||||
TrainingMode::White,
|
||||
QueueMode::ReviewInOrder,
|
||||
store.load().unwrap(),
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
session.play_uci("e2e4", 10).unwrap();
|
||||
store.save(session.stats_mut()).unwrap();
|
||||
assert_eq!(session.stats().revision, 1);
|
||||
session.restart(20).unwrap();
|
||||
session.play_uci("e2e4", 20).unwrap();
|
||||
store.save(session.stats_mut()).unwrap();
|
||||
assert_eq!(session.stats().revision, 2);
|
||||
assert_eq!(
|
||||
store
|
||||
.load()
|
||||
.unwrap()
|
||||
.runs(&rep.id, TrainingMode::White)
|
||||
.unwrap()
|
||||
.completions,
|
||||
2
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adding_training_and_deleting_never_touches_the_source_file() {
|
||||
let dir = temp_dir("source-file");
|
||||
let source_path = dir.join("legacy.pgn");
|
||||
let bytes = b"[Event \"Legacy\"]\n\n1. e4 c5 2. Nf3 d6 *\n\xff";
|
||||
|
|
@ -388,21 +908,19 @@ fn adding_and_deleting_never_touches_the_source_file() {
|
|||
let id = library.create_empty("Snapshot").unwrap();
|
||||
let at = source.mainline()[3];
|
||||
library.add_prefix(&id, &source, at).unwrap();
|
||||
let rep = library.repertoire(&id).unwrap().clone();
|
||||
let mut session = TrainingSession::new(
|
||||
&rep,
|
||||
TrainingMode::Both,
|
||||
QueueMode::ReviewInOrder,
|
||||
StatsData::default(),
|
||||
0,
|
||||
)
|
||||
.unwrap();
|
||||
for (now, mv) in ["e2e4", "c7c5", "g1f3", "d7d6"].into_iter().enumerate() {
|
||||
session.play_uci(mv, now as i64).unwrap();
|
||||
}
|
||||
library.delete(&id).unwrap();
|
||||
assert_eq!(std::fs::read(&source_path).unwrap(), bytes);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v2_stats_without_the_random_cursor_field_still_read_and_save() {
|
||||
let mut old = serde_json::to_value(StatsData::default()).unwrap();
|
||||
assert!(
|
||||
old.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("random_practice_cursors")
|
||||
.is_some()
|
||||
);
|
||||
let stats: StatsData = serde_json::from_value(old).unwrap();
|
||||
let saved = serde_json::to_value(&stats).unwrap();
|
||||
assert!(saved["random_practice_cursors"].is_array());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use chess_core::shakmaty::fen::Fen;
|
||||
use chess_core::shakmaty::{CastlingMode, Chess, EnPassantMode, Position};
|
||||
use chess_core::shakmaty::{CastlingMode, Chess, Color, EnPassantMode, Move, Position};
|
||||
use chess_core::{Game, MoveKind, NodeId};
|
||||
|
||||
use super::model::Repertoire;
|
||||
|
|
@ -20,7 +20,25 @@ pub fn fen4(position: &Chess) -> String {
|
|||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Candidate {
|
||||
pub mv: Move,
|
||||
pub uci: String,
|
||||
pub san: String,
|
||||
/// The selected PGN path. Other paths to the same move remain in the tree.
|
||||
pub node: NodeId,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct TrainingTarget {
|
||||
pub position_fen4: String,
|
||||
pub expected_uci: String,
|
||||
/// One deterministic PGN path used to reach the target as context.
|
||||
pub path: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct TrainingPath {
|
||||
/// Actual moves from the beginning of the scope through its boundary, inclusive.
|
||||
pub moves: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
|
|
@ -70,6 +88,10 @@ impl RepertoireTree {
|
|||
}
|
||||
}
|
||||
|
||||
pub(crate) fn max_plies(&self) -> u32 {
|
||||
self.max_plies
|
||||
}
|
||||
|
||||
pub fn game(&self) -> &Game {
|
||||
&self.game
|
||||
}
|
||||
|
|
@ -115,6 +137,21 @@ impl RepertoireTree {
|
|||
self.candidates_impl(at, None)
|
||||
}
|
||||
|
||||
pub fn scoped_candidates(&self, at: NodeId, scope: &TrainingScope) -> Vec<Candidate> {
|
||||
self.candidates_impl(at, Some(scope))
|
||||
}
|
||||
|
||||
pub fn scoped_candidate(
|
||||
&self,
|
||||
at: NodeId,
|
||||
uci: &str,
|
||||
scope: &TrainingScope,
|
||||
) -> Option<Candidate> {
|
||||
self.scoped_candidates(at, scope)
|
||||
.into_iter()
|
||||
.find(|candidate| candidate.uci == uci)
|
||||
}
|
||||
|
||||
fn candidates_impl(&self, at: NodeId, scope: Option<&TrainingScope>) -> Vec<Candidate> {
|
||||
if !self.is_trainable_path(at)
|
||||
|| self
|
||||
|
|
@ -156,7 +193,12 @@ impl RepertoireTree {
|
|||
}
|
||||
let uci = mv.to_uci(CastlingMode::Standard).to_string();
|
||||
if seen.insert(uci.clone()) {
|
||||
out.push(Candidate { uci });
|
||||
out.push(Candidate {
|
||||
mv,
|
||||
uci,
|
||||
san: game_move.san.clone(),
|
||||
node: *child,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -169,6 +211,48 @@ impl RepertoireTree {
|
|||
.find(|candidate| candidate.uci == uci)
|
||||
}
|
||||
|
||||
/// All one-side targets in deterministic PGN order, deduplicated by FEN4/UCI.
|
||||
pub fn targets(&self, side: Color) -> Vec<TrainingTarget> {
|
||||
self.targets_impl(side, None)
|
||||
}
|
||||
|
||||
pub fn scoped_targets(&self, side: Color, scope: &TrainingScope) -> Vec<TrainingTarget> {
|
||||
self.targets_impl(side, Some(scope))
|
||||
}
|
||||
|
||||
fn targets_impl(&self, side: Color, scope: Option<&TrainingScope>) -> Vec<TrainingTarget> {
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut out = Vec::new();
|
||||
for node in self.game.attached_nodes() {
|
||||
if !self.scope_allows_parent(node, scope) {
|
||||
continue;
|
||||
}
|
||||
if self.game.position(node).is_none_or(|p| p.turn() != side) {
|
||||
continue;
|
||||
}
|
||||
let Some(path) = self.path(node).map(<[String]>::to_vec) else {
|
||||
continue;
|
||||
};
|
||||
let Some(position_fen4) = self.position_key(node).map(str::to_owned) else {
|
||||
continue;
|
||||
};
|
||||
let candidates = match scope {
|
||||
Some(scope) => self.scoped_candidates(node, scope),
|
||||
None => self.candidates(node),
|
||||
};
|
||||
for candidate in candidates {
|
||||
if seen.insert((position_fen4.clone(), candidate.uci.clone())) {
|
||||
out.push(TrainingTarget {
|
||||
position_fen4: position_fen4.clone(),
|
||||
expected_uci: candidate.uci,
|
||||
path: path.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Follows a normal UCI path on the actual PGN tree. No transposition jump is made
|
||||
/// while replaying context, so the selected target path remains exact.
|
||||
pub fn node_at_path(&self, path: &[String]) -> Option<NodeId> {
|
||||
|
|
@ -211,6 +295,35 @@ impl RepertoireTree {
|
|||
Ok(anchor)
|
||||
}
|
||||
|
||||
/// Generates actual scope-to-boundary routes in PGN depth-first order. Repeated FEN4
|
||||
/// positions are included as the final move and never expanded again.
|
||||
pub fn training_paths(&self, scope: &TrainingScope) -> Result<Vec<TrainingPath>, String> {
|
||||
let mut paths = Vec::new();
|
||||
self.visit_training_paths(scope, |moves| {
|
||||
paths.push(TrainingPath {
|
||||
moves: moves.to_vec(),
|
||||
});
|
||||
std::ops::ControlFlow::Continue(())
|
||||
})?;
|
||||
Ok(paths)
|
||||
}
|
||||
|
||||
/// Streams routes in the same order as `training_paths`, retaining only the active
|
||||
/// route and its position history. A visitor may stop without expanding the rest.
|
||||
pub fn visit_training_paths(
|
||||
&self,
|
||||
scope: &TrainingScope,
|
||||
mut visit: impl FnMut(&[String]) -> std::ops::ControlFlow<()>,
|
||||
) -> Result<(), String> {
|
||||
let anchor = self.scope_anchor(scope)?;
|
||||
let mut positions = BTreeSet::new();
|
||||
if let Some(key) = self.position_key(anchor) {
|
||||
positions.insert(key.to_owned());
|
||||
}
|
||||
let _ = self.visit_paths(anchor, scope, &mut Vec::new(), &mut positions, &mut visit);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Streams the routes explicitly present in PGN, without importing continuations
|
||||
/// from other paths that reach the same position.
|
||||
pub fn visit_source_paths(
|
||||
|
|
@ -257,6 +370,63 @@ impl RepertoireTree {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn training_path_count(&self, scope: &TrainingScope) -> Result<usize, String> {
|
||||
let mut count = Some(0usize);
|
||||
self.visit_training_paths(scope, |_| {
|
||||
count = count.and_then(|count| count.checked_add(1));
|
||||
if count.is_none() {
|
||||
std::ops::ControlFlow::Break(())
|
||||
} else {
|
||||
std::ops::ControlFlow::Continue(())
|
||||
}
|
||||
})?;
|
||||
count.ok_or_else(|| "training path count exceeds the platform limit".to_owned())
|
||||
}
|
||||
|
||||
fn visit_paths(
|
||||
&self,
|
||||
at: NodeId,
|
||||
scope: &TrainingScope,
|
||||
current: &mut Vec<String>,
|
||||
positions: &mut BTreeSet<String>,
|
||||
visit: &mut impl FnMut(&[String]) -> std::ops::ControlFlow<()>,
|
||||
) -> std::ops::ControlFlow<()> {
|
||||
let candidates = if scope.parent_prefix().len() + current.len() >= self.max_plies as usize {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.scoped_candidates(at, scope)
|
||||
};
|
||||
if candidates.is_empty() {
|
||||
return if current.is_empty() {
|
||||
std::ops::ControlFlow::Continue(())
|
||||
} else {
|
||||
visit(current)
|
||||
};
|
||||
}
|
||||
// Each position has distinct UCI candidates, so each complete UCI route is
|
||||
// unique even when its continuation crosses a transposition.
|
||||
for candidate in candidates {
|
||||
current.push(candidate.uci.clone());
|
||||
let key = self.position_key(candidate.node);
|
||||
let repeated = key.is_some_and(|key| positions.contains(key));
|
||||
let result = if repeated {
|
||||
visit(current)
|
||||
} else {
|
||||
if let Some(key) = key {
|
||||
positions.insert(key.to_owned());
|
||||
}
|
||||
let result = self.visit_paths(candidate.node, scope, current, positions, visit);
|
||||
if let Some(key) = key {
|
||||
positions.remove(key);
|
||||
}
|
||||
result
|
||||
};
|
||||
current.pop();
|
||||
result?;
|
||||
}
|
||||
std::ops::ControlFlow::Continue(())
|
||||
}
|
||||
|
||||
fn scope_allows_parent(&self, at: NodeId, scope: Option<&TrainingScope>) -> bool {
|
||||
let Some(scope) = scope else {
|
||||
return true;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Архитектура ChessPenguin
|
||||
|
||||
Статус: описание реализованной системы для выпуска **2.5.2**, обновлено 2026-11-30. Тренажёр дебютов включён в настольное приложение с пометкой α.
|
||||
Статус: описание реализованной системы для выпуска **2.3.0**, обновлено 2026-11-06. Тренажёр дебютов включён в настольное приложение с пометкой α.
|
||||
Первоначальный документ с этим именем — архитектурное предложение этапа исследования
|
||||
(2026-10-17) — сохранён в `docs/research/architecture-proposal-2026-10-17.md`.
|
||||
|
||||
|
|
@ -106,10 +106,11 @@ desktop (egui, apps/desktop) │ web (wasm, apps/web) │ android (Kotlin + mobi
|
|||
- Реализовано и выпущено: библиотека PGN/ChessBase, нотация с редактированием,
|
||||
анализ и обзор партии, подготовка к сопернику, игра (Maia/Rodent), онлайн-партии,
|
||||
свои базы, перевод комментариев, автоматическое обновление. История — `CHANGELOG.md`.
|
||||
- Desktop-тренажёр дебютов (α): с 2.4.0 — упрощённый UI (`repertoire_ui.rs`, `opening_session.rs`,
|
||||
`opening_lines.rs`, `opening_layout.rs`) поверх ядра `crates/trainer/src/repertoire`: общая SRS-модель
|
||||
по `(профиль, FEN4, UCI)`, дневное занятие (к повторению + до 10 новых), «Повторить всё подряд»,
|
||||
тренировка ветки; режимы, параметры контекста и дашборд из UI удалены, формат хранения не менялся.
|
||||
- Desktop-тренажёр дебютов выпущен с пометкой α: библиотека PGN-репертуаров,
|
||||
общая SRS-модель, режимы обучения, контекст, редактор и аналитика. В 2.3.0
|
||||
изучаются все включённые варианты; PGN-пометки привязаны к показанному узлу.
|
||||
Повторный контекст сохраняется одним атомарным пакетом, позиции текущего пути
|
||||
кэшируются в памяти сессии без изменения формата хранения.
|
||||
Android продолжает использовать прежний линейный
|
||||
тренер и совместимые legacy-данные; web-версия этот экран не получает.
|
||||
- Очередь и идеи — `docs/dev/tasks.md`; перенос на другую машину — `docs/dev/handoff.md`.
|
||||
|
|
|
|||
|
|
@ -71,7 +71,6 @@
|
|||
- Enter на ходе открывает, Enter — готово, Esc — отмена (черновик выбрасывается); переход к другому ходу записывает; Shift+Enter — абзац;
|
||||
- значки: мышью в меню хода и в редакторе (обе группы — ход и позиция), дополнительно Ctrl+1…6 для `! ? !! ?? !? ?!`;
|
||||
- стрелки и цветные поля правой кнопкой на доске — в первой версии (цвет: без модификатора зелёный, Shift красный, Alt синий, Shift+Alt жёлтый; повтор снимает);
|
||||
- 2026-11-26: в игре и тренировках можно держать несколько временных стрелок и кругов до смены позиции; они не записываются в PGN. В обычном анализе фигуры остаются комментариями `[%cal]`/`[%csl]` и сохраняются только вместе с партией обычным действием сохранения. Модификаторы цвета и отказ от рисования пальцем на Android не меняются;
|
||||
- книжные комментарии: нетронутые байты не меняются, команды `[%cal]`, `[%clk]`, `[%eval]` сохраняются.
|
||||
|
||||
## Игра с компьютером (Maia), 2026-10-25
|
||||
|
|
@ -510,66 +509,3 @@ PGN для точного выбора пометок, минимальная г
|
|||
Публикация через main и штатный фильтр GitHub; существующие теги не меняются.
|
||||
Незавершённых изменений продуктовых правил NAG и авторских стрелок в выпуске нет:
|
||||
все включённые ветки изучаются, рисунки PGN сами не меняют тип зачёта.
|
||||
|
||||
## Тренировка дебюта v2 (2026-11-26)
|
||||
|
||||
Владелец поручил оркестратору самостоятельно переработать раздел: «проще, понятнее, функционально», остальные разделы не трогать. Принято (концепция `docs/design/opening-trainer-concept-2026-11-26.md`, спецификация `docs/design/opening-trainer-v2-spec.md`):
|
||||
|
||||
- Ядро сохраняется: LearningItem `(профиль, FEN4, UCI)`, SRS, несколько собственных ответов (2.3.0), формат файлов и типы Settings без изменений.
|
||||
- Занятие = все ходы к повторению + до 10 новых, «Ещё 10 новых». Подача линией от начала; спрашиваются только ходы к повторению и новые; новый ход сначала показывается стрелкой; ошибка показывает правильный ход и возвращается в том же занятии. Только что показанные ходы по расписанию возвращаются через минуту, поэтому следующее занятие в тот же день включает их.
|
||||
- Прогресс — в ходах: «Выучено X из Y · учится Z». «Выучено» по ядру — три верных самостоятельных ответа подряд, обычно за несколько дней; поэтому таблица показывает и «учится» (двухсегментная полоса, подсказка), а итог занятия — «Учится: +N» (2026-11-27).
|
||||
- Из UI удалены выбор режима и порядка, шесть параметров контекста, дашборд с вкладками и графиками, отчёт Branches/Lines, режим «за оба цвета». Сохранённые значения остаются на диске, но не действуют; лимит `max_plies` снимается при загрузке; незавершённые сессии 2.x не возобновляются. Это заменяет UI-части решений 2026-11-04/05.
|
||||
- Вторичные действия: «Повторить всё подряд», «Тренировать эту ветку», экран «Варианты». Редактирования ходов на доске в этом этапе нет. Строка ходов линии в занятии показывается по решению владельца 2026-11-27 (заменяет решение 03.11): одна бледная строка SAN с номерами до позиции на доске, без спрашиваемого хода и без отметок ошибок, обрезка слева, постоянная высота; место — между строкой дебюта и комментарием (блок C спецификации).
|
||||
- Цвет задаётся при импорте/создании. При первом открытии раздела (файла библиотеки ещё нет) создаются два примера: Испанская партия (белые) и Найдорф (чёрные); удалённые примеры не возвращаются.
|
||||
- Неверный ход на только что показанном новом ходе ошибкой не считается: «Не тот ход» ~0,4 с, затем снова показ.
|
||||
|
||||
## Выпуск 2.4.0 (2026-11-27)
|
||||
|
||||
Владелец поручил слить ветку `feature/opening-trainer-v2` в `main`, отправить в Forgejo и GitHub,
|
||||
собрать сборки и обновить сайт по обычному процессу. После 2.3.0 это 2.4.0, тег v2.4.0.
|
||||
Таблица репертуаров по замечаниям владельца: «Сегодня» — фраза («повторить N», «новые: N», «завтра»),
|
||||
«Пройдено A/Y» с полосой «пройдено/закреплено»; слова «учится/выучено» заменены на «пройдено/закреплено».
|
||||
|
||||
## Стартовые репертуары и тестовые окна (2026-11-27)
|
||||
|
||||
- Владелец: примеры дебютов должны появляться и у обновившихся. Выбран вариант «выдавать недостающие один раз»: ключ каждого примера запоминается в `repertoire-starters.json`, удалённые не возвращаются. Заменяет правило 2.4.0 «только при первом открытии раздела». Пользователь 2.4.0, удаливший пример до обновления, получит его один раз — подтверждено владельцем 2026-11-27.
|
||||
- Набор: Испанская партия и Ферзевый гамбит за белых, Найдорф и Треугольник (полуславянская) за чёрных.
|
||||
- Визуальная приёмка этого раздела — на Full HD 1920×1080 (владелец).
|
||||
- Тестовые окна приложения — только на невидимом мониторе Hyprland через `scripts/dev/headless-run.sh`, не на мониторах владельца (владелец выбрал вариант 2).
|
||||
- Комментарии примеров — на русском для русского интерфейса и на английском для остальных (владелец, 2026-11-27). Следующий выпуск — 2.4.1; не выпускать, пока владелец не добавит задачи из бэклога (42, 43 и др.) и не скомандует выпуск.
|
||||
- Задача 42, пакетная копия в новую базу (владелец, 2026-11-27): дублем считается только запись с тем же текстом PGN (пробелы и переносы не в счёт); версия партии с другими комментариями копируется; номера пропущенных — в итоге. Минимум: только desktop и только новая база; новая база встаёт в конец полки, вперёд — только по «Открыть».
|
||||
|
||||
## Выпуск 2.5.0 (2026-11-27)
|
||||
|
||||
Владелец поручил коммит, push в Forgejo и GitHub, тег v2.5 и новую сборку, обновить сайт. Ранее названный номер 2.4.1 заменён: в выпуске новые функции (задачи 27, 42, 43), поэтому минорное увеличение — 2.5.0, тег v2.5.0. В выпуск входят задачи 26, 27, 42, 43, 44, 45.
|
||||
|
||||
## Пакетный анализ вручную выделенных партий (2026-11-27)
|
||||
|
||||
Владелец расширил задачу 27 после выпуска 2.5.0: массив для общего анализа можно получить не только фильтром, но и существующим ручным выделением партий из задачи 42. Это отменяет прежнее согласованное ограничение «кнопка только по фильтру, без пункта для выделенных»; остальные правила задачи 27 сохраняются.
|
||||
|
||||
- **Приоритет источника.** Если выделена хотя бы одна партия, существующая кнопка анализирует выделение; если выделения нет — отфильтрованный массив, как раньше. Отдельную вторую кнопку не добавляем.
|
||||
- **Скрытые фильтром.** В анализ входят все выделенные партии, включая скрытые текущим фильтром: выделение по-прежнему переживает смену фильтра. Перед запуском явно показывается число выбранных партий и, если они есть, число скрытых текущим фильтром.
|
||||
- **Лимит.** Для выделения действует тот же предел: 1–100 партий включительно. При большем числе кнопка неактивна и подсказка просит выбрать не больше 100; очистка выделения возвращает прежнее поведение по фильтру.
|
||||
- **Без нового механизма.** Диалог, предупреждение о времени, кэш, проход Stockfish, прогресс, остановка/продолжение, итоговое окно и отметки `!!` используются общие. Создание новой базы из выбранных и исходные PGN не меняются.
|
||||
|
||||
## Выпуск 2.5.1 (2026-11-28)
|
||||
|
||||
Владелец явно выбрал увеличение последнего числа после 2.5.0: версия **2.5.1**, тег `v2.5.1`. В выпуск входит задача 46. Поручены отправка в Forgejo и GitHub и публикация сборок.
|
||||
|
||||
## Android: простая подготовка к сопернику (2026-11-28)
|
||||
|
||||
Владелец поручил мобильный сценарий задачи 48: выбрать соперника из базы или открытой партии и его цвет, показать доску цветом пользователя вниз (противоположным цвету соперника), продолжения стрелками и списком по частоте, число партий и победы/ничьи/поражения выбранного игрока. Ход разрешён и на доске, и касанием продолжения. Это разрешает **простую** подготовку на Android и не переносит настольный отчёт целиком; прежнее «на Android не делаем» задачи 19 остаётся в силе для его сложных разделов.
|
||||
|
||||
Технические границы реализации, выбранные оркестратором в рамках этого простого сценария: точный вариант имени без склейки, одна выбранная сторона, транспозиции, только первое вхождение позиции в основную линию каждой партии, RAV не считаются сыгранными ходами, неизвестный `Result` отдельно от поражений. Никаких оценок движка, поиска ошибок, SRS и изменения исходных баз.
|
||||
|
||||
## Android: ориентация доски подготовки — стороной пользователя (2026-11-29)
|
||||
|
||||
Владелец уточнил: подготовка строится от его стороны против выбранного соперника. Поэтому соперник белыми означает чёрные внизу (`flipped = true`), соперник чёрными — белые внизу (`flipped = false`). Прежняя реализация с цветом соперника вниз была неверной интерпретацией и исправлена. Ручной переворот доски остаётся доступным; обе стартовые ориентации и ручной flip проверены на эмуляторе и приняты независимым ревью (`docs/qa/android-prep-orientation.md`).
|
||||
|
||||
## Android: список игроков с плоскими строками (2026-11-29)
|
||||
|
||||
Владелец выбрал улучшенный экран Players по варианту B+: плоские строки 72 dp вместо двух плашек White/Black у каждого игрока. Если ненулевой цвет один, касание строки сразу открывает подготовку этим цветом; если доступны оба, открывается короткий лист с двумя действиями по 64 dp и без дополнительного подтверждения. Нулевой цвет остаётся видимым текстом, но не отдельной disabled-кнопкой. Поиск, точные имена, счётчики и возврат в подготовку сохраняются. Проект — `docs/design/android-players-improvement.md`. По ремарке владельца 2026-11-29 лист озаглавлен «Подготовиться к %1$s» (без двоеточия), действия названы «Против белых» и «Против чёрных», чтобы цвет не читался как цвет самого пользователя (`docs/qa/android-color-sheet-wording.md`).
|
||||
|
||||
## Выпуск 2.5.2 (2026-11-30)
|
||||
|
||||
Владелец явно выбрал увеличение последнего числа после 2.5.1: версия **2.5.2**, тег `v2.5.2`. В выпуск входят задачи 29 и 48: кнопка анализа и навигация на экране Android-партии, простая подготовка к сопернику. Поручены commit и push в Forgejo и GitHub, Android-сборка для сайта, обновление сайта и RuStore.
|
||||
|
|
|
|||
|
|
@ -1,332 +0,0 @@
|
|||
# Задача 48. Android: простая подготовка к сопернику по базе
|
||||
|
||||
Дизайнер, 2026-11-28, ветка `feature/android-opponent-prep`. Документ описывает **MVP для Android**, а не перенос настольного отчёта. Код не изменялся.
|
||||
|
||||
## 1. Задача и границы
|
||||
|
||||
**Задача экрана — за один взгляд понять, как выбранный человек играет из текущей позиции: доска и ход важнее всего, затем частые продолжения, число партий и результаты именно этого человека.**
|
||||
|
||||
В MVP есть два входа в один экран исследования:
|
||||
|
||||
1. **Из открытой партии** — соперник и позиция уже известны; остаётся выбрать, чей репертуар смотреть: белых или чёрных.
|
||||
2. **Из базы** — через экран игроков, где видны общее число партий и отдельные входы «белыми» / «чёрными» с числом партий.
|
||||
|
||||
На экране исследования:
|
||||
|
||||
- доска изначально повёрнута **цветом пользователя вниз — противоположным цвету соперника**;
|
||||
- ход можно сделать на доске, касанием стрелки частого продолжения или касанием строки продолжения;
|
||||
- продолжения отсортированы по числу партий; у каждого видны число, доля и W/D/L выбранного игрока;
|
||||
- ◀/▶, удержание для перехода к границам и ручной переворот работают как в текущей партии;
|
||||
- всё происходит локально и только для чтения: партия, PGN и база не меняются.
|
||||
|
||||
**Не входит:** Stockfish и оценки, поиск ошибок, вкладки «Дебюты/Ошибки», ECO и названия вариантов, фильтры периода/силы, список партий узла, экспорт досье, сохранённые подготовки, онлайн-explorer, desktop-отчёт и новая система повторений. Связь с задачей 38 — только техническая, через чтение базы и позиции; отдельного позиционного поиска и его фильтров здесь нет.
|
||||
|
||||
## 2. Что проверено в реальных материалах
|
||||
|
||||
Просмотрены сами изображения:
|
||||
|
||||
- приложенный владельцем монтаж `docs/screenshots/android.jpg`, **1920×1080**: список партий, партия, лист игры и список людей;
|
||||
- `website/shots/raw/phone/01-home.png`, `02-games.png`, `03-game.png`, `04-engine.png`, каждый **1080×2400**;
|
||||
- реальный кадр текущей панели после `a005185` — `/tmp/opencode/29-final.png`, **1080×2400**;
|
||||
- `designExample/reference.png` — доска и таблица продолжений ChessBase;
|
||||
- `designExample/доска.png` и `designExample/панель ходов с ответвлениями.png` — ориентация, координаты и чтение ходов;
|
||||
- настольный `docs/screenshots/prep-openings.jpg` использован только как подтверждение смысла цвета и статистики, не как макет для телефона.
|
||||
|
||||
Снимки телефона относятся к AVD **420 dpi**, то есть density **2,625**, а не ×3: 1080×2400 px соответствует примерно **411×914 dp**. Поэтому проектные размеры ниже даны в dp/sp; отдельно проверяется эталон **360×800 dp**.
|
||||
|
||||
По снимкам и коду текущего `a005185` подтверждено:
|
||||
|
||||
- доска в портрете занимает всю ширину, без полей и скругления; плашки игроков — 36 dp;
|
||||
- строка партии — 80 dp, поля списка — 16 dp, разделитель — 1 dp `outlineVariant`;
|
||||
- нижняя панель партии — **72 dp**, поверхность `surfaceContainer`; после `a005185` ◀/▶ делают один шаг, удержание идёт в начало/конец без автоповтора;
|
||||
- `Board` уже умеет ориентацию, последний ход, стрелки, tap-tap и drag через `BoardInput`; сами стрелки сейчас только рисуются и отдельного hit testing не имеют;
|
||||
- `GamesScreen` имеет поиск и постранично читаемый `LazyColumn`; `Navigation.kt` сохраняет состояние экранов в стеке;
|
||||
- в `mobile-api` пока нет Android-экрана игроков и готового API подготовки: его нужно спроектировать, а не выдавать настольный `prep` за уже доступный на телефоне.
|
||||
|
||||
## 3. Пользовательские пути и сохранение контекста
|
||||
|
||||
### 3.1. Из партии: «Кого изучить — белых или чёрных?»
|
||||
|
||||
Путь: **Партия → ⋮ → «Подготовиться к сопернику…» → строка игрока/цвета → исследование**.
|
||||
|
||||
Меню открывает небольшой `ModalBottomSheet`, а не добавляет два почти одинаковых пункта в основное меню:
|
||||
|
||||
```text
|
||||
┌────────────────────────────────────┐
|
||||
│ ─── │
|
||||
│ Подготовка к сопернику │
|
||||
│ ○ Morphy, Paul │
|
||||
│ Белые │ 64 dp, вся строка — кнопка
|
||||
│ ● Duke Karl / Count Isouard │
|
||||
│ Чёрные │ 64 dp
|
||||
└────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- Имя — `bodyLarge`, цвет — `bodyMedium` `onSurfaceVariant`; слева существующий `SideDisc` 12 dp. Полное имя доступно TalkBack, визуально — по правилу `PlayerName`.
|
||||
- Одно касание сразу открывает исследование. Дополнительная кнопка «Открыть» не нужна: выбор строки уже однозначен.
|
||||
- Если имя одной стороны пусто или `?`, показывается только строка другой стороны. Если имена совпадают, остаются обе строки — репертуары за разные цвета различаются.
|
||||
- Пункт доступен только у партии, открытой из существующей базы. У новой партии нет источника статистики, поэтому пункта нет; у активной игры с компьютером меню и так отдельное.
|
||||
- Во время предпросмотра PV пункт неактивен; вторая строка пункта — «Сначала закройте линию движка». Нельзя молча подменить позицию партии позицией PV. Если на пути текущего узла есть учебный null move `--`, вторая строка — «Поиск после учебного -- недоступен»: после него нельзя честно сопоставить линию с реально сыгранными партиями.
|
||||
|
||||
**Стартовая позиция — текущий реальный узел партии**, включая вариант и исходный FEN, но не PV. В исследование передаётся путь от начала этой партии до текущего узла, поэтому ◀ позволяет пройти назад по уже виденной линии. Сама партия не продолжается и не редактируется.
|
||||
|
||||
Возврат системной «Назад» или ← восстанавливает партию на том же узле, с прежними нотацией, прокруткой, ориентацией и несохранёнными правками. Диалога «сохранить?» у исследования нет — оно ничего не изменило.
|
||||
|
||||
Почему этот вход нужен наряду со списком игроков: человек уже нашёл партию соперника и конкретную позицию; повторный поиск имени и переход в начальную позицию потеряли бы главный контекст.
|
||||
|
||||
### 3.2. Из базы: «Найти человека и сразу выбрать его цвет»
|
||||
|
||||
Путь: **Партии базы → значок «Игроки» → кнопка цвета в строке игрока → исследование с начальной позиции**.
|
||||
|
||||
В `TopAppBar` экрана «Партии» добавляется `IconButton` с `Icons.Rounded.Groups` и описанием **«Игроки»**. Значок ставится перед поиском; поиск остаётся на привычном месте. У онлайн-базы после них остаётся существующее скачивание/обновление. Каждая цель — 48×48 dp, длинное имя базы уступает место и обрезается многоточием.
|
||||
|
||||
Отдельный видимый значок выбран вместо пункта меню, которого сейчас у «Партий» нет: это второй равноправный вход в задачу, а не скрытая команда. На полку баз новая кнопка не добавляется — сначала нужен источник, то есть конкретная база.
|
||||
|
||||
Стек:
|
||||
|
||||
```text
|
||||
Базы → Партии → Игроки → Подготовка
|
||||
└───── Партия ────→ Подготовка
|
||||
```
|
||||
|
||||
«Назад» из игроков возвращает в ту же выдачу партий с поиском и прокруткой. Возврат из подготовки — в игроков с прежними запросом и прокруткой. Стартовая позиция из этого входа — обычная начальная; никакие поиск/фильтры списка партий не переносятся скрыто в статистику.
|
||||
|
||||
## 4. Экран «Игроки»
|
||||
|
||||
### 4.1. Задача и компоновка
|
||||
|
||||
**Задача экрана — выбрать точное написание игрока и цвет одним действием, видя объём данных по каждому цвету.**
|
||||
|
||||
```text
|
||||
┌────────────────────────────────────┐
|
||||
│ ← Игроки ⌕ │
|
||||
│ Alekhine │
|
||||
│ Alekhine, Alexander 266 партий│
|
||||
│ [○ Белыми · 153] [● Чёрными · 113] │ 48
|
||||
│────────────────────────────────────│
|
||||
│ Anderssen, Adolf 2 партии│
|
||||
│ [○ Белыми · 2] [● Чёрными · 0] │
|
||||
└────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- Заголовок — «Игроки», вторая строка — имя текущей базы. Справа поиск с существующим поведением `GamesScreen`: поле вместо заголовка, клавиатура, ✕, задержка 250 мс. Подсказка — **«Имя игрока»**.
|
||||
- Список по умолчанию — по алфавиту через `Collator`, без отдельной кнопки сортировки. Поиск фильтрует по подстроке без учёта регистра. Это не поиск похожих имён и не объединение людей.
|
||||
- Строки — плоские, как список партий, **без карточек**. Разделитель 1 dp `outlineVariant` находится внутри строки и не добавляет высоту.
|
||||
- Обычная высота строки — **88 dp**: 8 сверху + имя/счёт 24 + 4 + кнопки 48 + 4 снизу. При крупном шрифте используется `heightIn(min = 88.dp)` и строка растёт. Если две подписи цвета больше не помещаются рядом, кнопки становятся одна над другой на всю ширину, каждая остаётся не ниже 48 dp; название цвета не обрезается.
|
||||
- Поля — 16 dp. Имя — `bodyLarge`, общее число партий справа — `bodyMedium.merge(Tabular)`, `onSurfaceVariant`; имя сокращается первым. Полное имя и полное число озвучиваются.
|
||||
- Между цветовыми кнопками — 8 dp. На ширине 360 dp каждая занимает **160 dp**: `(360 − 32 − 8) / 2`. На 320 dp — 140 dp, на 280 dp — 120 dp. Подпись одной строкой, сначала сокращается число по `short_count`, полное остаётся в описании.
|
||||
- Кнопка — нейтральная `surfaceContainerLow`, скругление 8 dp, `SideDisc` 12 + 8 + текст `labelLarge`. Никаких двух ярких цветовых плашек: круг и слова уже различают стороны.
|
||||
- **Вся кнопка 48 dp — действие.** Нажатие на имя ничего не открывает, поэтому нет конкурирующего третьего сценария.
|
||||
- Нулевой цвет остаётся видимым, но кнопка неактивна. Это честная информация «партий этим цветом нет», а не причина переставлять кнопки.
|
||||
|
||||
Ключ игрока — точное имя из тега после `trim`, без нечёткого слияния. `Alekhine`, `Alekhine, Alexander` и другое написание остаются разными строками. Пустые и `?` в список не попадают. Автоматических догадок, кто из тегов является учебным названием, MVP не делает. Общее число — число различных записей; счётчики цветов считаются отдельно. Если имя стоит на обеих сторонах одной партии, общее число не складывает её дважды, а результат в исследовании зависит от выбранной стороны.
|
||||
|
||||
### 4.2. Состояния списка
|
||||
|
||||
| Состояние | Поведение |
|
||||
|---|---|
|
||||
| Первое чтение | Верхняя панель уже видна; в области списка — индикатор и «Читаю игроков…». Нули вместо неизвестных счётчиков не показываются |
|
||||
| Подгрузка страниц | Заглушки тех же 88 dp, разделители остаются; список не скачет |
|
||||
| Поиск | Старый результат другой строки запроса не выдаётся за новый; показаны заглушки/индикатор, затем результат |
|
||||
| Нет именованных игроков | «В этой базе нет именованных игроков» и кнопка «К партиям» |
|
||||
| Ничего не найдено | «Игрок не найден» + «Сбросить поиск» |
|
||||
| Ошибка базы/индекса | «Не удалось прочитать игроков» + существующее `openProblem`, кнопка «Повторить»; технический текст не подменяет причину |
|
||||
| Большая база | Индекс и поиск в фоне, `LazyColumn`, чтение страницами; уход отменяет незавершённый запрос |
|
||||
| Возврат | Запрос, выдача и прокрутка сохранены; выбранный ранее игрок не подсвечивается как «текущая позиция» — это другое состояние |
|
||||
|
||||
## 5. Экран исследования
|
||||
|
||||
### 5.1. Портрет 360×800 dp
|
||||
|
||||
Плашки двух игроков из экрана партии здесь не повторяются: выбранный человек и цвет уже находятся в заголовке. Это освобождает 72 dp под продолжения, не уменьшая доску.
|
||||
|
||||
```text
|
||||
┌────────────────────────────────────┐ 24, системная строка
|
||||
│ ← Alekhine, Alexander │ 64
|
||||
│ Чёрными · Alekhine │ выбранный цвет · база
|
||||
├────────────────────────────────────┤
|
||||
│ │
|
||||
│ ДОСКА 360 × 360 │ чёрные внизу
|
||||
│ до 3 стрелок продолжений │
|
||||
│ │
|
||||
├────────────────────────────────────┤
|
||||
│ Соперник играет · 1.e4 113 партий │ 32
|
||||
│ 1…c5 79/113 · 70 % │ 56
|
||||
│ +55 =14 −10 · W/D/L 70/18/13 % │
|
||||
│────────────────────────────────────│
|
||||
│ 1…e5 20/113 · 18 % │ 56
|
||||
│ +13 =4 −3 · W/D/L 65/20/15 % │
|
||||
│────────────────────────────────────│
|
||||
│ 1…Nf6 8/113 · 7 % │
|
||||
│ +4 =3 −1 · W/D/L 50/38/13 % │
|
||||
│ … прокручивается только список … │
|
||||
├────────────────────────────────────┤
|
||||
│ ⇅ ◀ ▶ │ 72
|
||||
└────────────────────────────────────┘ 24, системная навигация
|
||||
```
|
||||
|
||||
Верхняя панель:
|
||||
|
||||
- ← с описанием «К партии» или «К игрокам» по источнику;
|
||||
- имя игрока — `titleMedium`, одна строка, полное имя в TalkBack;
|
||||
- вторая строка — **цвет словом + имя базы**, `bodyMedium` `onSurfaceVariant`;
|
||||
- новых ⋮, движка, разбора и настроек в этой панели нет.
|
||||
|
||||
Строка контекста 32 dp явно называет, чьи продолжения показаны:
|
||||
|
||||
- на ходе выбранного человека — **«Соперник играет»**;
|
||||
- на ходе другой стороны — **«Его оппоненты играют»**.
|
||||
|
||||
Затем идёт «начало» либо «после {SAN с номером}», справа — число партий текущей позиции M. Левая часть обрезается, M остаётся. При неизвестном счётчике стоит `…`, не `0`. Для TalkBack добавляется точная сторона «ход белых/чёрных»: по FEN её нельзя выводить из чётности хода. Подпись «Его оппоненты играют» не даёт принять первый ход белых за выбор соперника чёрными.
|
||||
|
||||
### 5.2. Строка продолжения и смысл чисел
|
||||
|
||||
Обычная высота — **56 dp**, поля 16 dp, две строки:
|
||||
|
||||
1. SAN по настройке записи ходов, 17 sp, слева; справа **`N/M · P %`** `bodyMedium.merge(Tabular)`, где M — партии текущей позиции, N — партии с этим продолжением.
|
||||
2. **`+W =D −L · W/D/L wp/dp/lp %`**, `labelSmall.merge(Tabular)`, `onSurfaceVariant`: слева исходные счётчики, справа их доли в том же порядке. Если у продолжения есть партии с неизвестным итогом, перед W/D/L добавляется `ещё U`.
|
||||
|
||||
Вся строка — `Role.Button` с обычным ripple. Разделитель 1 dp входит в её высоту. Никаких карточек, графиков, рейтинговых цветов и сортировки по столбцам.
|
||||
|
||||
- Порядок: **N по убыванию**, при равенстве — по SAN. Все продолжения остаются в `LazyColumn`; редкие не скрываются.
|
||||
- `P = N / M × 100 %`, а не доля от начального репертуара. Существующий ход с долей меньше 1 % показывается как `<1 %`, не `0 %`. Одновременные `N/M` не дают принять процент на одной партии за устойчивую закономерность.
|
||||
- В статистику входят **только реально сыгранные основные линии**. RAV в базе не считается ходом соперника; позиция, взятая из RAV открытой партии, при этом разрешена как отправная.
|
||||
- Транспозиции объединяются по позиции. Партия учитывается один раз, по **первому вхождению позиции в её основную линию**; другой ход после повторного вхождения не добавляется.
|
||||
- Если сумма долей меньше 100 %, после продолжений обычными недоступными строками показываются **«Здесь закончились: N»** и, при учебном/неподдерживаемом следующем ходе, **«Нет обычного продолжения: N»**. Должно выполняться `ΣN(move) + ended + noNormalContinuation = M`.
|
||||
- Неизвестный результат `*` не становится поражением. Он входит в N, M и частоту, но не в знаменатель W/D/L: `known = W + D + L`, каждая доля делится на `known`. Если известных результатов нет, вместо всех трёх долей — `—`. Доли округляются независимо и не подгоняются до суммы ровно 100 %.
|
||||
- Если нечитаемые записи повлияли на выборку, отдельная служебная строка — **«Пропущено нечитаемых: N»**. Ошибка чтения не маскируется под ноль совпадений.
|
||||
- При нехватке места вторая строка переносится, а высота растёт через `heightIn(min = 56.dp)`. При крупном шрифте первая строка использует компактное `N/M · P %`. Горизонтальной прокрутки нет.
|
||||
|
||||
**W/D/L всегда относится к выбранному человеку, а не к стороне, которая сейчас ходит.** На ходе его соперников список показывает их продолжения, но победы/ничьи/поражения по-прежнему считаются для выбранного человека. Например, для выбранных чёрных `0-1` — W, `1-0` — L. Это результат после фактически сыгранного продолжения, а не вероятность победы или оценка качества хода. Правило должно быть общим для API, отображения и TalkBack.
|
||||
|
||||
### 5.3. Доска и стрелки
|
||||
|
||||
- Начальная ориентация: соперник белыми — чёрные внизу (`flipped = true`), соперник чёрными — белые внизу (`flipped = false`). Она **не зависит от того, чей сейчас ход**. Уточнение владельца 2026-11-29 заменяет прежнюю неверную ориентацию цветом соперника вниз.
|
||||
- ⇅ позволяет вручную перевернуть доску; выбор сохраняется при навигации по позициям и повороте телефона, но новый вход снова начинает с выбранного цвета.
|
||||
- После готовых данных рисуются **до трёх самых частых различных направлений** из списка. Не все сразу: десяток пересекающихся стрелок закрыл бы фигуры и сделал hit testing случайным; полный выбор остаётся в списке. Цвет и геометрия — существующие `BoardArrow`/`EngineArrow`: первый вес 1,0 и alpha 0,63, следующие — 0,85/0,45 и 0,70/0,35. Новых цветовых легенд нет; порядок дополнительно виден в списке.
|
||||
- Если разные UCI имеют одинаковые from/to (например, превращения), рисуется одна стрелка, а не несколько одинаковых поверх.
|
||||
- Касание стрелки делает соответствующий ход **один раз**. Область — не только тонкий видимый штрих: используется невидимый коридор вокруг shaft/head и зона не менее 48 dp у наконечника, ограниченная доской.
|
||||
- Касание наконечника и касание строки передают **точный UCI продолжения**, включая недопревращение. Обычный ручной ввод пешки сохраняет текущее правило приложения — по умолчанию ферзь.
|
||||
- Если коридоры/наконечники нескольких ходов пересекаются в точке касания, нельзя молча выбирать верхнюю стрелку: открывается короткий лист **«Выберите ход»** только с конфликтующими SAN. Если from/to совпадают, лист обязателен. После выбора делается один ход.
|
||||
- При уже выбранной фигуре обычный `BoardInput` имеет приоритет над shortcut стрелки. Drag не считается касанием стрелки. Реализация должна использовать **один распознаватель жестов** для доски и стрелок, а не два конкурирующих `pointerInput`.
|
||||
- Стрелки исчезают сразу при смене позиции, загрузке, ошибке и пустом результате. Статистика прежней позиции не остаётся ни на доске, ни в списке.
|
||||
- На доске также работают существующие tap-tap и drag любого легального хода, даже если его нет в базе. Тогда следующая позиция может честно показать «0 партий»; это не ошибка и не запрет продолжать.
|
||||
|
||||
До реализации нужен небольшой UI-прототип именно hit testing: повёрнутая доска, пересекающиеся стрелки, ширина 280 dp и drag. Существующий `Board` доказывает отрисовку и ввод фигур, но не касаемость стрелок.
|
||||
|
||||
### 5.4. Линия, ◀/▶ и нижняя панель
|
||||
|
||||
Нижняя панель остаётся **72 dp** и использует текущий `BarButton` из `a005185`:
|
||||
|
||||
| ⇅ | ◀ | ▶ |
|
||||
|---|---|---|
|
||||
| 72 dp | оставшаяся ширина поровну | оставшаяся ширина поровну |
|
||||
|
||||
На 360 dp это 72 / 144 / 144, на 320 dp — 72 / 124 / 124, на 280 dp — 72 / 104 / 104. Кнопки не уже 48 dp и занимают всю высоту панели; значки ◀/▶ — 32 dp.
|
||||
|
||||
- Короткое ◀/▶ — один полуход по исследуемой линии. Удержание ◀ — в её начало, ▶ — в конец, один раз и без предварительного шага/автоповтора.
|
||||
- После ◀ кнопка ▶ возвращается **тем же продолжением**, а не самым частым.
|
||||
- Новый ход после возврата назад отбрасывает только будущий хвост временной линии. Это не удаление варианта PGN и не требует подтверждения.
|
||||
- Длинное нажатие имеет те же accessibility custom actions «В начало/конец линии». Звук и вибрация — только после совершённого хода и по общим настройкам.
|
||||
- Недоступные ◀/▶ остаются на месте и не меняют геометрию.
|
||||
|
||||
## 6. Загрузка, пусто, ошибка и гонки
|
||||
|
||||
Область под доской имеет постоянную геометрию: доска, верхняя и нижняя панели не двигаются при смене данных. Меняется только содержимое прокручиваемой области.
|
||||
|
||||
| Состояние | Что видно |
|
||||
|---|---|
|
||||
| Первый вход | Сразу доска правильной ориентации и текущий путь; в области продолжений — место тех же строк и индикатор |
|
||||
| Запрос короче 300 мс | Результат появляется без промежуточного мигания |
|
||||
| Запрос дольше 300 мс | «Считаю продолжения…» в области списка; фиксированная полоса 2 dp над ним. Прежние SAN, стрелки и W/D/L уже удалены |
|
||||
| Ход во время запроса | Доска и путь меняются сразу; запрос прежней позиции отменяется/игнорируется по поколению, новый начинается независимо |
|
||||
| Позиция не встречалась | «В партиях {name} этой позиции нет» и подсказка «Можно продолжить на доске или вернуться ◀»; стрелок нет |
|
||||
| Продолжений нет, партии закончились | «Все партии здесь закончились»; W/D/L не выдумывается |
|
||||
| Ошибка текущего запроса | Доска и путь остаются; в области списка «Не удалось посчитать продолжения» + причина + «Повторить». Повтор относится к видимой позиции |
|
||||
| Не хватает памяти для индекса | Отдельный текст «Недостаточно памяти для поиска по этой базе», не «позиция не найдена»; доступны «Повторить» и возврат |
|
||||
| База исчезла/изменилась | Не показывать кэш как актуальные данные; та же ошибка с `openProblem`, возврат по ← доступен |
|
||||
| Много продолжений | Прокручивается только список; доска, контекст и кнопки закреплены |
|
||||
| Выход из исследования | Временная линия исчезает без вопроса; исходный экран сохраняется |
|
||||
| Поворот/возврат из фона | Игрок, цвет, путь, курсор, ориентация и прокрутка списка восстанавливаются; ответ старого поколения не применяется |
|
||||
|
||||
Для каждого запроса ключ должен включать базу и её версию, точное имя, цвет и текущую позицию/историю, необходимую ядру. Ответ применяется только если ключ всё ещё видим на экране.
|
||||
|
||||
## 7. Альбомная ориентация, узкие экраны и HiDPI
|
||||
|
||||
- **Портрет:** доска `fillMaxWidth().aspectRatio(1f)`, как в партии. На очень низком экране она не уменьшается; список получает остаток и прокручивается.
|
||||
- **Альбомная ориентация/широкое окно:** верхняя панель общая; слева квадратная доска на всю доступную высоту, справа — строка контекста, `LazyColumn` с весом 1 и нижняя панель 72 dp. Системные insets учитываются отдельно, доска не пересекается с навигацией.
|
||||
- **Планшетный портрет:** доска ограничена 480 dp и центрируется; строка контекста и список имеют ту же ширину, а не растягиваются на весь экран. Пустые поля не заполняются декоративными карточками.
|
||||
- **280/320 dp:** те же три кнопки внизу, две цветовые кнопки у игрока и двухстрочные продолжения; ни одна цель не уже 48 dp, горизонтальной прокрутки нет.
|
||||
- **Крупный шрифт:** строка контекста имеет `heightIn(min = 32.dp)` и может вырасти, не обрезая «Соперник играет» / «Его оппоненты играют». Строки продолжений растут, `N/M` и частота остаются в первой строке, исходные +/=/− и W/D/L переносятся на следующие. Числа не исчезают и не обрезаются. У игрока кнопки цвета при необходимости становятся вертикальными по §4.1.
|
||||
- **HiDPI:** использовать существующие векторные Material icons, dp/sp, `Pieces` с растровым кэшем фактического размера. Новых растровых ресурсов не требуется. Обязательная проверка — реальный 420 dpi, без вывода «×3» из размеров PNG.
|
||||
|
||||
## 8. Доступность, клавиатура и подсказки
|
||||
|
||||
### 8.1. TalkBack
|
||||
|
||||
- **Игрок:** имя и общее число — один информационный узел. Каждая цветовая кнопка отдельно: «{name}, белыми, 153 партии. Подготовиться» / «… чёрными, нет партий, неактивно». Круг не озвучивается отдельно.
|
||||
- **Доска:** один узел с позицией и ориентацией: «Доска, позиция после 1.e4. Чёрные выбранного игрока внизу». Не создавать 64 отдельных фокуса клеток.
|
||||
- У доски есть custom actions для видимых стрелок: «Сыграть 1…c5, 79 партий, 70 процентов». Полный список продолжений всегда доступен ниже, поэтому сценарий не зависит от жеста по Canvas.
|
||||
- **Продолжение:** одна кнопка: «1…c5. 79 из 113 партий, 70 процентов. Результаты Alekhine, Alexander: 55 побед, 14 ничьих, 10 поражений; 70, 18 и 13 процентов. Сыграть». При неизвестных исходах добавляется их число и пояснение, что они не входят в знаменатель процентов.
|
||||
- **Контекст:** «Соперник играет, ход чёрных, после 1.e4, 113 партий» либо «Его оппоненты играют, ход белых…» объявляется politely после готовности, один раз на позицию. Прогресс не озвучивается на каждое обновление; ошибка и пустой результат объявляются один раз.
|
||||
- После активации строки фокус не остаётся на удалённом элементе: он переводится на строку контекста новой позиции. При быстром листании не накапливается очередь объявлений.
|
||||
- ◀/▶ сохраняют текущие полные описания и custom actions границ. Неактивность передаётся семантически, не только серым.
|
||||
|
||||
### 8.2. Аппаратная клавиатура и D-pad
|
||||
|
||||
| Клавиша | Действие |
|
||||
|---|---|
|
||||
| Tab / Shift+Tab, D-pad | Стандартный порядок фокуса: ← → доступные custom actions доски → строки продолжений → ⇅ → ◀ → ▶ |
|
||||
| Enter / Space / DPAD_CENTER | Активировать сфокусированную строку или кнопку, один раз |
|
||||
| Android Back / Esc | Сначала закрыть лист/меню, затем покинуть текущий экран |
|
||||
| Длительное действие TalkBack | Границы линии через custom actions, как на сенсорном экране |
|
||||
|
||||
Глобальных буквенных сокращений и перехвата ←/→ в списке нет: они нужны для перемещения фокуса. Произвольный ход по 64 клеткам с аппаратной клавиатуры в MVP не добавляется; все продолжения базы и навигация доступны списком. Это ограничение не должно маскироваться под полную клавиатурную поддержку доски.
|
||||
|
||||
Видимый фокус — рамка 2 dp `primary` вокруг кнопки/строки, а не только смена tint. Hover-tooltip: «Игроки», «Перевернуть доску», «Предыдущий ход. Удержание — в начало», «Следующий ход. Удержание — в конец». На ◀/▶ сенсорное удержание выполняет переход, а не показывает tooltip.
|
||||
|
||||
## 9. Требования разработчику
|
||||
|
||||
1. Добавить в существующий Nav3 два сохраняемых назначения: «Игроки базы» и «Подготовка». Не делать подготовку новым разделом верхнего уровня. Не передавать всё PGN-дерево в `NavKey`; использовать стабильные идентификаторы и сохраняемую сессию исследования.
|
||||
2. В `GamesScreen` вынести `onPlayers`; в `GameScreen` — `onPrepare(player, white)`. Лист выбора цвета остаётся локальным состоянием партии. Использовать существующий стек, не пересоздавать исходный экран при возврате.
|
||||
3. Компоненты: `PlayersScreen`, плоская `PlayerPrepRow`, `PrepScreen`, `ContinuationRow`, общий блок `PrepControls`. Переиспользовать `Board`, `BoardInput`, `Pieces`, `SideDisc`, `PlayerName`, `groupDigits`, `displaySan`, `openProblem` и текущий `BarButton`; не копировать жест long press второй реализацией.
|
||||
4. Нужен новый локальный API, например модели `PlayerSummary(name,total,whiteGames,blackGames)`, `PrepPosition(games,continuations,endedHere,noNormalContinuation,skipped,unknownResults)`, `PrepContinuation(uci,san,games,wins,draws,losses,unknown)`. Названия — ориентир для разработчика, не утверждение о существующем UniFFI.
|
||||
5. Счётчики строить только по выбранной базе и точному `(name,color)`. Агрегация в Rust — **main line, first occurrence**, с транспозициями и без RAV в статистике; существующий смешанный `MoveStat.tally` для этого не подходит. Частота — от партий текущей позиции; W/D/L — от финального результата выбранного игрока на ходе любой стороны. Не запускать Stockfish и не читать настольный отчёт об ошибках.
|
||||
6. Чтение игроков и позиций — вне UI-потока, со страницами, отменой и защитой от поздних ответов. Большая база не собирается в память целиком ради списка. Исходные файлы открываются только на чтение; тест — SHA-256/mtime до и после.
|
||||
7. Путь исследования отделён от `GameSession` партии. Касание строки/стрелки и обычный ввод дают один UCI и один переход. Для недопревращений не заменять UCI продолжения ходом по умолчанию.
|
||||
8. Доработать `Board` одним gesture resolver: координаты hit regions стрелок вычисляются тем же преобразованием `flipped`, что их отрисовка. Проверить конфликты с выбором фигуры, drag, краями доски и системным «назад».
|
||||
9. При каждом новом запросе сразу очищать старые стрелки/статистику. Никакого «пока новое считается, покажем прежнее».
|
||||
10. Все видимые строки и описания — ресурсы на всех девяти уже поддерживаемых языках; числа партий — через plurals. W/D/L можно оставить международным сокращением, но TalkBack обязан произносить локализованные «победы/ничьи/поражения».
|
||||
11. Compose-тесты: две цветовые цели игрока, disabled при нуле, одна активация продолжения, конфликт одинаковых from/to, flip-hit mapping, ◀/▶ и custom actions, отсутствие фокуса на исчезнувшей строке, стабильные минимальные размеры.
|
||||
12. Не добавлять сохранение, undo, пункты анализа, список партий или фильтры «на будущее» в этом MVP.
|
||||
|
||||
## 10. Независимой проверке и тестировщику
|
||||
|
||||
Визуальную приёмку выполняет **отдельный ревьюер, не автор макета и не автор реализации**. Он запускает реальное приложение в изолированных настройках и прикладывает снимки; чтения Kotlin и Compose preview недостаточно.
|
||||
|
||||
### 10.1. Обязательные сценарии и доказательства
|
||||
|
||||
1. **Сравнение существующего и нового:** текущие «Партии» и «Партия» из той же сборки, затем «Игроки» и «Подготовка». Сверить фон, `TopAppBar`, поля 16 dp, доску, нижние 72 dp, иконки и типографику. На реальном AVD 1080×2400/420 dpi указать фактические dp, а не называть его 360×800.
|
||||
2. **Оба входа:** партия → лист White/Black → текущая позиция; база → игроки → цвет → начальная позиция. Показать белые внизу в одном случае и чёрные внизу в другом. Возврат — к прежнему узлу/прокрутке.
|
||||
3. **Заполненная подготовка:** минимум четыре продолжения, разные N и W/D/L, до трёх стрелок. Проверить выравнивание SAN, `N/M · %`, второй строки +/=/− и W/D/L и отсутствие карточек.
|
||||
4. **Последовательность без скачков:** загрузка → заполнено → ход стрелкой → ход строкой → ◀ → ▶ → позиция без партий → ошибка → «Повторить». На каждом кадре зафиксировать координаты доски, строки контекста и нижней панели. Изменение высоты допустимо только при переносе текста/смене ориентации по явному условию.
|
||||
5. **Пустые состояния:** нет игроков, поиск игрока без результата, нулевой цвет, ноль партий в позиции, все партии закончились. Нули не должны мелькать во время загрузки.
|
||||
6. **Узкое и крупное:** 320 и 280 dp, font scale 1,3 и 2,0: обе цветовые кнопки, три нижние кнопки и W/D/L не обрезаны; строки растут без горизонтальной прокрутки.
|
||||
7. **Альбомная ориентация:** доска слева, продолжения справа, панель 72 dp; системные панели ничего не перекрывают. Светлую тему проверять отдельно только если добавятся новые цвета — по текущему макету новых ролей нет.
|
||||
8. **HiDPI:** чёткие SVG-фигуры, Material icons, круги сторон, стрелки и текст на 420 dpi. Снимки подписать файлом, размером px, density, ориентацией и состоянием данных.
|
||||
|
||||
Вердикт «ровно» без снимков не принимается. Дефект записывать как: экран/состояние, ожидаемая и фактическая координата или выравнивание, шаги воспроизведения, файл снимка.
|
||||
|
||||
### 10.2. Функциональная матрица
|
||||
|
||||
- Точные имена и цвета: одинаковое имя за оба цвета, разные написания, пусто/`?`, нулевой цвет, длинное имя.
|
||||
- Текущий узел и FEN из партии; начальная позиция из базы; вариант партии; PV и путь после учебного `--` не используются. Старт чёрными и `fullmove=0` определяют сторону по FEN, не по чётности ply.
|
||||
- Стрелка, строка, tap-tap и drag дают один и тот же ход; рокировка, взятие, превращение и недопревращение; flip не меняет UCI.
|
||||
- Пересекающиеся стрелки и одинаковые from/to не делают произвольный ход. Двойное касание не создаёт два хода.
|
||||
- ◀/▶ по одному полуходу, удержание без предварительного шага и автоповтора; возврат тем же child; новый ход отсекает только временный хвост.
|
||||
- Частота `N/M` от текущего узла, сортировка по N, `<1 %`, «закончились здесь», `noNormalContinuation`, неизвестный результат, исходные +/=/− и W/D/L выбранного игрока на ходе обеих сторон. Отдельно проверить белых и чёрных. Контрольный fixture: у соперника чёрными `0-1, 0-1, 1-0, *` → `+2 =0 −1 · ещё 1 · W/D/L 67/0/33 %`; зеркальный пример белыми даёт те же доли.
|
||||
- Две транспозиции дают одинаковую выборку; повтор позиции учитывается один раз; RAV-only запись не входит, основная линия с RAV добавляет только реальный следующий ход. Проверить равенство `ΣN + ended + noNormalContinuation = M`.
|
||||
- Гонка A → B → A: ответ первого A не применяется к последнему A без совпадения полного ключа/поколения; ответ B никогда не появляется на A.
|
||||
- Исходная партия с несохранёнными правками возвращается как была; PGN и база не изменились. Новых записей в «Мои базы» не появляется.
|
||||
- TalkBack: полные описания, disabled, custom actions стрелок и границ, отсутствие прогресс-спама, фокус после исчезновения строки. Аппаратная клавиатура — по §8.2, без заявления произвольного хода по клеткам.
|
||||
- Большая база: прокрутка игроков и продолжений, смена запроса во время чтения, уход с экрана, повтор после ошибки, отсутствие блокировки UI.
|
||||
|
|
@ -1,211 +0,0 @@
|
|||
# Задача 48. Android: улучшение экрана «Игроки»
|
||||
|
||||
Дизайнер, 2026-11-29. Документ предлагает следующий MVP-шаг после уже реализованного экрана. **Production-код, ресурсы и другие документы не изменялись.** Это не отчёт о визуальной приёмке и не исправление падения поиска.
|
||||
|
||||
## 1. Задача и приоритет
|
||||
|
||||
**Задача экрана — быстро найти точное имя и начать подготовку за нужный цвет, не заставляя человека читать по две одинаковые кнопки у каждого игрока.**
|
||||
|
||||
Приоритеты:
|
||||
|
||||
1. точное имя и понятное следующее действие;
|
||||
2. число партий по каждому цвету, включая честный ноль;
|
||||
3. одно касание там, где существует только один возможный цвет, и отсутствие отдельного подтверждения «Открыть»;
|
||||
4. плоский мобильный список, поиск и прокрутка сотен имён — не таблица и не досье.
|
||||
|
||||
Общее число партий остаётся полезным контекстом, но не должно отнимать место у имени и цветов. Поиск похожих имён, объединение написаний, аватары, рейтинги, список партий игрока и досье не добавляются.
|
||||
|
||||
## 2. Что проверено в материалах
|
||||
|
||||
### 2.1. Текущая реализация
|
||||
|
||||
Прочитаны `docs/design/android-opponent-prep.md` §4 и актуальный `PlayersScreen.kt`.
|
||||
|
||||
Сейчас `PlayerPrepRow` действительно состоит из:
|
||||
|
||||
- имени и общего счётчика;
|
||||
- двух отдельных кнопок высотой не менее 48 dp;
|
||||
- нейтральных плашек `surfaceContainerLow` со скруглением 8 dp;
|
||||
- disabled-кнопки при нулевом цвете;
|
||||
- обычной высоты 88 dp и трёх accessibility-узлов на человека: информация, White, Black.
|
||||
|
||||
Это понятная и быстрая схема: цвет выбирается сразу, одним касанием. Её цена — повторение двух плашек и подписей в каждой строке, а также визуальное присутствие неактивных действий там, где у человека есть партии только одним цветом.
|
||||
|
||||
`/tmp/opencode/qa48-search-crash/players.xml` существует и прочитан как **UI Automator XML, а не PNG**. На AVD 1080×2400, 420 dpi он подтверждает:
|
||||
|
||||
- шаг обычных строк 231 px = 88 dp;
|
||||
- цветовые цели 126 px = 48 dp;
|
||||
- поля 42 px = 16 dp;
|
||||
- у Alekhine две доступные кнопки, у Anderssen — White доступна, Black с нулём disabled;
|
||||
- имя/счёт и обе цветовые кнопки являются отдельными semantic nodes.
|
||||
|
||||
Также прочитаны `games.xml` и `logcat.txt`. Падение — отдельный `NullPointerException` из-за чтения `players!!` старым `LazyColumn` при смене запроса. Новая компоновка сама по себе этот дефект не исправляет и не должна подменять его regression-фикс.
|
||||
|
||||
**Ограничение evidence:** актуального PNG Players в `/tmp/opencode/qa48-search-crash/` нет; прежний каталог `/tmp/opencode/prep48` отсутствует. Поэтому утверждения о текущей геометрии опираются на XML и Kotlin, а не на несуществующий новый снимок. Ниже — проектное сравнение, не повторная визуальная приёмка старого экрана.
|
||||
|
||||
### 2.2. Визуальная система продукта
|
||||
|
||||
Инструментом просмотра изображений посмотрены сами изображения:
|
||||
|
||||
- `docs/screenshots/android.jpg`, 1920×1080 — монтаж Android-списков, партии и листов;
|
||||
- `website/shots/raw/phone/01-home.png`, `02-games.png`, `03-game.png`, каждый 1080×2400;
|
||||
- `designExample/reference.png`, `designExample/доска.png`, `designExample/панель ходов с ответвлениями.png` — референсы смысла доски и нотации, не макет мобильного списка.
|
||||
|
||||
Для Players нужно сохранить уже существующий язык Android-приложения: тёмную `surface`, обычную `TopAppBar`, `bodyLarge`/`bodyMedium`, `SideDisc`, плоские разделители `outlineVariant`, поля 16 dp и стандартный ripple. Новых цветовых ролей, карточек, градиентов, аватаров и dashboard-плиток не требуется.
|
||||
|
||||
## 3. Сравнение вариантов
|
||||
|
||||
| Вариант | Действия | Плотность и шум | Цена |
|
||||
|---|---|---|---|
|
||||
| **A. Оставить две кнопки 48 dp у каждого** | Всегда 1 касание | 88 dp; полные слова White/Black самые явные, но две плашки и до двух действий повторяются в каждой строке. Нулевой цвет занимает disabled-плашку | Минимум разработки и уже знакомая модель. Не решает запрос на более спокойный и компактный экран; при линейном TalkBack-обходе много лишних остановок |
|
||||
| **B. Одна строка игрока → выбор цвета** | Обычно 2 касания: игрок, затем цвет | Строка может быть 72 dp; имя и все счётчики видны без кнопочных плашек. На листе помещаются полное имя, полные подписи и точные числа | Дополнительный лист и второй тап даже тогда, когда ненулевой цвет только один. Если обязательно открывать лист всем, это неоправданная плата за единообразие |
|
||||
| **C. Компактные segmented controls в строке** | 1 касание, если сегмент сразу запускает подготовку; 2, если это настоящий single-choice с последующим «Открыть» | Возможна строка 72 dp, но на 360 dp группа шириной 144 dp оставляет имени примерно 172 dp после полей и промежутка. Полные локализованные «Белыми»/«Чёрными» и большие числа уже не помещаются; приходится оставлять круги и короткие числа | Маленькие соседние цели повышают цену промаха и снова сокращают имена. При 280 dp/font scale 2.0 блок придётся переносить, возвращаясь к высоте текущего варианта. `SingleChoiceSegmentedButtonRow` со `selected` также ложно обещает сохраняемый выбор, хотя здесь нужен переход, а не фильтр |
|
||||
|
||||
### Рекомендация — **B+: одна спокойная строка, лист только при реальном выборе**
|
||||
|
||||
- **Оба цвета ненулевые:** касание строки открывает короткий `ModalBottomSheet` с двумя большими действиями. Второй тап — сам выбор цвета, отдельной кнопки подтверждения нет.
|
||||
- **Ненулевой только один цвет:** касание строки сразу открывает подготовку этим цветом. Спрашивать единственный возможный вариант не нужно.
|
||||
- **Ноль:** остаётся видимым текстом в строке, но перестаёт быть отдельной disabled-кнопкой.
|
||||
- Никогда не выбирать автоматически цвет с большим числом партий, последний использованный цвет или White по умолчанию.
|
||||
|
||||
Так сохраняется один тап у частого случая «есть только White или только Black», а при двух репертуарах появляется более явный и безопасный выбор. Это не скрытая смена смысла строки: доступные цвета и ноль видны до касания, а TalkBack заранее произносит либо «Выбрать цвет», либо «Подготовиться белыми/чёрными».
|
||||
|
||||
Почему не C: экономия одного касания только у игроков с двумя цветами не оправдывает постоянное сокращение всех имён, риск попасть не в тот сегмент и неоднозначную семантику selected/action. При необходимости A можно оставить как временную реализацию, но не как целевой MVP-экран.
|
||||
|
||||
## 4. Пользовательский путь и контекст
|
||||
|
||||
```text
|
||||
Партии → Игроки → игрок с двумя цветами → лист цвета → Подготовка
|
||||
└ игрок с одним цветом ───────────────→ Подготовка
|
||||
```
|
||||
|
||||
- Поиск остаётся в текущей `TopAppBar`: подстрока без учёта регистра, задержка 250 мс, ✕ и системное закрытие поиска. Порядок — алфавитный через `Collator`; точные написания не объединяются.
|
||||
- При переходе в подготовку клавиатура скрывается. Возврат восстанавливает запрос, режим поиска и прокрутку, но сам не открывает клавиатуру поверх списка.
|
||||
- Возврат из подготовки идёт в Players, а не заново в лист цвета. Прежний игрок не получает постоянную подсветку «выбран» или «текущая позиция».
|
||||
- Android Back при открытом листе сначала закрывает только лист и возвращает фокус на исходную строку. Следующий Back возвращается в партии.
|
||||
- Players и лист только читают уже полученный `PlayerSummary`; никаких несохранённых изменений и диалога сохранения нет.
|
||||
|
||||
## 5. Макет списка
|
||||
|
||||
### 5.1. Обычная строка, 360 dp
|
||||
|
||||
```text
|
||||
┌────────────────────────────────────┐
|
||||
│ ← Игроки ⌕ │
|
||||
│ Classic games │
|
||||
│────────────────────────────────────│
|
||||
│ Alekhine, Alexander 5 партий ›│ 24
|
||||
│ ○ Белыми · 2 ● Чёрными · 3 │ 20
|
||||
│────────────────────────────────────│ обычная высота строки 72
|
||||
│ Anderssen, Adolf 2 партии ›│
|
||||
│ ○ Белыми · 2 ● Чёрными · 0 │
|
||||
│────────────────────────────────────│
|
||||
│ Aronian, Levon 1 партия ›│
|
||||
│ ○ Белыми · 1 ● Чёрными · 0 │
|
||||
└────────────────────────────────────┘
|
||||
```
|
||||
|
||||
`›` показан справа условно по центру строки, а не как третья колонка таблицы. Вся строка, включая имя, счётчики и свободное место, — одна кнопка.
|
||||
|
||||
### 5.2. Геометрия и типографика
|
||||
|
||||
- Минимальная высота — **72 dp**: 12 сверху + имя/общий счёт 24 + 4 + цвета 20 + 12 снизу. Разделитель 1 dp находится внутри нижней границы и высоту не добавляет.
|
||||
- По сравнению со 88 dp это на 18 % меньше высоты и примерно на 22 % больше видимых строк в той же области. Например, в подтверждённой текущим XML области около 750 dp помещается ориентировочно 10,4 строки вместо 8,5.
|
||||
- Горизонтальные поля — 16 dp. Справа декоративный `ChevronRight` 24 dp `onSurfaceVariant`, перед ним промежуток 8 dp; отдельной зоны нажатия у него нет.
|
||||
- Имя — существующий `PlayerName`, `bodyLarge`: полное имя, затем `shortName`, затем многоточие. Полное точное имя остаётся в content description. Общий счёт — `bodyMedium.merge(Tabular)`, `onSurfaceVariant`, одной строкой; перед ним 8 dp, сокращается сначала имя.
|
||||
- Цвета — `bodyMedium.merge(Tabular)`, `onSurfaceVariant`, в неизменном порядке **Белыми, затем Чёрными**. Существующий `SideDisc` 12 dp, промежуток до текста 8 dp; круг не озвучивается отдельно.
|
||||
- Группа «круг + название цвета + число» неделима. Между группами 16 dp. Если обе не помещаются, они переносятся на две строки, а высота растёт через `heightIn(min = 72.dp)`; горизонтальной прокрутки и обрезания нулей нет.
|
||||
- Общее число — прежнее число различных записей, а не обязательно `whiteGames + blackGames`. Оно не должно «исправляться» суммированием на UI.
|
||||
- Строка плоская, без фона-карточки. Есть стандартный ripple и разделитель `outlineVariant`; постоянного selected-фона после возврата нет.
|
||||
|
||||
### 5.3. Лист выбора цвета
|
||||
|
||||
Открывается только когда `whiteGames > 0 && blackGames > 0`:
|
||||
|
||||
```text
|
||||
┌────────────────────────────────────┐
|
||||
│ ─── │
|
||||
│ Alekhine, Alexander │ titleLarge, полное имя
|
||||
│ 5 партий · выберите цвет │ bodyMedium, secondary
|
||||
│ ○ Белыми 2 ›│ 64, вся строка — действие
|
||||
│ ● Чёрными 3 ›│ 64
|
||||
└────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- Использовать существующий паттерн `ModalBottomSheet`, горизонтальные поля 24 dp и нижний отступ 24 dp, как у текущего листа подготовки из партии.
|
||||
- Полное имя переносится, а не заменяется инициалами. При аномально длинном теге содержимое листа прокручивается; цветовые подписи и числа не обрезаются.
|
||||
- Каждая строка — `heightIn(min = 64.dp)`, `SideDisc` 12 + 12 dp, цвет `bodyLarge`, точный счёт справа `bodyMedium.merge(Tabular)`. Это `Role.Button`, не RadioButton и не `selected` segment.
|
||||
- Никакой загрузки статистики внутри листа: имя и счётчики уже есть в `PlayerSummary`, поэтому его высота не меняется после появления.
|
||||
- Касание цвета сразу вызывает существующий `onPrepare(player, white)` и закрывает лист. Кнопки «Открыть»/«Продолжить» нет.
|
||||
|
||||
## 6. Состояния и крайние случаи
|
||||
|
||||
| Состояние | Требуемое поведение |
|
||||
|---|---|
|
||||
| Первое чтение | Верхняя панель видна; в области списка текущий индикатор/«Читаю игроков…». Нули вместо неизвестных значений не показываются |
|
||||
| Подгрузка страниц | Заглушки с той же минимальной высотой 72 dp и теми же двумя текстовыми линиями; разделители не исчезают. Переход заглушка → обычная однострочная запись не меняет шаг списка |
|
||||
| Поиск | Прежнее поведение и debounce сохраняются; ответ старого запроса не показывается как новый. Одновременно с redesign обязателен отдельный regression-фикс снимка списка, а не новый `players!!` в строке |
|
||||
| Нет именованных игроков | Прежние «В этой базе нет именованных игроков» и «К партиям» |
|
||||
| Ничего не найдено | Прежние «Игрок не найден» и «Сбросить поиск» |
|
||||
| Ошибка | Прежние причина через `openProblem` и «Повторить»; ошибка не маскируется под пустой список или нулевые цвета |
|
||||
| Оба цвета есть | Одна строка «Выбрать цвет», затем лист с двумя действиями |
|
||||
| Только White или только Black | Оба счётчика видны, включая `0`; касание сразу запускает единственный ненулевой цвет |
|
||||
| Нулевой цвет | Текст `… · 0` обычной secondary-краской, без disabled-плашки и отдельного фокуса. Цвет не скрывается и места White/Black не меняются |
|
||||
| Длинное имя | Действует существующее `PlayerName`; счётчики не наезжают. Полное имя озвучивается, а на листе двух цветов также переносится визуально |
|
||||
| 280/320 dp и font scale 1.3/2.0 | Цветовые группы переносятся, строка и лист растут; названия цветов и нули не обрезаются. Нет горизонтального скролла и сегментов уже 48 dp |
|
||||
| Сотни игроков | Сохранить `LazyColumn`, страницы по 100, стабильный ключ `id` и фоновое чтение. Один semantic node на человека сокращает линейный TalkBack-обход. Не добавлять ради этого полную загрузку базы в память |
|
||||
| Широкое окно/ландшафт | Та же одноколоночная лента и тот же лист, не сетка и не настольные столбцы |
|
||||
| HiDPI | Только dp/sp, существующие векторные icons и `SideDisc`; новых растровых ресурсов нет |
|
||||
| Возврат | Запрос и прокрутка прежние; лист закрыт, клавиатура сама не появляется, строка не подсвечена как выбранная |
|
||||
|
||||
Алфавитный быстрый бегунок, буквенные section headers и виртуальные столбцы в этот MVP не входят: поиск уже решает основной сценарий сотен имён без усложнения жестов.
|
||||
|
||||
## 7. Доступность, клавиатура и фокус
|
||||
|
||||
### 7.1. TalkBack
|
||||
|
||||
Вся строка игрока — один `Role.Button`; дочерние тексты не создают самостоятельные остановки.
|
||||
|
||||
- Два цвета: **«Alekhine, Alexander, всего 5 партий. Белыми 2, чёрными 3. Выбрать цвет»**.
|
||||
- Один цвет: **«Anderssen, Adolf, всего 2 партии. Белыми 2, чёрными 0. Подготовиться белыми»**.
|
||||
- Только Black формулируется симметрично. Ноль произносится словами/числом, а не только затемнением.
|
||||
- На листе действия: **«Alekhine, Alexander, белыми, 2 партии. Подготовиться»** и аналогично для чёрных.
|
||||
|
||||
При открытии листа фокус переходит в него и один раз объявляется контекст «выберите цвет». При закрытии без выбора фокус возвращается на исходного игрока. После возврата из подготовки фокус/прокрутка по возможности восстанавливаются на том же `id`, без объявления его «текущей позицией». Ошибка и пустой результат объявляются один раз; подгрузка каждой страницы не читается вслух.
|
||||
|
||||
### 7.2. Аппаратная клавиатура и D-pad
|
||||
|
||||
| Ввод | Действие |
|
||||
|---|---|
|
||||
| Tab / Shift+Tab, D-pad | ← → Search/поле поиска → строки игроков → доступное действие пустого/ошибочного состояния. На листе: White → Black |
|
||||
| Enter / Space / DPAD_CENTER | Активировать игрока или цвет один раз |
|
||||
| IME Search | Скрыть клавиатуру, не запускать первого найденного игрока |
|
||||
| Android Back / Esc | Закрыть лист; затем закрыть поиск; затем покинуть Players |
|
||||
| Буквы и ←/→ вне текстового поля | Не перехватываются глобально; используются системной навигацией фокуса |
|
||||
|
||||
Видимый фокус — рамка 2 dp `primary` вокруг всей строки или действия листа. Hover-tooltip у строки соответствует будущему действию: «Выбрать цвет» либо «Подготовиться белыми/чёрными». Дополнительного сенсорного long press не требуется.
|
||||
|
||||
## 8. Требования разработчику
|
||||
|
||||
1. Заменить в списке `PlayerPrepRow` с двумя `PlayerColorButton` на одну плоскую actionable-строку по §5. `PlayerSummary`, API статистики и `onPrepare(player, white)` не меняются; новых запросов ради листа нет.
|
||||
2. Локальное состояние листа — только выбранный `PlayerSummary?`. Условие листа строго `whiteGames > 0 && blackGames > 0`; при ровно одном ненулевом счётчике вызывать `onPrepare` сразу. Не добавлять remembered color, сортировку по частоте или автоматический выбор большего репертуара.
|
||||
3. Не использовать `SingleChoiceSegmentedButtonRow` и `checked/selected` для навигационных действий листа. Нужны две обычные строки `Role.Button`, визуально близкие к существующему листу подготовки из партии.
|
||||
4. Переиспользовать `ModalBottomSheet`, `SideDisc`, `PlayerName`, `Tabular`, `groupDigits`, plurals и текущие цвета темы. Новые цвета не вводить; все новые строки/action labels перевести на девять поддерживаемых языков.
|
||||
5. Placeholder и обычная запись имеют одинаковую минимальную геометрию 72 dp. Разделитель рисовать внутри строки, не отдельным элементом `LazyColumn`.
|
||||
6. Исправление NPE при поиске остаётся обязательной отдельной частью изменения: LazyColumn должен работать с неизменным snapshot страницы, без чтения обнулённого `players!!`. Не считать смену UI-теста доказательством отсутствия гонки.
|
||||
7. Сохранить точную статистику и постраничность. Общий total не вычислять суммой цветов; пустые/`?` имена и разные написания обрабатывать как раньше.
|
||||
8. Compose-тесты: два цвета → лист; только White/Black → прямой переход; нули видимы без disabled-действия; отсутствие выбора по большему count; одна активация при double tap; Back из листа/подготовки; сохранение query+scroll; полное semantics-описание; перенос на 280 dp/font scale 2.0; placeholder → данные без скачка 72 dp.
|
||||
|
||||
## 9. Независимой проверке после реализации
|
||||
|
||||
Реализацию принимает отдельный ревьюер, не автор макета и не автор кода. Нужны реальные запуск и снимки, а не только Compose Preview или чтение Kotlin. Сравнить главную/«Партии» и «Партию» той же сборки по фону, TopAppBar, типографике, полям и `SideDisc`.
|
||||
|
||||
Минимальные доказательства с учётом экономии владельца:
|
||||
|
||||
1. **Players, заполненный:** 1080×2400, 420 dpi, тёмная тема; один человек с двумя ненулевыми цветами и минимум один с нулём. Проверить шаг 72 dp, поля 16 dp, переносы, отсутствие карточек и disabled-плашек.
|
||||
2. **Лист двух цветов:** тот же игрок и те же счётчики; полное имя, White/Black, строки ≥64 dp. Back возвращает к той же строке без выбора.
|
||||
3. **Единственный цвет:** касание сразу открывает подготовку стороной пользователя вниз (противоположной сопернику); возврат сохраняет query/scroll и не открывает лист.
|
||||
4. **Переполнение:** длинное имя и font scale 2.0 либо 280/320 dp — отдельный целевой кадр, потому что здесь меняется wrapping. Числа и слова цветов не обрезаны, высота растёт только от переноса текста.
|
||||
5. **Пагинация/поиск:** заглушка 72 dp → данные, ввод и очистка запроса без crash и без выдачи старого результата за новый. Для скачков зафиксировать координаты соседних строк; не создавать лишнюю серию одинаковых кадров.
|
||||
|
||||
Каждый снимок подписать файлом, px, density, ориентацией и состоянием. Дефект записывать как экран/состояние, ожидаемая и фактическая геометрия или действие, шаги воспроизведения и файл evidence. Отсутствие прежнего `/tmp/opencode/prep48` не разрешает выдавать этот документ за визуально доказанное «стало лучше»: это решение к реализации и последующей приёмке.
|
||||
|
|
@ -1,215 +0,0 @@
|
|||
# Задача 29. Android: «📈 Анализ» в нижней панели партии
|
||||
|
||||
Дизайнер, 2026-11-28, ветка `feature/android-review-button`. Я менял только этот документ; код не редактировал.
|
||||
|
||||
**Статус решения:** сценарий ниже — подтверждённое требование владельца, не вариант для выбора. Отдельные **⏮ и ⏭ убрать**. **Касание ◀/▶ — один ход, удержание ◀ — в начало, удержание ▶ — в конец.** «📈 Анализ» добавить справа в ту же нижнюю панель, цветом `!!`. Второй панели не будет, доска не уменьшается.
|
||||
|
||||
## 1. Задача экрана и пользовательский путь
|
||||
|
||||
Главное на экране — читать партию и переходить по ходам; разбор должен быть заметен сразу, но не отнимать место у доски и не смешиваться с живым движком.
|
||||
|
||||
Путь становится короче:
|
||||
|
||||
- раньше: «Партия» → `⋮` → «Анализ партии» → лист запуска;
|
||||
- теперь: «Партия» → **📈 Анализ** → тот же лист запуска → «Анализировать».
|
||||
|
||||
После разбора та же кнопка — **📈 Отчёт**: открывает существующий `ReviewSheet` и возвращает скрытую панель анализа. Алгоритм, кэш, лист запуска, график, отчёт, остановка крестиком и пауза живого движка не меняются. Пункт «Анализ партии / Отчёт по партии» убрать из `⋮`, чтобы не было двух одинаковых входов. Остальные пункты меню и кнопка «Отчёт» внутри панели анализа остаются.
|
||||
|
||||
Закрытие листа запуска или отчёта возвращает к той же позиции и прокрутке нотации. Системная «Назад» по-прежнему сначала закрывает верхний лист, затем предпросмотр PV, и только потом покидает партию.
|
||||
|
||||
## 2. Что проверено в реальных материалах
|
||||
|
||||
Просмотрены изображения, а не только имена файлов:
|
||||
|
||||
- `docs/screenshots/android.jpg` — 1920×1080;
|
||||
- `website/shots/raw/06-android.png` — 3840×2160;
|
||||
- `website/shots/raw/phone/03-game.png`, `04-engine.png`, `08-review.png` — каждый 1080×2400, то есть эталонные 360×800 dp при density ×3;
|
||||
- остальные телефонные снимки `01-home.png`, `02-games.png`, `05-play.png`, `06-who.png`, `07-rodent.png`;
|
||||
- соответствующие материалы `designExample/`, включая доску с анализом и панель вариантов.
|
||||
|
||||
На `03-game.png` панель высотой 72 dp содержит шесть элементов: движок, переворот, ⏮, ◀, ▶, ⏭. На `04-engine.png` включённый движок обозначен синим и подчёркиванием; это состояние нельзя дублировать у разбора. На `08-review.png` цвет `!!` уже используется в строке «!! Brilliant move» и в кружке на доске, а «Report» находится в строке над графиком.
|
||||
|
||||
Проверен код:
|
||||
|
||||
- нижняя панель — `GameScreen.kt:852–879`, высота `72.dp`; доска в портрете — `fillMaxWidth()` (`1284–1290`), в альбомной ориентации — `fillMaxHeight()` (`1272–1282`);
|
||||
- повтор ходов сейчас встроен в `BarButton` (`1642–1693`): шаг на нажатии, повтор через 400 мс каждые 120 мс. **Этот автоповтор для ◀/▶ отменяется новым требованием владельца**;
|
||||
- старый вход в разбор и его условия — `GameScreen.kt:1179–1200`;
|
||||
- панель разбора и листы — `ReviewViews.kt`; останавливать разбор новой нижней кнопкой не требуется: для этого уже есть ✕ в `ReviewPanel`;
|
||||
- во время активной партии с компьютером используется отдельный `PlayControls`; его состав этой задачей не меняем.
|
||||
|
||||
## 3. Обязательная компоновка
|
||||
|
||||
### 3.1. Портрет, эталон 360 dp
|
||||
|
||||
```text
|
||||
┌────────────────────────────────────┐
|
||||
│ ← Турнир · год ‹ › ⋮ │
|
||||
│ ● Чёрные │
|
||||
│ │
|
||||
│ ДОСКА 360 × 360 │ без изменения размера
|
||||
│ │
|
||||
│ ○ Белые │
|
||||
│ [движок/разбор — только по state] │
|
||||
│ нотация, комментарии, варианты │
|
||||
├────────────────────────────────────┤
|
||||
│ ▣ ⇅ ◀ ▶ [📈]│ 72 dp, одна панель
|
||||
│ Движок Анализ│
|
||||
└────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Порядок слева направо фиксирован: **Движок → Перевернуть → ◀ → ▶ → 📈 Анализ/Отчёт**. ⏮ и ⏭ не остаются ни визуально, ни как невидимые кнопки.
|
||||
|
||||
Размеры слотов на 360 dp:
|
||||
|
||||
| Движок | Перевернуть | ◀ | ▶ | Анализ |
|
||||
|---:|---:|---:|---:|---:|
|
||||
| 60 dp | 48 dp | 78 dp | 78 dp | 96 dp |
|
||||
|
||||
Сумма — ровно 360 dp. Все пять целей касания занимают полную высоту 72 dp; минимальная ширина — 48 dp. ◀/▶ остаются шире остальных навигационных кнопок, их значки — прежние 32 dp.
|
||||
|
||||
На 320 dp: **56 / 48 / 64 / 64 / 88 = 320 dp**. Ниже 320 dp подпись «Анализ/Отчёт» скрывается, слот разбора сужается до 52 dp, иконка и полное описание для TalkBack остаются; панель не прокручивается горизонтально и не переносится на вторую строку. При ширине 280 dp раскладка: **52 / 48 / 64 / 64 / 52 = 280 dp**.
|
||||
|
||||
В альбомной ориентации используется та же строка в правой колонке, высота по-прежнему 72 dp. Доска продолжает занимать полную доступную высоту. Никаких дополнительных карточек, отдельной плавающей кнопки или FAB над нотацией нет.
|
||||
|
||||
### 3.2. Сам контрол разбора
|
||||
|
||||
Он повторяет геометрию подписанной кнопки «Движок», чтобы базовые линии совпадали:
|
||||
|
||||
- зона нажатия — весь закреплённый слот × 72 dp;
|
||||
- визуальный контейнер иконки — **36×36 dp**, значок **24 dp**;
|
||||
- под иконкой — одна строка `labelSmall` 12 sp/16 dp: «Анализ», «Отчёт» либо табличный счётчик `N/M`;
|
||||
- контейнер 36 dp и ширина слота не меняются между состояниями;
|
||||
- у разбора нет синего подчёркивания движка: это действие/переход к отчёту, не переключатель.
|
||||
|
||||
Иконка — `Icons.Rounded.QueryStats`: график с лупой, близкий к настольному 📈 и отличный от `Memory` живого движка. Наличие `rounded/QueryStatsKt` проверено в уже подключённом `material-icons-extended-android:1.7.8`; новую графику и сторонние ресурсы добавлять не нужно.
|
||||
|
||||
## 4. Навигация: касание и удержание
|
||||
|
||||
| Контрол | Короткое касание | Удержание |
|
||||
|---|---|---|
|
||||
| ◀ | Ровно один шаг назад, как текущий `back()` | Один переход в начало отображаемой линии |
|
||||
| ▶ | Ровно один шаг вперёд, как текущий `forward()` | Один переход в конец отображаемой линии |
|
||||
|
||||
Обязательные детали:
|
||||
|
||||
1. **Удержание не должно сначала делать один ход.** Короткий шаг выполняется при отпускании до системного `longPressTimeout`; по достижении таймаута выполняется только переход к границе. Отпускание после него не добавляет ещё один шаг.
|
||||
2. Автоповтора 400/120 мс больше нет. Удержание срабатывает один раз; движение/отмена касания — без действия.
|
||||
3. Обычная партия: начало — узел `0`; конец — конец текущей ветки, как у существующего `end()`.
|
||||
4. Предпросмотр PV остаётся отдельным контекстом: касания листают шаги PV, удержания идут к первому/последнему шагу PV. Выход из PV — прежние ✕, системная «Назад» или касание доски; касание ◀ до первого шага также выходит, как сейчас. Партию предпросмотр не изменяет.
|
||||
5. `canBack`/`canForward` одновременно управляют касанием и удержанием. Недоступные действия не исчезают и не переставляют соседние кнопки.
|
||||
6. Для этих двух кнопок нужен отдельный `combinedClickable`-контрол (или эквивалент с такой же семантикой), а не прежний `BarButton(repeat = true)`. Переворот доски остаётся на прежнем `BarButton`.
|
||||
|
||||
## 5. Состояния кнопки разбора
|
||||
|
||||
Действие кнопки переиспользует логику удаляемого пункта меню `1179–1200`; повторный разбор, скачивание движка и открытие сессии для новой/завершённой компьютерной партии не переписываются.
|
||||
|
||||
| Состояние | Вид в постоянном слоте | Действие и доступность |
|
||||
|---|---|---|
|
||||
| Партия загружается | Нейтральная иконка, «Анализ» | Недоступна; слот уже занят, последующего сдвига нет |
|
||||
| Нет ходов | Нейтральная иконка, «Анализ» | Недоступна; подсказка «В партии нет ходов для анализа» |
|
||||
| Разбора нет, ходы есть | **Бирюзовый контейнер 36 dp**, тёмная/белая иконка по теме, подпись «Анализ» | Открывает существующий лист запуска; разбор не начинается молча |
|
||||
| Движок ещё не скачан | То же приглашающее состояние | Тот же лист запуска, затем существующий лист скачивания |
|
||||
| Движок готовится | Индетерминированное кольцо вокруг 📈, «Анализ» | Не даёт открыть дубликат потока; текст «Готовлю движок…» остаётся в панели |
|
||||
| Идёт первый разбор, данных для отчёта ещё нет | Детерминированное кольцо 📈, подпись `N/M`, без сплошной заливки | Недоступна как действие; прогресс и ✕ «Остановить» — в `ReviewPanel` |
|
||||
| Идёт разбор, частичный/прежний отчёт уже есть | Кольцо 📈, подпись «Отчёт» | Доступна: открывает отчёт, процесс продолжается; остановка только существующим ✕ |
|
||||
| Разбор готов или загружен из кэша/PGN | 📈 бирюзовым **без заливки**, подпись «Отчёт» обычным `onSurface` | Открывает `ReviewSheet`, возвращает панель, если она была скрыта |
|
||||
| Анализ скрыт через «Скрыть анализ» | То же состояние «Отчёт» | `reviewHidden = false` и открытие отчёта; анализ не удаляется |
|
||||
| `stale`, `missing`, `secondsMissing`, ошибка | Нижняя кнопка остаётся «Отчёт», если `hasData`; иначе обычная «Анализ» | «Обновить», «Дополнить», «Продолжить» остаются в панели; новых параллельных действий нет |
|
||||
| Идёт партия с компьютером | Эта панель не показывается, действует `PlayControls` | Ничего не добавлять; после завершения доступен обычный экран разбора |
|
||||
|
||||
Прогресс не должен озвучиваться автоматически на каждое обновление: TalkBack читает `N/M` при фокусе, иначе несколько сотен объявлений подряд помешают навигации.
|
||||
|
||||
## 6. Цвет и существующие селекторы
|
||||
|
||||
### 6.1. Источник цвета
|
||||
|
||||
В Android уже есть единый селектор шахматных цветов `nagColor(nag, dark)` в `theme/Color.kt:57–79`; `judgementColor(BRILLIANT, dark)` вызывает его через NAG `$3` (`ReviewViews.kt:81–92`). Использовать его, **не дублировать новую константу разбора в `GameScreen.kt`**.
|
||||
|
||||
| Состояние | Тёмная тема | Светлая тема |
|
||||
|---|---|---|
|
||||
| Контейнер «Анализ» | `#26C2A3` — `nagColor(3, true)` | `#1A846F` — `nagColor(3, false)` |
|
||||
| Иконка на контейнере | `#1B1B1B`, контраст 7,65:1 | `#FFFFFF`, контраст 4,59:1 |
|
||||
| Hover при мыши | `#3FD3B4` / иконка `#1B1B1B` | `#157461` / белая иконка |
|
||||
| Pressed | `#1FA88D` / иконка `#1B1B1B` | `#10614F` / белая иконка |
|
||||
| «Отчёт» | Без заливки; 📈 `#26C2A3`, подпись `onSurface` | Без заливки; 📈 `#1A846F`, подпись `onSurface` |
|
||||
| Недоступна | Без бирюзового: `onSurface` с alpha 0,38 | То же |
|
||||
|
||||
Оттенки hover/pressed совпадают с уже принятым настольным решением `docs/design/task-26-review-button-2026-11-27.md`. На панели Android `surfaceContainer` контраст самой бирюзовой иконки — 6,89:1 в тёмной и 4,02:1 в светлой теме; для графики достаточно 3:1. Подпись всегда `onSurface`, поэтому читаемость 12 sp не зависит от бирюзового.
|
||||
|
||||
В проекте нет XML `res/color*` или `selector`-ресурсов для этих кнопок: состояния задаются в Compose. Не создавать параллельный `ColorStateList`. Базовый цвет берётся из `nagColor`; производные оттенки, если понадобятся явно, размещаются одной функцией рядом с ним. Обычный ripple нажатия сохраняется поверх указанных цветов.
|
||||
|
||||
Сплошная заливка нужна только до первого разбора. После него яркое приглашение исчезает, чтобы не спорить с доской, синим текущим ходом (`#005C80`) и включённым движком. Состояния различаются также текстом, кольцом прогресса и доступностью, не одним цветом.
|
||||
|
||||
## 7. TalkBack, клавиатура и подсказки
|
||||
|
||||
### 7.1. Семантика разбора
|
||||
|
||||
- Вся область слота — один `Role.Button`, без отдельно фокусируемых иконки и подписи.
|
||||
- `contentDescription`: полное существующее `review_menu` («Анализ партии») или `review_report_menu` («Отчёт по партии»), а не короткое видимое «Анализ».
|
||||
- Во время подготовки/разбора `stateDescription`: «Готовлю движок…» или существующий `review_progress` («Анализ партии · N из M»).
|
||||
- Недоступное состояние выставляется через `disabled()`/`enabled = false`; TalkBack должен сказать «неактивно», касание ничего не запускает.
|
||||
- Кнопка не `Switch` и не `toggleable`: открытый лист — не включённый режим.
|
||||
|
||||
### 7.2. Семантика ◀/▶ и альтернатива удержанию
|
||||
|
||||
Для ◀:
|
||||
|
||||
- `contentDescription` — «Предыдущий ход»;
|
||||
- `onClick` — один шаг;
|
||||
- `onLongClick(label = "В начало линии")` — переход к началу;
|
||||
- в `customActions` добавить **«В начало линии»**.
|
||||
|
||||
Для ▶ — симметрично: «Следующий ход», `onLongClick(label = "В конец линии")`, custom action **«В конец линии»**.
|
||||
|
||||
Так переходы к границам доступны не только жестом: в TalkBack они есть в меню действий элемента. Двойное касание выполняет один шаг; двойное касание с удержанием — long click. Не полагаться только на последний жест.
|
||||
|
||||
Порядок обхода TalkBack и D-pad: **Движок → Перевернуть → Предыдущий ход → Следующий ход → Анализ партии**. Enter/Space/DPAD_CENTER активирует короткое действие. При фокусе на ◀ клавиша Home повторяет «В начало линии», при фокусе на ▶ End — «В конец линии»; глобальных буквенных сокращений не добавлять. Фокус — видимая рамка 2 dp `primary` вокруг контейнера иконки, не только изменение tint.
|
||||
|
||||
### 7.3. Видимые подсказки
|
||||
|
||||
1. **📈:** `PlainTooltip` по hover и удержанию (у этой кнопки удержание не занято навигацией). Текст: «Анализ партии», «Отчёт по партии», «Анализ партии · N из M. Остановка — крестиком над графиком» либо причина недоступности. Tooltip обёртывает весь слот, поэтому работает и у визуально неактивной кнопки.
|
||||
2. **◀/▶:** hover-tooltip «Предыдущий ход. Удержание — в начало линии» / «Следующий ход. Удержание — в конец линии». На сенсорном экране долгое нажатие выполняет действие, а не показывает tooltip.
|
||||
3. Чтобы жест был открываем без мыши и TalkBack, один раз на устройство показать существующий `SnackbarHost`: **«Касание ◀ ▶ — один ход. Удержание — начало или конец линии.»** Показ — после загрузки обычной партии, не во время активной игры с компьютером и не поверх открытого листа. Snackbar перекрывает панель временно, но не меняет размеры layout; повторять при каждом открытии не нужно. Признак показа сохраняется в настройках.
|
||||
4. Для локализации добавить короткие `review_short` («Анализ» / «Analysis»), подсказки удержания и одноразового Snackbar на все уже поддерживаемые языки. Полные названия берутся из существующих `review_menu`, `review_report_menu`, `review_progress`, `review_stop`.
|
||||
|
||||
## 8. Матрица размеров и остальных состояний
|
||||
|
||||
| Ситуация | Требуемое поведение |
|
||||
|---|---|
|
||||
| Пустая/новая партия | Кнопка видна, но неактивна; доска и остальные четыре контрола не двигаются |
|
||||
| Ошибка загрузки партии | Нейтральная неактивная «Анализ»; ошибка остаётся существующим текстом в области нотации |
|
||||
| Большая база | Разбор относится к уже открытой партии; новых списков и работы на UI-потоке нет |
|
||||
| Несохранённые правки | Поведение сохранения и ухода не меняется; нижняя кнопка использует тот же путь, что прежний пункт меню |
|
||||
| Запуск → прогресс → готово | Панель остаётся 72 dp, слот и контейнер 36 dp неизменны; меняются только иконка/кольцо и подпись |
|
||||
| Появление кэша при открытии | «Анализ» меняется на «Отчёт» внутри того же слота без изменения ширины и высоты |
|
||||
| Живой движок включён | Кнопка движка остаётся; во время разбора его строка показывает прежнюю паузу, затем счёт продолжается |
|
||||
| Крупный шрифт | В узком слоте остаётся только 📈; полное имя есть в TalkBack и tooltip. Текст не обрезается и не переносит панель |
|
||||
| 320/280 dp | Раскладки из §3.1; пять целей не уже 48 dp, нет горизонтального скролла |
|
||||
| HiDPI | Vector-иконка и кольцо задаются в dp; эталонные снимки ×3 не должны показать обрезку или размытие |
|
||||
| Смена темы | Меняется только палитра; размеры и позиции идентичны |
|
||||
|
||||
Появление существующей панели разбора 88 dp уменьшает только нотацию и происходит по явному запуску/открытию сохранённого анализа, как раньше. **Само это изменение новой кнопки не добавляет ни одного dp по вертикали; доска в портрете остаётся 360×360 dp, а в альбомной ориентации — на всю доступную высоту.** Завершение, остановка, возврат из фона и появление статистики не должны вызывать скачков нижней панели.
|
||||
|
||||
## 9. Требования разработчику
|
||||
|
||||
1. В `GameScreen.kt` удалить два слота `FirstPage`/`LastPage`, добавить `ReviewButton` справа и оставить высоту `Surface`/строки без изменений.
|
||||
2. Для ◀/▶ заменить repeat-контрол на tap/long-click с семантикой §4 и §7. Не вызывать шаг на `down`, иначе удержание даст лишний ход.
|
||||
3. Вынести текущий обработчик пункта меню в один `onReview()` и вызывать его из новой кнопки; пункт меню удалить. Не заводить вторую реализацию открытия сессии.
|
||||
4. Базовый цвет получать через `judgementColor(MoveJudgement.BRILLIANT, dark)` или `nagColor(3, dark)`. Не использовать `MaterialTheme.colorScheme.primary`: синий зарезервирован за движком и текущей позицией.
|
||||
5. Ширину слота не вычислять от текста «Анализ»/`N/M`/«Отчёт». Счётчик — `labelSmall.merge(Tabular)`, одна строка.
|
||||
6. Состояния и нажатия не должны менять `review`, кроме существующего пути запуска/открытия отчёта. Остановка остаётся только в `ReviewPanel`.
|
||||
7. Добавить/обновить Compose-тесты семантики: один click, long click без предварительного click, custom actions, disabled, content/state descriptions и постоянные размеры слотов.
|
||||
|
||||
## 10. Что передать независимому ревьюеру и тестировщику
|
||||
|
||||
Ревьюер — не автор реализации; проверять реальное приложение на эмуляторе/устройстве и снимки, не только Kotlin-код.
|
||||
|
||||
1. **Сравнение 360×800 dp, density ×3:** `03-game`, `04-engine`, `08-review` до/после. Доска и верх панели совпадают по координатам; нижняя панель остаётся 72 dp. Состояния: нет разбора, идёт первый разбор, готово/«Отчёт», включён живой движок.
|
||||
2. **Серия без скачков:** «Анализ» → лист запуска → `N/M` → «Отчёт» → скрыть анализ → вернуть через нижнюю кнопку. Зафиксировать координаты доски, верха нотации и всех пяти слотов на каждом снимке.
|
||||
3. **Жесты:** 20 коротких касаний дают ровно 20 ходов; удержание ◀/▶ — один переход к границе без предварительного шага и без автоповтора. Проверить вариант и PV, выход из PV прежними способами.
|
||||
4. **Доступность:** TalkBack озвучивает полные названия, прогресс только по запросу фокуса, disabled; custom actions «В начало/конец линии» работают без удержания. Проверить одноразовый Snackbar и tooltip разбора.
|
||||
5. **Узкое и крупное:** 320 dp и 280 dp, крупный шрифт: пять кнопок видны, цели ≥48 dp, текст не обрезан, второй строки нет.
|
||||
6. **Цвет:** пиксельная сверка контейнера с `nagColor(3, dark)` и строкой «!! Brilliant move» на `08-review`-состоянии. В светлой теме — `#1A846F`, белая иконка. «Отчёт» не сохраняет сплошную заливку.
|
||||
7. **Регрессии:** живой движок ставится на паузу и возобновляется; остановка разбора существующим ✕; поворот и возврат из фона продолжают разбор; активная игра с компьютером использует прежний `PlayControls`.
|
||||
|
||||
Вердикт визуальной приёмки должен ссылаться на файлы снимков, размер/плотность и состояние каждого. Общего «панель выглядит так же» без доказательств недостаточно.
|
||||
|
|
@ -1,67 +0,0 @@
|
|||
# Тренировка дебюта: новая концепция (2026-11-26)
|
||||
|
||||
Статус: решение оркестратора по поручению владельца («проработай сам: проще, понятнее,
|
||||
функционально; другие разделы не трогать»). Основания: `docs/research/opening-trainer-rethink-2026-11-26.md`
|
||||
(аналитик), `docs/research/opening-trainer-code-audit-2026-11-26.md` (разработчик),
|
||||
`docs/design/opening-trainer-ui-audit-2026-11-26.md` (дизайнер), руководство и форум ChessTempo
|
||||
(корпус: `target/qa-opening-rethink/chesstempo-corpus/`).
|
||||
|
||||
## Идея в одной фразе
|
||||
|
||||
Репертуар — это PGN-дерево за один цвет; кнопка «Тренироваться» проводит по линиям от начала,
|
||||
спрашивает только те свои ходы, которые пора повторить или которые новые, и заканчивает занятие
|
||||
понятным итогом. Всё остальное — во втором плане или удалено.
|
||||
|
||||
## Сценарий
|
||||
|
||||
1. «Тренировка дебюта» → один экран: слева доска (геометрия экрана партии), справа таблица
|
||||
репертуаров (стиль таблицы библиотеки) и карточка выбранного.
|
||||
2. Пусто → текст и две кнопки: «Импорт PGN…», «Новый репертуар». Ещё путь — «Добавить в репертуар…»
|
||||
из экрана партии (уже есть, не меняется).
|
||||
3. Карточка: название · «Играю белыми/чёрными» · «Сегодня: N повторить · M новых» ·
|
||||
«Выучено X из Y ходов» с полосой · основная кнопка **Тренироваться**.
|
||||
4. Занятие: программа проигрывает ходы соперника и уже уверенно известные свои ходы с анимацией,
|
||||
останавливается на спрашиваемом ходе. Одна строка состояния сверху: что делать сейчас и «Осталось N».
|
||||
- **Новый ход:** показан стрелкой и подписью «Новый ход — сыграйте его»; комментарий PGN виден.
|
||||
- **Повторение:** «Ваш ход» без стрелки.
|
||||
- **Верно:** короткое «Верно», комментарий к ходу, дальше.
|
||||
- **Неверно:** фигура возвращается, «Правильно: Сb5» + стрелка, пользователь играет его; ход
|
||||
вернётся в этом же занятии.
|
||||
- «Подсказка» (H) — показать ход; засчитывается как показанный, а не как верный.
|
||||
5. Конец: «Готово. Верно 14, ошибок 2. Следующее повторение — завтра» и кнопки «К репертуару» /
|
||||
«Ещё 10 новых» (если есть).
|
||||
6. Меню строки `⋯`: «Повторить всё подряд» (обзор перед турниром, линия за линией), «Просмотр
|
||||
вариантов» (дерево ходов: выбрать ход → «Тренировать эту ветку», «Не тренировать»/«Тренировать»),
|
||||
переименовать, сменить цвет, экспорт PGN, сброс прогресса (с подтверждением), удалить.
|
||||
|
||||
## Уточнения по UI-аудиту дизайнера (приняты)
|
||||
|
||||
- Состояние занятия («Новый ход», «Ваш ход», «Неверно…», «Осталось N») живёт в карточке правой
|
||||
панели, как статус партии в игре с компьютером, а не строкой над доской.
|
||||
- Цвет репертуара спрашивается при импорте/создании (сейчас чёрный PGN открывается как «Белые», `op-04`).
|
||||
- Меню `⋯` действует только на свою строку; вёрстка таблицы в узкой панели проверяется на 960×600.
|
||||
|
||||
## Решения по открытым вопросам
|
||||
|
||||
| Вопрос | Решение | Почему |
|
||||
| --- | --- | --- |
|
||||
| Единица тренировки | Ход (SRS по `(FEN4, UCI)`), подача — линией от начала | ядро ChessTempo; линия даёт контекст, который владелец просил 02–03.11 |
|
||||
| Единица прогресса | Ходы | честно отражает модель; варианты пересекаются |
|
||||
| Порция новых | 10 за занятие, кнопка «Ещё 10 новых» | ясный конец занятия; без настройки |
|
||||
| Режимы, порядки, 6 параметров контекста, окно параметров | Удалить из UI | главный источник прошлых отказов; типы в Settings остаются, чтобы не сбросить настройки |
|
||||
| Дашборд, графики, вкладки, отчёт Branches/Lines, Uncertain/Resistant | Удалить из UI | заменяются тремя числами карточки; данные на диске не трогаются |
|
||||
| Режим «за оба цвета» | Удалить из UI | у репертуара один цвет; старые «Both» открываются как белые/выбор цвета при первом запуске |
|
||||
| Лимит глубины `max_plies` | Снимать при загрузке (как 03.11 сняли старые лимиты) | пользователь его не выбирал; PGN не меняется |
|
||||
| Незавершённые сессии 2.x | Не возобновлять, начинать новое занятие | все ответы уже записаны; прогресс не теряется |
|
||||
| Редактирование ходов на доске | Не в этом этапе | новая функция; добавление идёт через PGN и «Добавить в репертуар…» |
|
||||
| Несколько своих ответов (2.3.0) | Сохранить | уже выпущено |
|
||||
| Пометки PGN и временные стрелки | Сохранить | выпущено/в работе, полезно |
|
||||
|
||||
## Границы
|
||||
|
||||
- База — `main` (2.3.0), отдельный worktree. Рабочее дерево ветки `feature/opening-repertoire-training`
|
||||
с незакоммиченными временными стрелками не трогается; при интеграции стрелки переносятся.
|
||||
- Меняются только файлы раздела в `apps/desktop/src` и минимальные дополнения ядра
|
||||
`crates/trainer/src/repertoire` (смешанная очередь «к повторению + N новых», возврат ошибки в том же
|
||||
занятии). Формат файлов, Settings-типы, `app.rs`, библиотека, экран партии, доска, Android — без изменений.
|
||||
- Мёртвый код ядра (`session.rs`, `stats.rs`, `StatsStore`) удаляется отдельной задачей после приёмки.
|
||||
|
|
@ -1,140 +0,0 @@
|
|||
# Тренировка дебюта: аудит интерфейса по реальным снимкам (2026-11-26)
|
||||
|
||||
Статус: аудит дизайнера, **не макет**. Исходный код и другие документы не менялись.
|
||||
Отчёты аналитика и разработчика (`docs/research/opening-trainer-*-2026-11-26.md`) не пересказываются.
|
||||
|
||||
## 0. Как снималось и что не снято
|
||||
|
||||
- Снимки: `target/qa-opening-rethink/shots/`, все 1400×900, тёмная тема, русский, масштаб 1.
|
||||
- Версии: **[2.2.0+]** — рабочее дерево (`f425e3a` + незакоммиченные правки); **[2.3.0]** — `main` @ `ddc8361`,
|
||||
worktree `/tmp/opencode/cp-main`, цель сборки `/tmp/opencode/cp-main-target`.
|
||||
- [2.2.0+]: `ref-01…06`, `op-01…10`, `op-12`.
|
||||
- [2.3.0]: `op-11`, `op-13`, `op-20…28`, `op-30…43`, `op-50`.
|
||||
- Изоляция: отдельные `HOME`/`XDG_*` в `/tmp/opencode/qa/prof-*`; настоящие данные пользователя не изменялись.
|
||||
Окно — вложенный Xwayland `:7`, ввод XTEST, старт состояний dev-хуками `CP_*`. Данные — два своих PGN с
|
||||
вариантами, импортированные через интерфейс.
|
||||
- **Не снято** (обрыв бюджета и ограничения стенда): 960×600; конец занятия; сброс прогресса; модальное
|
||||
«Добавить в репертуар» из партии; автопоказ подводящих ходов; кадр «верно» сразу после ответа (стенд
|
||||
задерживает события ввода — длительности пауз тоже не измерялись); HiDPI; светлая тема.
|
||||
`op-28` (вкладка «Серии») снят, но не просмотрен. По этим состояниям выводов ниже нет.
|
||||
|
||||
## 1. Подсчёты (по снимкам)
|
||||
|
||||
| Что | Сколько | Снимки |
|
||||
| --- | --- | --- |
|
||||
| Экраны раздела | 4: рабочая область, задание, статистика, «редактор» | `op-06`, `op-30`, `op-22`, `op-50` |
|
||||
| Вкладки статистики | 6 (4 видимых + 2 в меню «Дополнительно») + 2 селектора | `op-22…27` |
|
||||
| Окна и вставные формы | модальное «Параметры» (8 элементов управления, 9 абзацев пояснений); вставные формы импорта, имени, удаления; меню строки (5 пунктов); список режимов (3) | `op-09`, `op-02`, `op-11`, `op-10`, `op-08`, `op-07` |
|
||||
| Элементы управления на стартовом экране (2 репертуара) | 14: назад, настройки, цвет ×2, режим, 3 кнопки, 2 строки, 2 меню `…`, «Создать», «Импорт» + 3 строки счётчиков | `op-06` |
|
||||
| Элементы управления в задании | 4: назад, настройки, «Подсказка», переворот | `op-30` |
|
||||
| Шагов до первого хода | 2 клика, только если нужный репертуар первый по алфавиту и цвет угадан; иначе 4 (строка, цвет). С нуля: импорт → файл → «Добавить» → ожидание → цвет → «Тренироваться» = 5–6 | `op-01…06`, `op-30` |
|
||||
|
||||
## 2. Главные проблемы
|
||||
|
||||
1. **Задание не говорит, какой ход нужен.** Первый же вопрос по ни разу не виденному ходу: «Ваш ход: сыграйте
|
||||
ход из репертуара» — без показа (`op-30`, 2.3.0). Подтверждает вывод разработчика «новый ход спрашивается
|
||||
без предварительного показа». Наказание следует сразу: «Ошибка» (`op-31`).
|
||||
2. **Тексты обратной связи — язык модели, не человека.** «Повторите показанный ход; это не будет
|
||||
самостоятельным успехом» (`op-31`, причём ход в этот момент ещё не показан — стрелка появляется позже,
|
||||
`op-33`), «Ход повторён после ошибки. Самостоятельный ответ не засчитан» (`op-34`), «Ответ с подсказкой
|
||||
не считается самостоятельным» (`op-36`). Название правильного хода текстом не пишется нигде.
|
||||
3. **Блок состояния меняет высоту и вид**: одна строка (`op-30`) → две строки с красной рамкой (`op-31`) →
|
||||
две строки без рамки (`op-33`). Правая панель при этом на 85 % пустая: 700 px ниже блока не используются.
|
||||
4. **Нет прогресса занятия.** «Заданий: 2 из 51» (`op-38`) — это счёт от всего репертуара; сколько осталось
|
||||
сегодня и где конец, не видно. Под заголовком — служебное «По расписанию · Белые».
|
||||
5. **Цвет не свойство репертуара.** Репертуар за чёрных после импорта открыт с «Цвет: Белые» и предлагает
|
||||
учить ходы белых (`op-04`: 8 ходов; на 2.3.0 — 17, `op-11`). Пользователь обязан помнить и переключать.
|
||||
6. **Скрытый лимит глубины подтверждён.** Оба импортированных репертуара получили `max_plies = 20`
|
||||
(проверено в `repertoires.json` изолированного профиля); на экране это только бледная строка
|
||||
«Тренировка: часть репертуара» (`op-06`), а само число видно лишь в «редакторе»: «Глубина 20 полуходов»
|
||||
(`op-50`).
|
||||
7. **«Редактор» («Изменить») не редактирует ходы** — подтверждено: плоский список одной главной линии без
|
||||
вариантов, чекбокс глубины и «Аналитика хода» (`op-50`). Варианты, которые видны в библиотеке (4), здесь
|
||||
не найти.
|
||||
8. **Вставные формы вместо диалогов, список прыгает.** Импорт (`op-02`, `op-05`), имя (`op-11`, `op-13`),
|
||||
удаление (`op-10`) вставляются над таблицей и сдвигают её на 22–88 px; положение формы зависит от того,
|
||||
выбран ли репертуар (y=145 в `op-02`, y=323 в `op-05`). Эталоны для того же используют модальные окна.
|
||||
9. **Действие строки не привязано к объекту.** Меню `…` строки white открывается при выбранном black
|
||||
(`op-08`); вопрос «Удалить репертуар?» не называет имя (`op-10`); поле переименования white стоит над
|
||||
списком при подсвеченном black (`op-11`). Риск удалить не то.
|
||||
10. **Мигание при выборе и возврате.** На секунду и более счётчики превращаются в «Изучено … из … ходов»,
|
||||
три кнопки гаснут (`op-12`, `op-42`), затем кнопка меняет подпись на «Продолжить» (`op-43`). После
|
||||
импорта форма остаётся на экране, пока строка крутит индикатор (`op-03`) — владелец просил без спиннеров.
|
||||
11. **Строка таблицы — 158 px.** Пять строк ECO-названий на английском на репертуар; на экран входит 3–4
|
||||
репертуара (`op-06`). В библиотеке строка 27 px (`ref-01`). Имя берётся из имени файла («white»), а не
|
||||
из `Event` PGN.
|
||||
12. **Три режима и окно параметров на пути к запуску** (`op-07`, `op-09`): «По расписанию / Подряд / Сначала
|
||||
новые и давние», «Верных ответов подряд», «Дней до срока повторения», «Пропуск знакомого начала … 100».
|
||||
Окно при открытии дорастает на строку «Сбросить прогресс…» (наблюдалось на двух кадрах подряд; сохранён
|
||||
только итоговый `op-09`).
|
||||
13. **Статистика — отдельное приложение.** Пустые полноэкранные листы (`op-20`, `op-22`), повторный выбор
|
||||
репертуара и стороны, термины «Элементы», «Введено в обучение», «Отсрочка до потери подтверждения»,
|
||||
«Надёжно изучено %», «Изучено = надёжно изучено + неподтверждено» (`op-22`, `op-24`, `op-25`).
|
||||
«Ходы» — список SAN без номера и линии, с повторами «Bb3» (`op-25`); «Варианты» — список префиксов
|
||||
«1. d4», «1. d4 1… d5», а не вариантов (`op-27`); «Динамика» показывает 0/51/0, когда в обзоре уже 2 к
|
||||
повторению, ось «0–0», дата ISO (`op-23`). Две вкладки спрятаны в кнопку, похожую на вкладку (`op-26`).
|
||||
14. **Счётчики расходятся по словам и смыслу.** «Не изучались: 47 · Пора повторить: 2» (`op-43`) против
|
||||
«Ещё не изучали 47 / В процессе изучения 4 / Пора повторить 2» (`op-22`) после трёх сыгранных ходов;
|
||||
в задании тот же объект назван «Заданий».
|
||||
15. **Несогласованность с эталонами.** Доска прижата к левому краю (x=8…832, `op-06`), на экране партии она
|
||||
по центру своей области (x=54…886, `ref-02`); шапка однострочная 30 px с «← Базы» против двухстрочной
|
||||
52 px с «⬅ Библиотека» (`ref-02`, `ref-04`); правая панель 560 px против 460 px; главная и второстепенные
|
||||
кнопки одной высоты и ширины в ряд (`op-06`), в эталонах главная одна и справа внизу (`ref-03`, `ref-05`).
|
||||
Доска стартового экрана ничего не показывает — выбор репертуара её не меняет (`op-04`, `op-06`).
|
||||
|
||||
## 3. Паттерны эталонов для переиспользования
|
||||
|
||||
Номера строк — по рабочему дереву [2.2.0+]; на `main` сверить.
|
||||
|
||||
| Паттерн | Где видно | Код |
|
||||
| --- | --- | --- |
|
||||
| Шапка раздела: кнопка назад, разделитель, заголовок, «Настройки» справа | `ref-06`, `op-06` | `widgets.rs:14` `section_header`, `widgets.rs:6` `settings_button` |
|
||||
| Шапка партии: две строки (заголовок + бледная подпись), бейдж справа от заголовка | `ref-02`, `ref-04` | `game_view.rs:952` `header` |
|
||||
| Геометрия «доска + правая панель 460 px», доска по центру области | `ref-02`, `ref-04` | `game_view.rs:1217` `board_area`, `game_view.rs:1467` `side_panel` |
|
||||
| Карточка состояния в правой панели (имя, подпись «ваш ход/ждёт», активная — с заливкой) | `ref-04` | `game_view.rs:3432` `clock_card` |
|
||||
| Нижняя полоса значков 30×30 под панелью, действие («Прервать») отдельной строкой | `ref-02`, `ref-04` | `widgets.rs:127` `icon_button` |
|
||||
| Главная кнопка: заливка цвета выделения, жирный текст, высота 30; одна на экран/диалог | `ref-03`, `ref-06` | `widgets.rs:112` `primary`, `widgets.rs:117` `primary_wide` (ширина не скачет при смене подписи) |
|
||||
| Диалог: `egui::Modal`, заголовок, секции с жирным подзаголовком, бледные пояснения, «Отмена» + главная справа внизу | `ref-03`, `ref-05` | `play.rs:1256`, `prep_ui.rs:534`, `own_db.rs:143` |
|
||||
| Подтверждение опасного действия — модальное, с именем объекта | — (по коду) | `own_db.rs:806`, `app.rs:2196` |
|
||||
| Сегментный выбор из 2–3 значений плашками (Белые / Случайно / Чёрные) | `ref-03` | `play.rs:1256` и ниже (там же сетка контролей) |
|
||||
| Таблица: строка 27 px, чередование фона, сортируемые заголовки, выделение заливкой | `ref-01`, `ref-06` | `large_db.rs:2106`, `prep_ui.rs:4052` (`TableBuilder`), `widgets.rs:64` `sort_header` |
|
||||
| Пустое состояние: бледный текст по центру + одна главная кнопка | `ref-06` | `prep_ui.rs:4761` |
|
||||
| Вкладки-плашки над содержимым панели | `ref-02`, `ref-06` | `game_view.rs:221` (`side_tab`), `prep_ui.rs:1703` |
|
||||
| Строка-сводка бледным под заголовком («PGN, кодировка UTF-8 · 100 партий») | `ref-01` | `library.rs:1466` `header` |
|
||||
| Типографика: заголовок `heading`, основной текст 14, пояснения `weak()`, предупреждение оранжевым | `ref-03`, `ref-06` | `docs/design/design-system.md` |
|
||||
|
||||
## 4. Предварительные принципы нового раздела
|
||||
|
||||
1. Два экрана: «репертуары» и «занятие». Статистика и «редактор» как отдельные экраны исчезают.
|
||||
2. Занятие повторяет экран игры с компьютером: та же шапка, доска по центру, панель 460 px, карточка
|
||||
состояния фиксированной высоты, полоса значков снизу. Ничего нового не изобретать.
|
||||
3. Блок «что делать сейчас» — одного размера во всех состояниях; текст называет ход («Правильно: Сb5»),
|
||||
цвет рамки не единственный признак ошибки.
|
||||
4. Новый ход сначала показан (стрелка + подпись), потом спрашивается.
|
||||
5. В занятии виден остаток («Осталось N»), а не доля всего репертуара.
|
||||
6. Цвет задаётся один раз при создании или импорте и хранится в репертуаре; на пути к запуску — одна кнопка.
|
||||
7. Все вопросы и формы (импорт, имя, удаление, сброс) — `egui::Modal` с именем объекта. Список никогда не
|
||||
сдвигается.
|
||||
8. Строка репертуара — одна, 27 px: имя, цвет, «повторить сегодня», «выучено X из Y». ECO-названия — в
|
||||
карточке выбранного или в подсказке.
|
||||
9. Одни и те же слова для одних и тех же чисел на всех экранах; ни одного из терминов п. 2.2 и 2.13.
|
||||
10. Никаких переходных «…» и гаснущих кнопок: до готовности данных показывается прежнее значение.
|
||||
|
||||
## 5. Замечания к концепции (`opening-trainer-concept-2026-11-26.md`)
|
||||
|
||||
- **«Одна строка состояния сверху»** — на эталоне игры состояние живёт в карточке правой панели
|
||||
(`ref-04`), а не над доской. Предлагаю карточку в панели; иначе доска занятия сместится относительно
|
||||
экрана партии.
|
||||
- **«Таблица в стиле библиотеки» + карточка выбранного** — в панели 460 px таблица библиотеки с 4 колонками
|
||||
не поместится без обрезания; нужна проверка прототипом на 960×600 (панель там уже). Число колонок — не
|
||||
больше трёх.
|
||||
- **Меню `⋯` из семи пунктов** прячет две функции («Повторить всё подряд», «Просмотр вариантов»), а
|
||||
остальные — служебные. Меню должно действовать на выбранную строку и только на неё (сейчас это нарушено,
|
||||
`op-08`); «Просмотр вариантов» лучше дать видимой второстепенной кнопкой карточки.
|
||||
- **«Сменить цвет» в меню** — нужен и момент первого выбора: импорт сейчас молча ставит «Белые» (`op-04`).
|
||||
Определять по PGN или спрашивать в диалоге импорта.
|
||||
- **Конец занятия: две кнопки** — главная одна («К репертуару» или «Ещё 10 новых» — решить), вторая обычная.
|
||||
- **Доска на экране репертуаров** сейчас декоративна (`op-06`). Либо она показывает позицию выбранного
|
||||
варианта, либо её стоит обосновать заново.
|
||||
- **Снятие `max_plies` при загрузке** увеличит «Y» у существующих репертуаров — в карточке это не должно
|
||||
выглядеть как потеря прогресса.
|
||||
|
|
@ -1,470 +0,0 @@
|
|||
# Тренировка дебюта v2: спецификация интерфейса (2026-11-26)
|
||||
|
||||
Основание: `opening-trainer-concept-2026-11-26.md` (продуктовые решения не пересматриваются),
|
||||
`opening-trainer-ui-audit-2026-11-26.md` (снимки `ref-*`, `op-*`). Номера строк — по этому worktree
|
||||
(`feature/opening-trainer-v2`, 2.3.0). Тексты: EN — ключ `tr("…")`, RU — строка `i18n.rs`; остальные
|
||||
четыре языка — по образцу. Размеры в pt при масштабе 1.
|
||||
|
||||
Задача раздела одной фразой: **выбрать репертуар и одной кнопкой начать занятие, в котором в каждый момент
|
||||
написано, что делать, и виден конец**.
|
||||
|
||||
Три экрана: **Репертуары** (§2–3), **Занятие** (§4–6), **Варианты** (§6.3). Диалоги — §7. Других экранов,
|
||||
окон и вкладок нет.
|
||||
|
||||
## 1. Компоновка (общая для трёх экранов)
|
||||
|
||||
Все три экрана используют один каркас. Переход между ними не меняет ни прямоугольник доски, ни ширину панели.
|
||||
|
||||
| Область | 1400×900 | 960×600 | Как сделать |
|
||||
| --- | --- | --- | --- |
|
||||
| Шапка | высота 52 (y 0…52) | 52 | Две строки, как у партии (`ref-02`, `ref-04`): строка 1 — кнопка «назад», разделитель, заголовок `heading` с обрезкой, справа `settings_button`; строка 2 — бледная подпись с обрезкой. `GameView::header` (`game_view.rs:952`) закрыт и связан с партией, поэтому: **новая** функция `widgets::section_header_sub(ui, back, title, subtitle) -> (bool, bool)` рядом с `section_header` (`widgets.rs:14`), повторяющая отступы `game_view.rs:958` (`add_space(4)`) и строку подписи `game_view.rs:1151`. Существующие функции не менять. |
|
||||
| Правая панель | ширина 460 (x 940…1400) | 384 | `egui::Panel::right("opening_side")`, один id на все три экрана. Формула партии, `game_view.rs:788–800`: `default_size((width*0.4).clamp(260.0, 460.0).min(room))`, `room = (width - board - 24).clamp(least, most)`, `resizable(true)`, `size_range(least..=most)`, `least = 320` (как `REF_MIN`, `game_view.rs:5001`), `most = (width - 220 - 24).max(least)`. После — `widgets::check_panel` (`widgets.rs:36`). |
|
||||
| Доска | квадрат 832, x 54…886, y 60…892 | квадрат 532, x 22…554, y 60…592 | `CentralPanel`; квадрат по центру области, формула `game_view.rs:1250–1253`. Виджет `BoardView::show` (`board.rs:169`, `:194`) с настройками доски пользователя. Полосы оценки нет. |
|
||||
| Узкое/высокое окно | — | — | Правило партии `game_view.rs:761–763`: если `board_stack >= 1.25 * board_side` — доска сверху, панель снизу высотой ≥ 300 (`STACK_BOTTOM_MIN`). Текущее собственное правило `learning_training.rs:1530` (`width < 900 && height > width`) удалить. |
|
||||
|
||||
Внутренние поля панели: стандартные egui (как у партии), между блоками 6. Никаких новых цветов, рамок и
|
||||
шрифтов: заливка выделения — `visuals.selection.bg_fill`, рамки — `widgets.noninteractive.bg_stroke`,
|
||||
ошибка — `visuals.error_fg_color`, предупреждение — `visuals.warn_fg_color`.
|
||||
|
||||
Общие компоненты:
|
||||
|
||||
| Нужно | Брать |
|
||||
| --- | --- |
|
||||
| Главная кнопка (одна на экран/диалог) | `widgets::primary_wide` (`widgets.rs:117`), высота 30, фиксированная ширина |
|
||||
| Обычная кнопка | `ui.button`, в ряду с главной — `min_size(vec2(0, 30))` |
|
||||
| Значки нижней полосы 28 pt | замыкание `icon` из `play_toolbar` (`game_view.rs:3563–3564`), переворот — `game_view.rs:3582` |
|
||||
| Карточка состояния | рамка `clock_card` (`game_view.rs:3451–3463`): `inner_margin(10, 6)`, радиус 4, обводка 1; активная — заливка `sel.bg_fill.gamma_multiply(0.35)`; ошибка — обводка 1.5 `error_fg_color` |
|
||||
| Плашки выбора из двух значений | замыкание `choice` (`play.rs:1283–1289`): `Button::selectable(..).frame_when_inactive(true)` |
|
||||
| Заголовок секции диалога | `play.rs:1280` (`strong().size(15.0)`) |
|
||||
| Диалог | `egui::Modal`, `ui.set_width(460.0)`, `ui.heading`, как `game_view.rs:3261–3263`; вопрос с опасным действием — как `app.rs:2196`, `own_db.rs:806` |
|
||||
| Таблица | `TableBuilder`, настройки `large_db.rs:2106–2111`, заголовок 26 (`:2146`), строка 24 (`:2160`) |
|
||||
| Пустое состояние | `prep_ui.rs:4760` (бледный текст по центру + одна `primary`) |
|
||||
| Дерево ходов | `Notation` (`notation.rs:13`, `show` — `:189`) с `read_only: true` |
|
||||
|
||||
## 2. Экран «Репертуары»: таблица
|
||||
|
||||
Шапка: назад «⬅ Library / ⬅ Библиотека»; заголовок «Opening training / Тренировка дебюта» (пометку
|
||||
«(α version)» сохранить до решения владельца — одна строка `repertoire_ui.rs:1035`); подпись
|
||||
«{n} repertoires / Репертуаров: {n}», при пустом списке подписи нет.
|
||||
|
||||
Панель сверху вниз: карточка выбранного (§3, фиксированная высота 166) · поле поиска (только если
|
||||
репертуаров > 8, высота 24, подсказка «Search / Поиск») · таблица (всё оставшееся, прокрутка) · полоса
|
||||
сообщения (высота 20, всегда зарезервирована, §7.6) · нижний ряд (высота 30): «Import PGN… / Импорт PGN…»,
|
||||
«New repertoire / Новый репертуар» — обычные кнопки одинаковой ширины 150.
|
||||
|
||||
Колонки (ширина панели 384 → на название остаётся ≥ 150):
|
||||
|
||||
| Колонка | Ширина | Содержимое |
|
||||
| --- | --- | --- |
|
||||
| «Name / Название» | остаток, обрезка «…», полный текст в подсказке | имя репертуара |
|
||||
| (без заголовка) | 22 | король цвета: ♔ / ♚; подсказка «You play White / Вы играете белыми» (… Black / чёрными) |
|
||||
| «Today / Сегодня» | 58, вправо | `повторить + новые` одним числом; 0 → «—» бледно. Подсказка: «{n} to review, {m} new / Повторить: {n}, новых: {m}» |
|
||||
| «Learned / Выучено» | 70, вправо | «34/120»; пустой репертуар → «—» |
|
||||
| (без заголовка) | 26 | кнопка `⋯` |
|
||||
|
||||
- Строка 24, чередование фона, выделение — заливка выделения на всю строку (как библиотека, `ref-01`).
|
||||
Порядок — по имени, без сортировки по клику.
|
||||
- Клик — выбрать (карточка и доска обновляются). Двойной клик или Enter — то же, что главная кнопка карточки.
|
||||
↑/↓ — соседняя строка, выбранная строка прокручивается в видимую область.
|
||||
- Пока строка считается в фоне, в «Сегодня» и «Выучено» — прежние значения; если их ещё не было — «…».
|
||||
Индикаторов вращения нет.
|
||||
- Доска экрана: позиция **после общего начала репертуара** (последний ход до первого разветвления), с
|
||||
подсветкой последнего хода, перевёрнута для чёрных; ввода нет. Пустой репертуар и пустой список —
|
||||
начальная позиция.
|
||||
|
||||
Меню `⋯` (также правый клик по строке). Открытие меню **выбирает эту строку**; все пункты действуют на неё.
|
||||
|
||||
| № | EN | RU | Примечание |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | Train | Тренироваться | = главная кнопка; недоступно, если ходов нет |
|
||||
| 2 | Review all lines | Повторить всё подряд | §6.1 |
|
||||
| 3 | Lines… | Варианты… | §6.3 |
|
||||
| — | | | разделитель |
|
||||
| 4 | Rename… | Переименовать… | §7.3 |
|
||||
| 5 | Play as Black / Play as White | Играть чёрными / Играть белыми | показан противоположный текущему; §7.4 |
|
||||
| 6 | Add PGN to this repertoire… | Добавить PGN в этот репертуар… | §7.1 |
|
||||
| 7 | Export PGN… | Экспорт PGN… | системный диалог, как сейчас (`repertoire_ui.rs:799`) |
|
||||
| — | | | разделитель |
|
||||
| 8 | Reset progress… | Сбросить прогресс… | §7.5 |
|
||||
| 9 | Delete… | Удалить… | §7.5 |
|
||||
|
||||
Пустой список: карточки и таблицы нет; по центру панели (вертикально тоже) —
|
||||
заголовок «No repertoires yet / Репертуаров пока нет», бледный текст «A repertoire is your opening moves as a
|
||||
PGN with variations. Import a file, or open any game, pick a move and choose “Add to repertoire…”. /
|
||||
Репертуар — это ваши дебютные ходы в PGN с вариантами. Импортируйте файл или откройте любую партию,
|
||||
выберите ход и нажмите «Добавить в репертуар…».», под ним `primary` «Import PGN… / Импорт PGN…» и обычная
|
||||
«New repertoire / Новый репертуар». Нижний ряд в этом состоянии скрыт (кнопки не дублируются).
|
||||
|
||||
## 3. Карточка выбранного репертуара
|
||||
|
||||
Рамка как у `clock_card` без заливки, высота 166 во всех состояниях (строки не появляются и не исчезают —
|
||||
пустая строка остаётся пустой).
|
||||
|
||||
| Строка | Высота | Содержимое |
|
||||
| --- | --- | --- |
|
||||
| 1 | 26 | имя (`heading`, обрезка) · справа бледно «♔ You play White / ♔ Вы играете белыми» (♚ … Black / чёрными) |
|
||||
| 2 | 22 | **сегодня** (strong 15), тексты ниже |
|
||||
| 3 | 8 + 20 | полоса прогресса высотой 8 во всю ширину: сегмент «выучено» — цвет выделения, сегмент «учится» — тот же цвет с `gamma_multiply(0.45)`, остаток — фон поля; под ней «Learned {x} of {y} moves / Выучено {x} из {y} ходов», справа бледно «{k} in progress / учится: {k}» (скрыто при k = 0) |
|
||||
| 4 | 20 | бледная строка пояснения (тексты ниже) |
|
||||
| 5 | 30 | главная кнопка (ширина 170) · «Lines / Варианты» (ширина 110) · место третьей кнопки (ширина 150) |
|
||||
|
||||
Определения чисел (из ядра, без новых понятий): `y` — свои ходы репертуара за его цвет; `x` — ходы со
|
||||
статусом ядра «изучено»; `k` — ходы, которые уже спрашивали, но ещё не «изучено»; «повторить» — ходы со
|
||||
сроком сегодня или раньше; «новых» — `min(10, ещё не показанные)`.
|
||||
|
||||
Состояния (строка 2 · строка 4 · кнопки):
|
||||
|
||||
| Состояние | Строка 2 (EN / RU) | Строка 4 (EN / RU) | Главная | Третья кнопка |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Есть повторения (и, возможно, новые) | «Today: {n} to review · {m} new» / «Сегодня: {n} повторить · {m} новых» (часть с нулём опускается) | «About {t} min» / «Примерно {t} мин» (20 с на ход, округление вверх; < 1 мин не показывать) | **Train / Тренироваться** | — |
|
||||
| Повторять нечего, есть новые | «Today: {m} new moves» / «Сегодня: {m} новых ходов» | «Nothing to review today» / «Повторять сегодня нечего» | **Learn {m} new / Учить {m} новых** | «Review all lines / Повторить всё подряд» |
|
||||
| Всё показано, до повторения есть время | «Done for today» / «На сегодня всё» | «Next review: {when} · {n} moves» / «Следующее повторение: {when} · ходов: {n}» | **Review all lines / Повторить всё подряд** | — |
|
||||
| Всё выучено и повторений в расписании нет (теоретически) | «Done for today» / «На сегодня всё» | пусто | **Review all lines / Повторить всё подряд** | — |
|
||||
| Репертуар пустой | «No moves yet» / «Ходов пока нет» | «Add a PGN, or use “Add to repertoire…” in any game» / «Добавьте PGN или нажмите «Добавить в репертуар…» в любой партии» | **Add PGN… / Добавить PGN…** | — |
|
||||
| В репертуаре нет ходов за выбранный цвет | «No moves for White here» / «Здесь нет ходов за белых» (… Black / чёрных) | «This PGN may be a repertoire for the other colour» / «Возможно, это репертуар за другой цвет» | **Play as Black / Играть чёрными** (или белыми) | — |
|
||||
| Индексация в фоне, прежние числа есть | прежние значения | прежняя строка | прежняя, доступна | прежняя |
|
||||
| Индексация в фоне, чисел ещё не было | «Counting moves…» / «Считаем ходы…» | пусто | **Train / Тренироваться**, недоступна, подсказка «Counting moves… / Считаем ходы…» | — |
|
||||
| Ошибка чтения репертуара | «Cannot read this repertoire» / «Не удалось прочитать репертуар» (цвет предупреждения) | текст ошибки с обрезкой, полный в подсказке | **Try again / Повторить** | — |
|
||||
|
||||
`{when}`: «today at 18:40 / сегодня в 18:40», «tomorrow / завтра», «in {d} days / через {d} дн.», далее дата
|
||||
в формате библиотеки (`ДД.ММ.ГГГГ`).
|
||||
|
||||
Тупиков нет: в любом состоянии главная кнопка что-то делает; «Повторить всё подряд» всегда есть в меню `⋯`.
|
||||
Кнопка «Варианты» недоступна только у пустого репертуара. Подпись главной кнопки меняется только при смене
|
||||
состояния данных; ширина фиксирована.
|
||||
|
||||
## 4. Экран «Занятие»
|
||||
|
||||
### 4.1. Шапка и панель
|
||||
|
||||
Шапка: назад «⬅ Repertoires / ⬅ Репертуары» (при ширине < 600 — «⬅»); заголовок — имя репертуара; подпись —
|
||||
вид занятия: «Training · you play White / Тренировка · вы играете белыми» (см. §6 для других видов).
|
||||
|
||||
Панель сверху вниз, **все высоты постоянны**:
|
||||
|
||||
| Блок | Высота | Содержимое |
|
||||
| --- | --- | --- |
|
||||
| A. Карточка состояния | 64 | слева две строки: заголовок (strong 15) и указание (обычный 13, обрезка; полный текст в подсказке); справа счётчик: число моноширинным 24 и под ним бледная подпись 11. Рамка и заливка по §1 |
|
||||
| B. Дебют | 20 | бледно, обрезка: «C84 · Ruy Lopez: Closed» — код и название текущей позиции из той же базы названий, что сейчас в библиотеке (`repertoire_ui.rs:1297`); если позиция вне базы — последнее известное название; до первого хода пусто |
|
||||
| C. Путь | 20 | бледно, одна строка, обрезка **слева** («… 4. Ba4 Nf6 5. O-O Be7»): ходы до текущей позиции в нотации приложения (`san::show`). Спрашиваемый ход в строку не входит, пока не сыгран. Клики не обрабатываются |
|
||||
| D. Комментарий | остаток, прокрутка внутри | заголовок-ход (strong): номер, ход, значок NAG цветом `notation::assessment_text_color` (`notation.rs:709`); ниже текст комментария PGN (`notation::comment_text`, `notation.rs:748`). Правила — §4.4. Пусто — пустая область, без «нет комментария» |
|
||||
| E. Действия | 30 | слева обычная «Hint (H) / Подсказка (H)» шириной 150; справа место главной кнопки шириной 170 (обычно пусто) |
|
||||
| F. Полоса | 28 + разделитель | значок переворота с подсказкой «Flip board (F) / Перевернуть доску (F)»; справа «× Finish / × Закончить» (как «× Прервать», `ref-04`) |
|
||||
|
||||
Доска: стрелки и кружки PGN, значок-бейдж хода — как в 2.3.0 (`learning_training.rs:1206–1265`), временные
|
||||
стрелки пользователя сохраняются. Стрелка-подсказка — существующая зелёная (`op-33`, `op-36`).
|
||||
|
||||
### 4.2. Машина состояний
|
||||
|
||||
Счётчик в обычном занятии: число = сколько вопросов осталось в этом занятии (включая возвращённые ошибки),
|
||||
подпись «left / осталось». Число уменьшается только после верного самостоятельного ответа или сыгранного
|
||||
нового хода; при ошибке не меняется (ход вернётся).
|
||||
|
||||
| Состояние | Когда | Заголовок EN / RU | Указание EN / RU | Рамка | Доска, кнопки |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| S0 Подготовка | до первого кадра занятия, только если дольше 300 мс | Preparing… / Готовим занятие… | — | обычная | ввод закрыт; счётчик «—» |
|
||||
| S1 Подвод | программа проигрывает ходы до вопроса (ходы соперника и уверенно известные свои) | Watch / Смотрите | Moves up to your next question / Ходы до вашего следующего вопроса | обычная | ввод закрыт; «Подсказка» недоступна; главная справа: «Skip (Enter) / Пропустить (Enter)» — обычная кнопка, сразу ставит позицию вопроса |
|
||||
| S2 Новый ход | ход ни разу не показывали | New move / Новый ход | Play {san} — it is shown by the arrow / Сыграйте {san} — он показан стрелкой | активная заливка | стрелка сразу; комментарий хода виден (§4.4); «Подсказка» недоступна |
|
||||
| S3 Ваш ход | повторение | Your move / Ваш ход | Play the move from your repertoire / Сыграйте ход из репертуара | активная заливка | стрелки нет; «Подсказка» доступна |
|
||||
| S3a Ваш ход, ответов несколько | в позиции несколько своих ходов (2.3.0) | Your move / Ваш ход | Play {san}'s alternative: one more move here / Здесь есть ещё один ваш ход, не {san} | активная заливка | показывается, когда спрашивается не первый из ответов; уже сыгранные перечисляются через запятую |
|
||||
| S4 Верно | верный самостоятельный ответ | Correct / Верно | {n}. {san} | обычная, заголовок цветом оценки «хороший ход» (`notation::assessment_text_color` для `!`) | 600 мс после анимации, затем S1/S2/S3 следующего вопроса или S8; ввод закрыт |
|
||||
| S5 Неверно | сыгран не тот ход | Not this move / Не тот ход | Correct: {san}. Play it / Правильно: {san}. Сыграйте его | обводка 1.5 `error_fg_color` | фигура возвращается (существующая анимация), сразу стрелка верного хода; ждём ход пользователя; «Подсказка» недоступна. Другой неверный ход — состояние остаётся, фигура возвращается |
|
||||
| S5a Ход есть в репертуаре, но спрашивается другой | сыгран другой свой ход этой позиции | This one is in your repertoire too / Этот ход тоже есть в репертуаре | Now the other one: play {san} / Сейчас нужен другой: сыграйте {san} | обычная | ошибкой **не считается**; стрелка на нужный ход |
|
||||
| S6 После показа | сыгран ход, показанный в S5 или S7 | Got it / Запомним | {n}. {san} will come back in this session / {n}. {san} вернётся в этом занятии | обычная | 600 мс, далее следующий вопрос |
|
||||
| S7 Подсказка | нажата «Подсказка» в S3 | Hint / Подсказка | Play {san}. It will come back in this session / Сыграйте {san}. Ход вернётся в этом занятии | обычная | стрелка; после хода — S6 |
|
||||
| S9 Ошибка записи | ответ не сохранился | Could not save your answer / Не удалось сохранить ответ | текст ошибки, обрезка, полный в подсказке | обводка 1.5 `error_fg_color` | ввод закрыт; в E: главная «Try again / Повторить», слева вместо «Подсказки» — «Finish / Закончить» |
|
||||
| S8 Итог | вопросы кончились | §5 | | | |
|
||||
|
||||
Обычное сохранение ответа не показывается никак (решение 05.11). Доска после отпускания фигуры сразу
|
||||
показывает сыгранный ход (поведение 2.2.0 сохраняется).
|
||||
|
||||
Все `{san}` — в нотации приложения (буквы фигур по настройке языка), с номером хода там, где указано `{n}.`.
|
||||
|
||||
### 4.3. Клавиши и выход
|
||||
|
||||
| Клавиша | Действие | Сверка |
|
||||
| --- | --- | --- |
|
||||
| H | подсказка (S3) | как сейчас, `learning_training.rs:1136` |
|
||||
| F | перевернуть доску | как в партии и игре, `game_view.rs:3583` |
|
||||
| Enter, Space | S1 — пропустить подвод; S8 — «К репертуару»; S9 — «Повторить» | Enter на итоге уже есть, `learning_training.rs:1142` |
|
||||
| N | S8 — «Ещё 10 новых» | новая, только на итоге |
|
||||
| Esc, Ctrl+W | закончить занятие и вернуться к репертуарам | как сейчас, `:1130–1131`; Ctrl+W — «в библиотеку» у партии |
|
||||
| Ctrl+, | общие настройки, занятие не сбрасывается | решение 05.11 |
|
||||
|
||||
Клавиши не действуют, пока открыт модальный диалог или поле ввода (правило `game_view.rs:4776–4783`).
|
||||
Удаляются: Space/P — пауза автопоказа, Esc — отмена автопоказа (`:1124–1128`), L и Shift+A (`:1138–1139`).
|
||||
|
||||
Выход посреди занятия (Esc, Ctrl+W, «⬅ Репертуары», «× Закончить»): **без вопроса**, сразу на экран
|
||||
«Репертуары» — каждый ответ уже записан, терять нечего; текущий неотвеченный вопрос не засчитывается.
|
||||
Если запись в процессе — выход после её завершения (как сейчас, Esc ждёт `!board.is_busy()`). Если
|
||||
отвечен хотя бы один вопрос, вместо мгновенного выхода показывается итог §5 с заголовком «Session stopped /
|
||||
Занятие прервано» — человек видит, что сделанное сохранено. Незаконченное занятие не возобновляется
|
||||
(концепция): кнопка карточки начинает новое.
|
||||
|
||||
### 4.4. Комментарии и значки PGN
|
||||
|
||||
- Значок NAG хода (`!`, `?`, `!?` …) пишется рядом с ходом в блоке D и в указании S4/S6; бейдж на доске — как
|
||||
в 2.3.0.
|
||||
- В блоке D всегда комментарий **последнего хода на доске**; у хода соперника — его комментарий (он
|
||||
объясняет позицию вопроса).
|
||||
- Комментарий **спрашиваемого** хода в S3 не показывается (он подсказывает ответ). Он появляется в S2
|
||||
(сразу), в S5 и S7 (вместе со стрелкой), в S4/S6 (после хода) и остаётся до следующего комментария, с
|
||||
заголовком-ходом, чтобы было видно, к чему он относится.
|
||||
- Комментарий перед первым ходом партии PGN показывается в начале подвода.
|
||||
- Перевод комментариев и их редактирование — нет (не этот этап).
|
||||
|
||||
## 5. Итог занятия (S8)
|
||||
|
||||
Доска остаётся на последней позиции, ввода нет. Панель: блоки A–C и F на местах и тех же высот; блок D
|
||||
занят итогом; блок E — кнопки.
|
||||
|
||||
- A: заголовок «Session complete / Занятие окончено» (при досрочном выходе — «Session stopped / Занятие
|
||||
прервано»), указание «Everything is saved / Всё сохранено»; счётчик «0», при досрочном — остаток.
|
||||
- D, строки по 22, подпись слева, число справа (колонка 60):
|
||||
- «Correct first time / Верно с первого раза» — {a}
|
||||
- «Mistakes / Ошибок» — {b}
|
||||
- «Hints / Подсказок» — {h} (строка скрыта при 0)
|
||||
- «New moves learned / Новых ходов» — {m} (скрыта при 0)
|
||||
- разделитель
|
||||
- «Next review / Следующее повторение» — {when} (§3); если что-то осталось на сегодня — «today, {n} more /
|
||||
сегодня, ещё {n}»
|
||||
- если были ошибки — подзаголовок «Moves to remember / Что запомнить» и до 8 строк «{n}. {san}» с путём
|
||||
бледно («после 2… Nc6»: «after {path} / после {path}»); больше 8 — «and {k} more / и ещё {k}».
|
||||
- E: главная справа — **«To repertoires (Enter) / К репертуарам (Enter)»**; слева обычная «10 more new (N) /
|
||||
Ещё 10 новых (N)» (число — сколько реально осталось, максимум 10; скрыта, если новых нет или вид занятия —
|
||||
§6).
|
||||
|
||||
## 6. Другие виды занятия и экран «Варианты»
|
||||
|
||||
### 6.1. «Повторить всё подряд»
|
||||
|
||||
Тот же экран и те же состояния. Отличия:
|
||||
|
||||
- подпись шапки: «Review all lines · you play White / Повторение подряд · вы играете белыми»;
|
||||
- счётчик карточки A: число «{k}/{n}», подпись «line / вариант»; `n` — число вариантов (листьев дерева с
|
||||
учётом выключенных веток), `k` — текущий;
|
||||
- спрашивается **каждый** свой ход варианта, уверенно известные не пропускаются; ход, которого ещё не
|
||||
показывали, идёт как S2;
|
||||
- между вариантами S1 с заголовком «Next line / Следующий вариант» и указанием «{k} of {n} / {k} из {n}»;
|
||||
общее начало с предыдущим вариантом не проигрывается заново (поведение 05.11 сохраняется);
|
||||
- ошибочный ход повторяется сразу (S5→S6) и в этом занятии не возвращается;
|
||||
- ответы записываются в расписание, как в обычном занятии;
|
||||
- итог: первая строка «Lines reviewed / Пройдено вариантов» — {k} из {n}; кнопки «Ещё 10 новых» нет.
|
||||
|
||||
### 6.2. «Тренировать эту ветку»
|
||||
|
||||
Как §6.1, но только варианты, проходящие через выбранный ход. Подпись шапки:
|
||||
«Branch: {path} / Ветка: {path}» (путь с обрезкой слева). Назад и «× Закончить» возвращают на экран
|
||||
«Варианты» с тем же выбранным ходом; Enter на итоге — туда же («To lines / К вариантам»).
|
||||
|
||||
### 6.3. Экран «Варианты»
|
||||
|
||||
Задача: посмотреть, что в репертуаре, и выбрать, что тренировать. Ходы не редактируются.
|
||||
|
||||
Шапка: назад «⬅ Repertoires / ⬅ Репертуары»; заголовок — имя; подпись «Lines · {n} lines · {y} your moves /
|
||||
Варианты · вариантов: {n} · ваших ходов: {y}».
|
||||
|
||||
Панель:
|
||||
|
||||
| Блок | Высота | Содержимое |
|
||||
| --- | --- | --- |
|
||||
| Дебют | 20 | как блок B занятия, для выбранной позиции |
|
||||
| Дерево | остаток, прокрутка | `Notation { game: &дерево репертуара, cursor: выбранный ход, scroll_to_cursor: true при смене хода с клавиатуры, read_only: true, marks/preview/translations/editor/dim_until/mistakes: None }` (`notation.rs:13–33`). Клик — `NotationResponse::clicked` (`:37`). Комментарии и NAG рисует сам компонент |
|
||||
| Выбранный ход | 92 | рамка как у карточки; строка 1 — путь до хода (strong, обрезка слева); строка 2 бледно — «Below: {n} lines · {y} your moves · learned {x} / Дальше: вариантов {n} · ваших ходов {y} · выучено {x}»; у выключенной ветки строка 2 — «Not trained / Не тренируется» цветом предупреждения; строка 3 — кнопки: главная «Train this branch / Тренировать эту ветку» (170), обычная «Don't train / Не тренировать» ↔ «Train again / Снова тренировать» (170) |
|
||||
| Полоса | 28 | `⏮ ◀ ▶ ⏭` и переворот — как `play_toolbar` (`game_view.rs:3567–3583`) |
|
||||
|
||||
- Доска: позиция выбранного хода, подсветка последнего хода, стрелки/кружки PGN; перевёрнута для чёрных;
|
||||
ввода нет.
|
||||
- Ничего не выбрано (начало): строка 1 — «Start position / Начальная позиция», главная —
|
||||
«Review all lines / Повторить всё подряд», вторая кнопка скрыта.
|
||||
- «Не тренировать» выключает ветку от выбранного хода (существующие `disabled_prefixes`), действует сразу,
|
||||
отменяется той же кнопкой; числа карточки пересчитываются в фоне. У хода соперника и у своего хода
|
||||
действует одинаково.
|
||||
- Клавиши как у партии: ←/→ ход, ↑/↓ соседний вариант, Home/End, F — переворот, Enter — главная кнопка,
|
||||
Esc/Ctrl+W — назад.
|
||||
- **Отметка выключенных веток в дереве.** `Notation` не умеет приглушать поддерево (`dim_until` — только
|
||||
главная линия по номеру полухода). Нужна аддитивная правка `notation.rs`: поле
|
||||
`muted: Option<&HashSet<NodeId>>` по образцу `mistakes` (`:32`) — ходы из множества рисуются `weak` и
|
||||
зачёркнутыми. Это выход за границу «только файлы раздела»; до согласования оркестратора — без отметки в
|
||||
дереве, состояние видно только в блоке выбранного хода.
|
||||
|
||||
## 7. Диалоги
|
||||
|
||||
Все — `egui::Modal`, ширина 460, `heading`, кнопки справа внизу: «Cancel / Отмена», затем главная. Enter —
|
||||
главная (кроме опасных, где Enter = «Отмена»), Esc — отмена. Таблица под диалогом не сдвигается.
|
||||
|
||||
### 7.1. Импорт PGN
|
||||
|
||||
Сначала системный выбор файла (`rfd`, как `repertoire_ui.rs:753`), затем диалог «Import PGN / Импорт PGN»:
|
||||
|
||||
- «Name / Название» — поле (до 120 знаков); по умолчанию — тег `Event` первой партии, если он не пустой и не
|
||||
«?», иначе имя файла без расширения.
|
||||
- «You play / Вы играете» — две плашки `choice` шириной 222, высотой 34: «♔ White / ♔ Белыми», «♚ Black /
|
||||
♚ Чёрными». Предвыбор: цвет, у которого в дереве меньше позиций с несколькими ходами (свои ходы обычно
|
||||
единственные); при равенстве — белые. Под плашками бледно: «Chosen from the PGN — check it / Выбрано по
|
||||
PGN — проверьте».
|
||||
- Сводка бледно: «{g} games · {v} lines · {y} your moves / Партий: {g} · вариантов: {v} · ваших ходов: {y}»
|
||||
— `y` пересчитывается при смене цвета.
|
||||
- Предупреждения (цвет предупреждения, до 3 строк, остальное — «and {k} more / и ещё {k}»): нераспознанные
|
||||
ходы, партии без ходов.
|
||||
- Кнопки: «Cancel / Отмена», главная «Import / Импортировать» (недоступна при пустом имени или `y = 0`;
|
||||
подсказка «No moves for this colour / Нет ходов за этот цвет»).
|
||||
- Пока файл читается: вместо сводки «Reading the file… / Читаем файл…», главная недоступна.
|
||||
- После импорта диалог закрывается, новый репертуар выбран.
|
||||
|
||||
«Добавить PGN в этот репертуар…»: заголовок «Add PGN to “{name}” / Добавить PGN в «{name}»», без полей имени
|
||||
и цвета; сводка «{m} new moves · {v} new lines / Новых ходов: {m} · новых вариантов: {v}»; при `m = 0` —
|
||||
«Nothing new in this file / В файле нет новых ходов», главная недоступна. Главная — «Add / Добавить».
|
||||
|
||||
Окно «Добавить в репертуар…» из партии (`repertoire_ui.rs:1987`) остаётся как есть; при создании нового
|
||||
репертуара в нём добавляются те же плашки цвета (предвыбор — сторона, чей ход выбран в партии).
|
||||
|
||||
### 7.2. Новый репертуар
|
||||
|
||||
«New repertoire / Новый репертуар»: поле названия, плашки цвета (предвыбор — белые), бледно: «Moves are added
|
||||
from a PGN file or with “Add to repertoire…” in any game. / Ходы добавляются из PGN-файла или кнопкой
|
||||
«Добавить в репертуар…» в любой партии.» Главная — «Create / Создать». Ошибка имени (пустое, занято) —
|
||||
строка цветом предупреждения под полем, место под неё зарезервировано.
|
||||
|
||||
### 7.3. Переименование
|
||||
|
||||
«Rename repertoire / Переименовать репертуар»: поле с текущим именем, выделенным целиком; главная —
|
||||
«Save / Сохранить»; та же строка ошибки.
|
||||
|
||||
### 7.4. Смена цвета
|
||||
|
||||
«Play “{name}” as Black? / Играть «{name}» чёрными?» (или белыми). Текст: «You will be asked Black's moves:
|
||||
{y}. Progress for White is kept and comes back if you switch again. / Спрашиваться будут ходы чёрных: {y}.
|
||||
Прогресс за белых сохранится и вернётся, если переключить обратно.» Главная — «Switch / Переключить».
|
||||
|
||||
### 7.5. Сброс прогресса и удаление
|
||||
|
||||
Опасные: главной (залитой) кнопки нет, обе кнопки обычные, фокус и Enter — на «Отмена» (образец
|
||||
`app.rs:2196`).
|
||||
|
||||
**Сброс.** Заголовок: «Reset progress of “{name}”? / Сбросить прогресс «{name}»?»
|
||||
|
||||
- «All {y} moves of this repertoire become new again: answers and review dates are erased. / Все ходы этого
|
||||
репертуара ({y}) снова станут новыми: ответы и сроки повторений будут стёрты.»
|
||||
- «The moves themselves and PGN files do not change. / Сами ходы и PGN-файлы не меняются.»
|
||||
- Если есть общие позиции (существующий расчёт `impact`, `repertoire_ui.rs:1906–1940`), цветом
|
||||
предупреждения: «{s} of these moves are also in: {names}. They become new there too. / Из них {s}
|
||||
встречаются также в: {names}. Там они тоже станут новыми.»
|
||||
- Кнопки: «Cancel / Отмена», «Reset / Сбросить». Флажок «I understand…» (`:1950`) убрать — его заменяет
|
||||
точный текст.
|
||||
|
||||
**Удаление.** Заголовок: «Delete “{name}”? / Удалить «{name}»?»
|
||||
|
||||
- «The repertoire leaves this list. PGN files on disk do not change. / Репертуар исчезнет из списка.
|
||||
PGN-файлы на диске не меняются.»
|
||||
- «Your answers are kept: import the same PGN again and the progress returns. / Ответы сохранятся: если
|
||||
импортировать тот же PGN снова, прогресс вернётся.» (сверить с ядром; если прогресс не возвращается —
|
||||
разработчик сообщает, текст меняется на «Progress of its moves is erased / Прогресс по его ходам будет
|
||||
стёрт».)
|
||||
- Кнопки: «Cancel / Отмена», «Delete / Удалить». После удаления выбирается соседняя строка.
|
||||
|
||||
### 7.6. Сообщения и ошибки
|
||||
|
||||
Полоса сообщения над нижним рядом экрана «Репертуары» (20, всегда зарезервирована): одна строка с обрезкой,
|
||||
полный текст в подсказке, справа `small_close_button` (`widgets.rs:74`). Ошибка — цвет предупреждения
|
||||
(«Could not save: {e} / Не удалось сохранить: {e}»), успех экспорта — обычный бледный («Saved to {path} /
|
||||
Сохранено: {path}»), исчезает через 6 с. Сообщение никогда не сдвигает таблицу.
|
||||
|
||||
## 8. Что удаляется из интерфейса
|
||||
|
||||
| Что | Где сейчас |
|
||||
| --- | --- |
|
||||
| Экран «Статистика обучения» целиком: вкладки Обзор, Динамика, Расписание, Ходы, меню «Дополнительно» (Варианты, Серии), селекторы репертуара и стороны, «Показатели обучения» | `learning_dashboard.rs`, `learning_charts.rs`, `learning_branches.rs`; вход `repertoire_ui.rs:1007`; хук `CP_LEARNING_DASHBOARD_TAB` |
|
||||
| Окно «Параметры тренировки» и кнопка «Параметры» | `repertoire_ui.rs:1669`, `learning_context_controls.rs` |
|
||||
| Экран «Изменить» («редактор»): список главной линии, «Без ограничения глубины», «Глубина … полуходов», «Аналитика хода», «Отмена/Сохранить» в шапке | `repertoire_editor.rs`; вход `repertoire_ui.rs:992`. Заменён экраном «Варианты» |
|
||||
| Переключатель «Цвет» и список «Режим» (По расписанию / Подряд / Сначала новые и давние) в карточке | `repertoire_ui.rs:1515` (`workspace_panel`) |
|
||||
| Строки «Не изучались… · Пора повторить…», «Тренировка: часть репертуара» | `repertoire_ui.rs:1591` и рядом |
|
||||
| Кнопки «Статистика», «Продолжить» (возобновление) | `workspace_panel` |
|
||||
| Вставные формы: имя (`name_editor`), импорт (`import_preview`), удаление, сброс (`shared_reset_panel`) | `repertoire_ui.rs:1403`, `:1448`, `:1172–1195`, `:1906` |
|
||||
| Строка таблицы высотой 156 с пятью названиями ECO, колонки «ECO» и «Варианты», индикатор вращения в строке | `repertoire_ui.rs:1136` (`show_library`), `:1297–1331` |
|
||||
| Пункт меню «Изменить» | `repertoire_ui.rs:1350` |
|
||||
| В занятии: «Заданий: k из n», строка «По расписанию · Белые», блок сообщений переменной высоты, тексты «…не будет самостоятельным успехом», «Самостоятельный ответ не засчитан», «…не считается самостоятельным» | `learning_training.rs` (`side`, тексты состояния) |
|
||||
| В занятии: пауза/отмена автопоказа (Space, P, Esc), L, Shift+A; кнопки управления показом | `learning_training.rs:1124–1139` |
|
||||
| Собственная раскладка «доска сверху» по правилу `width < 900 && height > width`; id панели `repertoire_workspace_side`; ширина панели 420–560 | `learning_training.rs:1530–1554`, `repertoire_ui.rs:1507`, `repertoire_editor.rs:100` |
|
||||
| Режим «за оба цвета», лимит глубины в любом виде | по концепции |
|
||||
|
||||
Строки `i18n.rs`, которые после этого нигде не используются, удалить (тест `all_used_keys_are_translated`
|
||||
ловит обратное, не это — проверить поиском).
|
||||
|
||||
## 9. Визуальная приёмка
|
||||
|
||||
Ревьюер — не автор кода; изолированный профиль; снимки 1400×900 и 960×600, тёмная тема, русский язык;
|
||||
дополнительно три ключевых кадра (репертуары, S3, итог) в светлой теме, на английском и при масштабе 2.
|
||||
|
||||
**Сравнение с эталонами** (снимки в одном размере окна, наложением):
|
||||
|
||||
1. Прямоугольник доски в «Репертуарах», «Занятии», «Вариантах» совпадает с доской игры с компьютером
|
||||
(`ref-04`): 1400×900 — x 54…886, y 60…892; 960×600 — x 22…554, y 60…592; допуск 1 px.
|
||||
2. Высота шапки, положение кнопки «назад», заголовка, подписи и «Настроек» — как у партии (`ref-02`).
|
||||
3. Левый край правой панели — как у игры (940 при 1400; 576 при 960).
|
||||
4. Карточка состояния рядом с карточкой игрока (`ref-04`): те же поля, радиус, обводка, заливка активной.
|
||||
5. Строка и заголовок таблицы рядом с таблицей библиотеки (`ref-01`): высоты 24 и 26, чередование, выделение.
|
||||
6. Диалоги рядом с «Игра с компьютером» и «Подготовка к сопернику» (`ref-03`, `ref-05`): заголовок, поля,
|
||||
кнопки справа внизу, одна главная.
|
||||
7. Высота всех кнопок в рядах — 30, значков полосы — 28; ширины главных кнопок 170.
|
||||
|
||||
**Состояния для снимков** (каждое в двух размерах): пустой список; один репертуар; 12 репертуаров (поиск,
|
||||
прокрутка); длинное имя (120 знаков); каждое состояние карточки из §3 (девять); меню `⋯`; все диалоги §7,
|
||||
включая импорт с предупреждениями, сброс с общими позициями и ошибку имени; S0–S9 занятия, включая S3a и
|
||||
S5a; длинный комментарий (прокрутка в D); позиция без названия дебюта; итог без ошибок, с ошибками (> 8),
|
||||
досрочный; «Повторить всё подряд» (S1 между вариантами, итог); «Тренировать эту ветку»; «Варианты» — начало,
|
||||
выбран глубокий ход, выключенная ветка; полоса сообщения с ошибкой; панель, суженная до 320.
|
||||
|
||||
**Отсутствие скачков** — серии кадров с наложением, различия допускаются только внутри названных блоков:
|
||||
|
||||
- A. Выбор строк 1→2→3 и возврат: меняются только тексты карточки и позиция доски; рамка карточки, таблица,
|
||||
нижний ряд неподвижны.
|
||||
- B. Импорт: до диалога → диалог → после: таблица сдвигается только на добавленную строку; во время счёта
|
||||
нет «…» поверх прежних чисел и нет индикатора вращения.
|
||||
- C. «Тренироваться» → S1 → S3 → S4 → S3 → S5 → S6 → S7 → S6 → S8 → «К репертуарам»: доска и границы
|
||||
блоков A–F совпадают на всех кадрах; меняются только тексты, рамка A и содержимое D.
|
||||
- D. Ошибка записи (S9) и повтор: те же границы.
|
||||
- E. «Варианты»: выбор десяти разных ходов, включение/выключение ветки — блок выбранного хода и полоса не
|
||||
меняют высоту.
|
||||
- F. Открытие общих настроек из каждого экрана и возврат: состояние не сброшено.
|
||||
|
||||
**Понятность без цвета**: в S4, S5, S9 состояние названо словом в заголовке; выключенная ветка — словом «Не
|
||||
тренируется»; цвет репертуара — фигурой короля и подсказкой.
|
||||
|
||||
Дефект записывается так: снимок, размер, состояние, блок, ожидаемое и фактическое значение в pt.
|
||||
|
||||
## 10. Передать тестировщику
|
||||
|
||||
- Числа карточки, таблицы, счётчика занятия и итога сходятся между собой на одном сценарии (10 новых,
|
||||
3 ошибки, 1 подсказка).
|
||||
- Ошибочный ход возвращается в том же занятии; S5a не считается ошибкой.
|
||||
- Выход на каждом состоянии (Esc, Ctrl+W, кнопки) не теряет записанные ответы; PGN-файлы не меняются
|
||||
(контрольные суммы до и после).
|
||||
- Репертуары 2.2.0/2.3.0 с режимом «оба цвета», с `max_plies = 20`, с незаконченной сессией открываются без
|
||||
ошибок и без потери прогресса.
|
||||
- Сброс с общими позициями меняет ровно названные репертуары.
|
||||
- Клавиши §4.3 и §6.3 не срабатывают под диалогом и в поле ввода.
|
||||
|
||||
## Возражения и риски
|
||||
|
||||
1. **Строка «Путь» (блок C).** 03.11 владелец убрал нотацию из тренировки. Здесь это одна бледная
|
||||
нередактируемая строка «где я», без дерева. Считаю её полезной для запоминания номеров ходов; если
|
||||
владелец против — блок удаляется без последствий для вёрстки (D займёт его место один раз, при сборке).
|
||||
2. **Полоса прогресса с сегментом «учится».** Концепция даёт одно число «Выучено X из Y». Критерий ядра
|
||||
«изучено» — три верных ответа подряд, поэтому первые дни X = 0 и работа не видна. Сегмент «учится» не
|
||||
вводит настроек и снимает это; число `k` можно убрать, оставив только цвет.
|
||||
3. **«Новый репертуар» без редактирования ходов** создаёт пустой объект, который нечем наполнить на этом
|
||||
экране. Диалог это объясняет, но путь остаётся слабым до этапа «ходы на доске».
|
||||
4. **Отметка выключенных веток** требует правки общего `notation.rs` (§6.3) — нужно решение оркестратора.
|
||||
5. **Текст удаления про возврат прогресса** (§7.5) не проверен по ядру.
|
||||
6. **Предвыбор цвета при импорте** — эвристика; на PGN из целых партий она ненадёжна, поэтому выбор всегда
|
||||
показан и подписан «проверьте».
|
||||
7. Пометка «(α версия)» в названии оставлена: её ввёл владелец, снять её может только он.
|
||||
|
||||
## Решения оркестратора по вопросам дизайнера (2026-11-26)
|
||||
|
||||
1. `widgets::section_header_sub` — **принято**: новая функция в `widgets.rs`, существующие функции и их вызовы не меняются.
|
||||
2. Поле в общем `notation.rs` для выключенных веток — **отклонено**: экран партии не трогаем. Состояние ветки показывается в блоке выбранного хода; если нужна отметка в дереве — только средствами раздела (например, своя обёртка/постобработка), без изменения поведения и вида нотации в других экранах.
|
||||
3. Строка «Путь» в занятии — **не делать**: владелец дважды (03.11) явно убирал нотацию из тренировки. Место строки не резервировать.
|
||||
4. Сегмент «учится» в полосе прогресса — **принято**.
|
||||
5. Текст диалога удаления — разработчик сверяет с ядром (удаление репертуара не стирает LearningItem; при повторном импорте того же дерева прогресс подхватывается по `(FEN4, UCI)`); если не так — исправить текст, а не ядро.
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue