Android: fixes from the tester's report
- An old evaluation never shows for a new position, not even for a frame:
every snapshot carries its position and the screen compares it with the
board; the engine handle is held for 40 ms at most.
- Turning the engine off while it starts no longer leaves a Stockfish process
behind (generations in EngineSession).
- Landscape: the board on the left, the notation, engine and buttons beside it.
- "Undo" after removing a database keeps the access to its file; picking a
file again restores the access.
- After Android restarts the app the same game comes back (the search is kept).
- Mate and stalemate are named instead of waiting for the engine.
- The download sheet shows progress and "Cancel" at once; a cancelled download
stops reading and never writes the file together with the next one.
- Plain error texts with "Remove from list"; evaluations rounded ("+0.5",
"0.0", "#−2"); search results start at the top; tag names translated;
"PGN copied" / "FEN copied".
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
305fff20b6
commit
7eac8db29a
13 changed files with 416 additions and 181 deletions
|
|
@ -16,8 +16,9 @@ import kotlinx.serialization.Serializable
|
|||
|
||||
@Serializable data class Games(val db: String) : NavKey
|
||||
|
||||
/// The game at `place` on the list of games shown for the database.
|
||||
@Serializable data class GameAt(val db: String, val place: Int) : 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
|
||||
|
||||
@Serializable data object SettingsKey : NavKey
|
||||
|
||||
|
|
@ -34,10 +35,10 @@ fun MainNavigation() {
|
|||
DatabasesScreen(onOpen = { backStack.add(Games(it)) }, onSettings = { backStack.add(SettingsKey) })
|
||||
}
|
||||
entry<Games> { key ->
|
||||
GamesScreen(key.db, onBack = { backStack.removeLastOrNull() }, onGame = { backStack.add(GameAt(key.db, it)) })
|
||||
GamesScreen(key.db, onBack = { backStack.removeLastOrNull() }, onGame = { place, query -> backStack.add(GameAt(key.db, place, query)) })
|
||||
}
|
||||
entry<GameAt> { key ->
|
||||
GameScreen(key.db, key.place, onBack = { backStack.removeLastOrNull() }, onSettings = { backStack.add(SettingsKey) })
|
||||
GameScreen(key.db, key.place, key.query, onBack = { backStack.removeLastOrNull() }, onSettings = { backStack.add(SettingsKey) })
|
||||
}
|
||||
entry<SettingsKey> {
|
||||
SettingsScreen(onBack = { backStack.removeLastOrNull() }, onAbout = { backStack.add(AboutKey) })
|
||||
|
|
|
|||
|
|
@ -7,6 +7,8 @@ import io.github.vrubelroman.chesspenguin.BuildConfig
|
|||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.cancelAndJoin
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
|
|
@ -45,6 +47,7 @@ class EngineFiles(private val context: Context, private val scope: CoroutineScop
|
|||
private val _state = MutableStateFlow(if (installed()) NetState.Ready else NetState.Missing)
|
||||
val state: StateFlow<NetState> = _state.asStateFlow()
|
||||
private var job: Job? = null
|
||||
@Volatile private var connection: HttpURLConnection? = null
|
||||
|
||||
/// A network checked when it was written: the right size is enough later.
|
||||
private fun installed() = net.length() == BuildConfig.NET_SIZE
|
||||
|
|
@ -61,9 +64,14 @@ class EngineFiles(private val context: Context, private val scope: CoroutineScop
|
|||
/// Gets the network ready: from the APK, or from the internet. Runs on in the app's
|
||||
/// scope when the screen that asked goes away.
|
||||
fun prepare() {
|
||||
if (_state.value == NetState.Ready || job?.isActive == true) return
|
||||
if (_state.value == NetState.Ready || _state.value is NetState.Loading) return
|
||||
// At once: the sheet shows the progress (and "Cancel") from the first moment.
|
||||
_state.value = NetState.Loading(part.length().coerceAtMost(BuildConfig.NET_SIZE), BuildConfig.NET_SIZE)
|
||||
val previous = job
|
||||
job = scope.launch(Dispatchers.IO) {
|
||||
_state.value = try {
|
||||
// A cancelled download may still be leaving: one writer of the file at a time.
|
||||
previous?.cancelAndJoin()
|
||||
val result = try {
|
||||
dir.mkdirs()
|
||||
if (builtIn) copyFromApk() else download()
|
||||
NetState.Ready
|
||||
|
|
@ -72,13 +80,16 @@ class EngineFiles(private val context: Context, private val scope: CoroutineScop
|
|||
} catch (e: IOException) {
|
||||
NetState.Failed(if (dir.usableSpace < BuildConfig.NET_SIZE) NetProblem.NoSpace else NetProblem.Interrupted)
|
||||
}
|
||||
// After "Cancel" the state is already "missing"; the broken connection is no failure.
|
||||
if (isActive) _state.value = result
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops a download; what came is kept for the next one.
|
||||
fun cancel() {
|
||||
job?.cancel()
|
||||
job = null
|
||||
// A read waiting for the network returns at once.
|
||||
connection?.disconnect()
|
||||
_state.value = NetState.Missing
|
||||
}
|
||||
|
||||
|
|
@ -108,6 +119,7 @@ class EngineFiles(private val context: Context, private val scope: CoroutineScop
|
|||
var hops = 0
|
||||
while (true) {
|
||||
conn = url.openConnection() as HttpURLConnection
|
||||
connection = conn
|
||||
conn.instanceFollowRedirects = false
|
||||
conn.connectTimeout = 15_000
|
||||
conn.readTimeout = 30_000
|
||||
|
|
@ -154,7 +166,7 @@ class EngineFiles(private val context: Context, private val scope: CoroutineScop
|
|||
if (n < 0) break
|
||||
out.write(buf, 0, n)
|
||||
done += n
|
||||
if (done - last > 512 * 1024) {
|
||||
if (done - last > 512 * 1024 && isActive) {
|
||||
last = done
|
||||
_state.value = NetState.Loading(done, total)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -54,63 +54,115 @@ sealed interface EngineStatus {
|
|||
data class Failed(val notStarting: Boolean) : EngineStatus
|
||||
}
|
||||
|
||||
/// What the engine said, and about which position: the screen shows it only while that
|
||||
/// position is on the board, so an old evaluation never appears for a new one, not
|
||||
/// even for a frame.
|
||||
data class EngineView(val position: EnginePosition, val analysis: Analysis)
|
||||
|
||||
/// The engine while a game is on the screen: one Stockfish process, the analysis of the
|
||||
/// shown position only. A new position clears the lines at once; snapshots of an older
|
||||
/// search are dropped, so an old evaluation is never shown for a new position.
|
||||
/// shown position only.
|
||||
class EngineSession(private val files: EngineFiles, private val scope: CoroutineScope) {
|
||||
private val _status = MutableStateFlow<EngineStatus>(EngineStatus.Off)
|
||||
val status: StateFlow<EngineStatus> = _status.asStateFlow()
|
||||
private val _analysis = MutableStateFlow<Analysis?>(null)
|
||||
val analysis: StateFlow<Analysis?> = _analysis.asStateFlow()
|
||||
private val _analysis = MutableStateFlow<EngineView?>(null)
|
||||
val analysis: StateFlow<EngineView?> = _analysis.asStateFlow()
|
||||
|
||||
private val lock = Mutex()
|
||||
private var analyzer: Analyzer? = null
|
||||
@Volatile private var analyzer: Analyzer? = null
|
||||
private var loop: Job? = null
|
||||
private var timer: Job? = null
|
||||
@Volatile private var search: ULong = 0u
|
||||
|
||||
/// The search whose snapshots are taken, and its position (set together).
|
||||
private data class Search(val id: ULong, val position: EnginePosition)
|
||||
@Volatile private var search: Search? = null
|
||||
private var position: EnginePosition? = null
|
||||
private var prefs = Prefs()
|
||||
|
||||
/// Bumped by [shutdown]: work queued before it is dropped instead of starting the
|
||||
/// engine again.
|
||||
@Volatile private var generation = 0
|
||||
|
||||
/// Starts the engine (if it is not running) and analyses `pos`.
|
||||
fun show(pos: EnginePosition, p: Prefs) {
|
||||
prefs = p
|
||||
val changed = pos != position
|
||||
position = pos
|
||||
val gen = generation
|
||||
scope.launch {
|
||||
lock.withLock {
|
||||
val a = analyzer ?: startLocked() ?: return@withLock
|
||||
if (gen != generation) return@withLock
|
||||
val a = analyzer ?: startLocked(gen) ?: return@withLock
|
||||
// The same position again (the screen redrawn, the time over) stays as it is.
|
||||
if (changed || _status.value == EngineStatus.Starting) analyzeLocked(a, pos)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops thinking (a mate or stalemate on the board); the process stays for the next
|
||||
/// position.
|
||||
fun pause() {
|
||||
position = null
|
||||
search = null
|
||||
_analysis.value = null
|
||||
timer?.cancel()
|
||||
val gen = generation
|
||||
scope.launch {
|
||||
lock.withLock {
|
||||
if (gen != generation) return@withLock
|
||||
val a = analyzer ?: return@withLock
|
||||
withContext(Dispatchers.IO) { a.stop() }
|
||||
_status.value = EngineStatus.Paused
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Thinks on about the same position after the time ran out.
|
||||
fun deeper() {
|
||||
val pos = position ?: return
|
||||
scope.launch { lock.withLock { analyzer?.let { analyzeLocked(it, pos) } } }
|
||||
val gen = generation
|
||||
scope.launch {
|
||||
lock.withLock {
|
||||
if (gen == generation) analyzer?.let { analyzeLocked(it, pos) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Quits the process (the screen went away, the button was turned off).
|
||||
fun shutdown() {
|
||||
generation++
|
||||
position = null
|
||||
search = null
|
||||
_analysis.value = null
|
||||
_status.value = EngineStatus.Off
|
||||
val a = analyzer
|
||||
analyzer = null
|
||||
loop?.cancel()
|
||||
timer?.cancel()
|
||||
if (a != null) scope.launch(Dispatchers.IO) { lock.withLock { a.quit(); a.close() } }
|
||||
// Taken now, so that a show() right after it starts a new engine.
|
||||
val a = analyzer ?: return
|
||||
analyzer = null
|
||||
scope.launch(Dispatchers.IO) {
|
||||
lock.withLock {
|
||||
a.quit()
|
||||
a.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun startLocked(): Analyzer? {
|
||||
private suspend fun startLocked(gen: Int): Analyzer? {
|
||||
_status.value = EngineStatus.Starting
|
||||
val a = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
Analyzer.start(files.executable, files.net.path, prefs.engineThreads.toUInt(), prefs.engineHashMb.toUInt())
|
||||
}
|
||||
}.getOrElse {
|
||||
_status.value = EngineStatus.Failed(notStarting = true)
|
||||
if (gen == generation) _status.value = EngineStatus.Failed(notStarting = true)
|
||||
return null
|
||||
}
|
||||
if (gen != generation) {
|
||||
// Turned off while it was starting.
|
||||
withContext(Dispatchers.IO) {
|
||||
a.quit()
|
||||
a.close()
|
||||
}
|
||||
return null
|
||||
}
|
||||
analyzer = a
|
||||
|
|
@ -119,23 +171,22 @@ class EngineSession(private val files: EngineFiles, private val scope: Coroutine
|
|||
}
|
||||
|
||||
private suspend fun analyzeLocked(a: Analyzer, pos: EnginePosition) {
|
||||
// No snapshot is taken until the new search has its number.
|
||||
search = 0u
|
||||
_analysis.value = null
|
||||
search = null
|
||||
val id = withContext(Dispatchers.IO) {
|
||||
runCatching { a.analyze(pos.startFen, pos.moves, prefs.engineLines.toUInt()) }
|
||||
}.getOrElse {
|
||||
_status.value = EngineStatus.Failed(notStarting = false)
|
||||
return
|
||||
}
|
||||
search = id
|
||||
val s = Search(id, pos)
|
||||
search = s
|
||||
_status.value = EngineStatus.Thinking
|
||||
timer?.cancel()
|
||||
if (prefs.engineSeconds > 0) {
|
||||
timer = scope.launch {
|
||||
delay(prefs.engineSeconds * 1000L)
|
||||
lock.withLock {
|
||||
if (search == id && analyzer === a) {
|
||||
if (search == s && analyzer === a) {
|
||||
withContext(Dispatchers.IO) { a.stop() }
|
||||
_status.value = EngineStatus.Paused
|
||||
}
|
||||
|
|
@ -146,13 +197,17 @@ class EngineSession(private val files: EngineFiles, private val scope: Coroutine
|
|||
|
||||
private suspend fun poll(a: Analyzer) {
|
||||
while (scope.isActive && analyzer === a) {
|
||||
// A short wait: analyze() waits for the engine handle while this holds it.
|
||||
val snapshot = try {
|
||||
a.poll(150u)
|
||||
a.poll(40u)
|
||||
} catch (e: Exception) {
|
||||
if (analyzer === a) _status.value = EngineStatus.Failed(notStarting = false)
|
||||
return
|
||||
}
|
||||
if (snapshot != null && snapshot.search == search && analyzer === a) _analysis.value = snapshot
|
||||
val s = search
|
||||
if (snapshot != null && s != null && snapshot.search == s.id && analyzer === a) {
|
||||
_analysis.value = EngineView(s.position, snapshot)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -91,10 +91,14 @@ class Library(private val context: Context) {
|
|||
/// Adds a file picked with the system picker; its read permission is kept across
|
||||
/// restarts. Returns the new entry, or the one already on the list.
|
||||
fun addFile(uri: Uri): DbEntry {
|
||||
_entries.value.firstOrNull { it.location == uri.toString() }?.let { return it }
|
||||
// Taken again for a file already on the list: picking it grants a new permission.
|
||||
runCatching {
|
||||
context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
_entries.value.firstOrNull { it.location == uri.toString() }?.let {
|
||||
open.remove(it.id)?.close()
|
||||
return it
|
||||
}
|
||||
val fileName = displayName(uri) ?: "database.pgn"
|
||||
val entry = DbEntry(
|
||||
id = UUID.randomUUID().toString(),
|
||||
|
|
@ -110,7 +114,7 @@ class Library(private val context: Context) {
|
|||
fun rename(id: String, name: String) = update { list -> list.map { if (it.id == id) it.copy(name = name, renamed = true) else it } }
|
||||
|
||||
/// Takes the database off the list (the file stays where it is). Returns its place,
|
||||
/// for "Undo".
|
||||
/// for "Undo"; the access to the file is kept until [forget].
|
||||
fun remove(id: String): Pair<Int, DbEntry>? {
|
||||
val list = _entries.value
|
||||
val i = list.indexOfFirst { it.id == id }
|
||||
|
|
@ -118,20 +122,18 @@ class Library(private val context: Context) {
|
|||
val e = list[i]
|
||||
update { it.filterNot { x -> x.id == id } }
|
||||
open.remove(id)?.close()
|
||||
if (e.source == Source.File) {
|
||||
runCatching {
|
||||
context.contentResolver.releasePersistableUriPermission(Uri.parse(e.location), Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
}
|
||||
return i to e
|
||||
}
|
||||
|
||||
fun restore(place: Int, entry: DbEntry) {
|
||||
if (entry.source == Source.File) {
|
||||
runCatching {
|
||||
context.contentResolver.takePersistableUriPermission(Uri.parse(entry.location), Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
/// Gives the access to a removed file back to the system, once "Undo" is gone.
|
||||
fun forget(entry: DbEntry) {
|
||||
if (entry.source != Source.File || _entries.value.any { it.location == entry.location }) return
|
||||
runCatching {
|
||||
context.contentResolver.releasePersistableUriPermission(Uri.parse(entry.location), Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
}
|
||||
|
||||
fun restore(place: Int, entry: DbEntry) {
|
||||
update { it.toMutableList().apply { add(place.coerceIn(0, size), entry) } }
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ import androidx.compose.animation.core.FastOutSlowInEasing
|
|||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
|
|
@ -138,7 +137,6 @@ fun Board(
|
|||
val density = LocalDensity.current
|
||||
Canvas(
|
||||
modifier
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(1f)
|
||||
.semantics { contentDescription = description },
|
||||
) {
|
||||
|
|
|
|||
|
|
@ -134,7 +134,11 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onSettings: () -> Unit) {
|
|||
scope.launch {
|
||||
snackbar.currentSnackbarData?.dismiss()
|
||||
val r = snackbar.showSnackbar(removedText, undoText, withDismissAction = false)
|
||||
if (r == SnackbarResult.ActionPerformed) library.restore(removed.first, removed.second)
|
||||
if (r == SnackbarResult.ActionPerformed) {
|
||||
library.restore(removed.first, removed.second)
|
||||
} else {
|
||||
library.forget(removed.second)
|
||||
}
|
||||
}
|
||||
},
|
||||
modifier = Modifier.animateItem(),
|
||||
|
|
|
|||
|
|
@ -64,6 +64,7 @@ fun whiteShare(line: EngineLine?): Float {
|
|||
/// evaluation, the depth, the best line; ▾ shows more lines.
|
||||
@Composable
|
||||
fun EngineStrip(
|
||||
ending: String?,
|
||||
status: EngineStatus,
|
||||
analysis: Analysis?,
|
||||
flipped: Boolean,
|
||||
|
|
@ -87,6 +88,12 @@ fun EngineStrip(
|
|||
if (left > 0f) Box(Modifier.weight(left.coerceAtLeast(0.001f)).fillMaxHeight().background(if (flipped) black else white))
|
||||
if (left < 1f) Box(Modifier.weight((1f - left).coerceAtLeast(0.001f)).fillMaxHeight().background(if (flipped) white else black))
|
||||
}
|
||||
if (ending != null) {
|
||||
Row(Modifier.fillMaxWidth().height(48.dp).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(ending, style = MaterialTheme.typography.labelLarge)
|
||||
}
|
||||
return@Column
|
||||
}
|
||||
if (status is EngineStatus.Failed) {
|
||||
Row(Modifier.fillMaxWidth().height(48.dp).padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
|
|
@ -170,7 +177,8 @@ private fun LineRow(
|
|||
/// The evaluation: light when White is better, dark when Black is (§8.2).
|
||||
@Composable
|
||||
private fun EvalPlaque(line: EngineLine?) {
|
||||
val blackBetter = line != null && ((line.mate ?: 0) < 0 || (line.mate == null && (line.cp ?: 0) < 0))
|
||||
// Dark only when Black is better by what is shown ("0.0" stays light).
|
||||
val blackBetter = line != null && ((line.mate ?: 0) < 0 || (line.mate == null && Math.round((line.cp ?: 0) / 10.0) < 0))
|
||||
val bg = if (blackBetter) Color(0xFF26282B) else Color(0xFFF5F5F0)
|
||||
val fg = if (blackBetter) Color(0xFFE8E8E8) else Color(0xFF1C1D1F)
|
||||
Box(
|
||||
|
|
@ -183,7 +191,7 @@ private fun EvalPlaque(line: EngineLine?) {
|
|||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
line?.eval?.let(::shortEval) ?: "",
|
||||
line?.let(::shownEval) ?: "",
|
||||
color = fg,
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
|
|
@ -192,11 +200,15 @@ private fun EvalPlaque(line: EngineLine?) {
|
|||
}
|
||||
}
|
||||
|
||||
/// One decimal is enough on a phone (§8.2): "+0.45" → "+0.4".
|
||||
fun shortEval(eval: String): String {
|
||||
if (eval.contains('#')) return eval
|
||||
val dot = eval.indexOf('.')
|
||||
return if (dot >= 0 && eval.length > dot + 2) eval.substring(0, dot + 2) else eval
|
||||
/// The evaluation as shown (§8.2): pawns with one decimal, rounded ("+0.45" → "+0.5"),
|
||||
/// no sign for an equal position; mates as the engine line has them ("#3", "#−2").
|
||||
fun shownEval(line: EngineLine): String {
|
||||
if (line.mate != null) return line.eval
|
||||
val tenths = Math.round((line.cp ?: 0) / 10.0).toInt()
|
||||
if (tenths == 0) return "0.0"
|
||||
val sign = if (tenths > 0) "+" else "\u2212"
|
||||
val a = kotlin.math.abs(tenths)
|
||||
return "$sign${a / 10}.${a % 10}"
|
||||
}
|
||||
|
||||
/// The bar above the notation while an engine line is shown on the board (§8.3).
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.content.Intent
|
||||
import android.view.HapticFeedbackConstants
|
||||
import androidx.activity.compose.BackHandler
|
||||
|
|
@ -75,6 +76,7 @@ import androidx.compose.ui.draw.scale
|
|||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.res.stringResource
|
||||
|
|
@ -112,7 +114,7 @@ private data class Preview(val line: EngineLine, val step: Int)
|
|||
/// under the thumb; ‹ › page the games of the list (android-ui.md §7).
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun GameScreen(db: String, startPlace: Int, onBack: () -> Unit, onSettings: () -> Unit) {
|
||||
fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, onSettings: () -> Unit) {
|
||||
val app = app()
|
||||
val context = LocalContext.current
|
||||
val prefs by app.settings.prefs.collectAsState()
|
||||
|
|
@ -130,8 +132,8 @@ fun GameScreen(db: String, startPlace: Int, onBack: () -> Unit, onSettings: () -
|
|||
failed = true
|
||||
return@LaunchedEffect
|
||||
}
|
||||
// After the process was restarted the list is gone: page all the games.
|
||||
val list = games ?: withContext(Dispatchers.Default) { database.find("") }.also {
|
||||
// After the process was restarted the list is gone: the same search finds it again.
|
||||
val list = games ?: withContext(Dispatchers.Default) { database.find(query) }.also {
|
||||
games = it
|
||||
app.shown[db] = it
|
||||
}
|
||||
|
|
@ -158,7 +160,7 @@ fun GameScreen(db: String, startPlace: Int, onBack: () -> Unit, onSettings: () -
|
|||
val netState by files.state.collectAsState()
|
||||
val session = remember { EngineSession(files, app.scope) }
|
||||
val status by session.status.collectAsState()
|
||||
val analysis by session.analysis.collectAsState()
|
||||
val engineView by session.analysis.collectAsState()
|
||||
var visible by remember { mutableStateOf(true) }
|
||||
var sheet by remember { mutableStateOf(false) }
|
||||
var wantEngine by remember { mutableStateOf(false) }
|
||||
|
|
@ -167,7 +169,8 @@ fun GameScreen(db: String, startPlace: Int, onBack: () -> Unit, onSettings: () -
|
|||
var info by remember { mutableStateOf(false) }
|
||||
@Suppress("DEPRECATION")
|
||||
val clipboard = androidx.compose.ui.platform.LocalClipboardManager.current
|
||||
val copiedText = stringResource(R.string.copied)
|
||||
val pgnCopied = stringResource(R.string.pgn_copied)
|
||||
val fenCopied = stringResource(R.string.fen_copied)
|
||||
suspend fun pgnText(): String? {
|
||||
val index = games?.getOrNull(place) ?: return null
|
||||
val database = app.library.database(db).getOrNull() ?: return null
|
||||
|
|
@ -204,10 +207,23 @@ fun GameScreen(db: String, startPlace: Int, onBack: () -> Unit, onSettings: () -
|
|||
val notation = rememberLazyListState()
|
||||
val engineReady = netState == NetState.Ready
|
||||
val engineOn = prefs.engineOn && engineReady
|
||||
val position = remember(g, current) { g?.let { enginePosition(it, current) } }
|
||||
// Only what the engine said about the position on the board.
|
||||
val analysis = engineView?.takeIf { it.position == position }?.analysis
|
||||
// Mate and stalemate need no engine: the strip says what it is (§7.3).
|
||||
val ending = when (node?.end) {
|
||||
"checkmate" -> stringResource(R.string.checkmate) + (g?.let { " · " + shortResult(it.result) }?.takeIf { !it.endsWith("*") } ?: "")
|
||||
"stalemate" -> stringResource(R.string.stalemate) + " · ½-½"
|
||||
else -> null
|
||||
}
|
||||
|
||||
LaunchedEffect(g, current, engineOn, visible, prefs.engineLines, prefs.engineSeconds) {
|
||||
if (g == null || !visible) return@LaunchedEffect
|
||||
if (engineOn) session.show(enginePosition(g, current), prefs) else session.shutdown()
|
||||
LaunchedEffect(position, engineOn, visible, prefs.engineLines, prefs.engineSeconds) {
|
||||
if (position == null || !visible) return@LaunchedEffect
|
||||
when {
|
||||
!engineOn -> session.shutdown()
|
||||
ending != null -> session.pause()
|
||||
else -> session.show(position, prefs)
|
||||
}
|
||||
}
|
||||
// A download started from the button turns the engine on when it is done.
|
||||
LaunchedEffect(netState) {
|
||||
|
|
@ -268,6 +284,123 @@ fun GameScreen(db: String, startPlace: Int, onBack: () -> Unit, onSettings: () -
|
|||
}
|
||||
BackHandler(preview != null) { preview = null }
|
||||
|
||||
val landscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE
|
||||
val controls: @Composable (Modifier) -> Unit = { modifier ->
|
||||
Column(modifier) {
|
||||
val p = preview
|
||||
if (p == null && node != null && nodes != null && node.children.size > 1) {
|
||||
Forks(node.children.map { nodes[it.toInt()] }, san, onMove = ::go)
|
||||
}
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
|
||||
Surface(color = MaterialTheme.colorScheme.surfaceContainer) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
EngineButton(
|
||||
on = engineOn,
|
||||
needsDownload = !engineReady && !files.builtIn,
|
||||
loading = netState as? NetState.Loading,
|
||||
modifier = Modifier.weight(1.2f),
|
||||
onClick = ::toggleEngine,
|
||||
)
|
||||
BarButton(Icons.Rounded.SwapVert, stringResource(R.string.flip), true, Modifier.weight(1f)) { flipped = !flipped }
|
||||
BarButton(Icons.Rounded.FirstPage, stringResource(R.string.to_start), canBack, Modifier.weight(1f)) {
|
||||
if (preview != null) preview = null else go(0)
|
||||
}
|
||||
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() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val board: @Composable (Modifier) -> Unit = { boardModifier ->
|
||||
val p = preview
|
||||
val step = p?.let { it.line.steps[it.step] }
|
||||
val fen = step?.fen ?: node?.fen ?: START
|
||||
val description = when {
|
||||
step != null -> stringResource(R.string.board_description, step.label)
|
||||
node == null || current == 0 -> stringResource(R.string.board_start)
|
||||
else -> stringResource(R.string.board_description, (if (node.white) "${node.moveNumber}." else "${node.moveNumber}…") + node.san)
|
||||
}
|
||||
val arrows = buildList {
|
||||
if (p != null) {
|
||||
p.line.steps.getOrNull(p.step + 1)?.let { add(BoardArrow(it.fromSquare, it.toSquare, EngineArrow)) }
|
||||
} else {
|
||||
node?.marks?.forEach { m -> m.to?.let { add(BoardArrow(m.from, it, markColor(m.color), 0.9f)) } }
|
||||
if (engineOn && prefs.bestArrow) {
|
||||
analysis?.lines?.take(2)?.forEachIndexed { i, l ->
|
||||
val f = l.fromSquare
|
||||
val t = l.toSquare
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val marks = if (p == null) node?.marks?.filter { it.to == null }?.map { BoardMark(it.from, markColor(it.color)) }.orEmpty() else emptyList()
|
||||
val check = (step?.label ?: node?.san ?: "").let { it.endsWith("+") || it.endsWith("#") }
|
||||
Board(
|
||||
fen = fen,
|
||||
flipped = flipped,
|
||||
lastFrom = step?.fromSquare ?: node?.fromSquare,
|
||||
lastTo = step?.toSquare ?: node?.toSquare,
|
||||
pieces = pieces,
|
||||
description = description,
|
||||
arrows = arrows,
|
||||
marks = marks,
|
||||
check = check,
|
||||
animated = prefs.animation,
|
||||
modifier = boardModifier.pointerInput(Unit) {
|
||||
detectTapGestures {
|
||||
if (firstBoardTouch(context)) scope.launch { snackbar.showSnackbar(hint) }
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
val side: @Composable (Modifier) -> Unit = { sideModifier ->
|
||||
Column(sideModifier.fillMaxWidth()) {
|
||||
val p = preview
|
||||
if (engineOn) {
|
||||
EngineStrip(
|
||||
ending = ending,
|
||||
status = status,
|
||||
analysis = analysis,
|
||||
flipped = flipped,
|
||||
lines = prefs.engineLines,
|
||||
expanded = expanded,
|
||||
onExpand = { expanded = !expanded },
|
||||
onLine = { l -> if (l.steps.isNotEmpty()) preview = Preview(l, 0) },
|
||||
onDeeper = { session.deeper() },
|
||||
onRestart = {
|
||||
session.shutdown()
|
||||
position?.let { session.show(it, prefs) }
|
||||
},
|
||||
notation = line,
|
||||
)
|
||||
} else if (wantEngine && files.builtIn && netState is NetState.Loading) {
|
||||
Row(Modifier.fillMaxWidth().height(48.dp).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)
|
||||
Text(stringResource(R.string.preparing_engine), Modifier.padding(start = 12.dp), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
if (p != null) PreviewBar(p.step + 1, p.line.steps.size, onClose = { preview = null })
|
||||
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||
when {
|
||||
g != null -> Notation(g, items, where, current, notation, san, onMove = ::go, modifier = Modifier.fillMaxSize())
|
||||
failed -> Text(
|
||||
stringResource(R.string.game_failed),
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.align(Alignment.Center),
|
||||
)
|
||||
else -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
|
|
@ -314,7 +447,7 @@ fun GameScreen(db: String, startPlace: Int, onBack: () -> Unit, onSettings: () -
|
|||
scope.launch {
|
||||
pgnText()?.let {
|
||||
clipboard.setText(AnnotatedString(it))
|
||||
snackbar.showSnackbar(copiedText)
|
||||
snackbar.showSnackbar(pgnCopied)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
|
@ -322,7 +455,7 @@ fun GameScreen(db: String, startPlace: Int, onBack: () -> Unit, onSettings: () -
|
|||
menu = false
|
||||
(preview?.let { it.line.steps[it.step].fen } ?: node?.fen)?.let {
|
||||
clipboard.setText(AnnotatedString(it))
|
||||
scope.launch { snackbar.showSnackbar(copiedText) }
|
||||
scope.launch { snackbar.showSnackbar(fenCopied) }
|
||||
}
|
||||
})
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.share_game)) }, enabled = g != null, onClick = {
|
||||
|
|
@ -344,115 +477,23 @@ fun GameScreen(db: String, startPlace: Int, onBack: () -> Unit, onSettings: () -
|
|||
)
|
||||
},
|
||||
snackbarHost = { SnackbarHost(snackbar) },
|
||||
// In the bottom bar, so that snackbars stand above the move buttons.
|
||||
bottomBar = {
|
||||
Column {
|
||||
val p = preview
|
||||
if (p == null && node != null && nodes != null && node.children.size > 1) {
|
||||
Forks(node.children.map { nodes[it.toInt()] }, san, onMove = ::go)
|
||||
}
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
|
||||
Surface(color = MaterialTheme.colorScheme.surfaceContainer) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
EngineButton(
|
||||
on = engineOn,
|
||||
needsDownload = !engineReady && !files.builtIn,
|
||||
loading = netState as? NetState.Loading,
|
||||
modifier = Modifier.weight(1.2f),
|
||||
onClick = ::toggleEngine,
|
||||
)
|
||||
BarButton(Icons.Rounded.SwapVert, stringResource(R.string.flip), true, Modifier.weight(1f)) { flipped = !flipped }
|
||||
BarButton(Icons.Rounded.FirstPage, stringResource(R.string.to_start), canBack, Modifier.weight(1f)) {
|
||||
if (preview != null) preview = null else go(0)
|
||||
}
|
||||
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() }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
// In the bottom bar, so that snackbars stand above the move buttons; beside the
|
||||
// board when the phone lies on its side.
|
||||
bottomBar = { if (!landscape) controls(Modifier) },
|
||||
) { padding ->
|
||||
Column(Modifier.fillMaxSize().padding(top = padding.calculateTopPadding(), bottom = padding.calculateBottomPadding())) {
|
||||
val p = preview
|
||||
val step = p?.let { it.line.steps[it.step] }
|
||||
val fen = step?.fen ?: node?.fen ?: START
|
||||
val description = when {
|
||||
step != null -> stringResource(R.string.board_description, step.label)
|
||||
node == null || current == 0 -> stringResource(R.string.board_start)
|
||||
else -> stringResource(R.string.board_description, (if (node.white) "${node.moveNumber}." else "${node.moveNumber}…") + node.san)
|
||||
}
|
||||
val arrows = buildList {
|
||||
if (p != null) {
|
||||
p.line.steps.getOrNull(p.step + 1)?.let { add(BoardArrow(it.fromSquare, it.toSquare, EngineArrow)) }
|
||||
} else {
|
||||
node?.marks?.forEach { m -> m.to?.let { add(BoardArrow(m.from, it, markColor(m.color), 0.9f)) } }
|
||||
if (engineOn && prefs.bestArrow) {
|
||||
analysis?.lines?.take(2)?.forEachIndexed { i, l ->
|
||||
val f = l.fromSquare
|
||||
val t = l.toSquare
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
val inner = Modifier.fillMaxSize().padding(top = padding.calculateTopPadding(), bottom = padding.calculateBottomPadding())
|
||||
if (landscape) {
|
||||
Row(inner) {
|
||||
board(Modifier.fillMaxHeight())
|
||||
Column(Modifier.weight(1f).fillMaxHeight()) {
|
||||
side(Modifier.weight(1f))
|
||||
controls(Modifier)
|
||||
}
|
||||
}
|
||||
val marks = if (p == null) node?.marks?.filter { it.to == null }?.map { BoardMark(it.from, markColor(it.color)) }.orEmpty() else emptyList()
|
||||
val check = (step?.label ?: node?.san ?: "").let { it.endsWith("+") || it.endsWith("#") }
|
||||
Board(
|
||||
fen = fen,
|
||||
flipped = flipped,
|
||||
lastFrom = step?.fromSquare ?: node?.fromSquare,
|
||||
lastTo = step?.toSquare ?: node?.toSquare,
|
||||
pieces = pieces,
|
||||
description = description,
|
||||
arrows = arrows,
|
||||
marks = marks,
|
||||
check = check,
|
||||
animated = prefs.animation,
|
||||
modifier = Modifier.pointerInput(Unit) {
|
||||
detectTapGestures {
|
||||
if (firstBoardTouch(context)) scope.launch { snackbar.showSnackbar(hint) }
|
||||
}
|
||||
},
|
||||
)
|
||||
if (engineOn) {
|
||||
EngineStrip(
|
||||
status = status,
|
||||
analysis = analysis,
|
||||
flipped = flipped,
|
||||
lines = prefs.engineLines,
|
||||
expanded = expanded,
|
||||
onExpand = { expanded = !expanded },
|
||||
onLine = { l -> if (l.steps.isNotEmpty()) preview = Preview(l, 0) },
|
||||
onDeeper = { session.deeper() },
|
||||
onRestart = {
|
||||
session.shutdown()
|
||||
g?.let { session.show(enginePosition(it, current), prefs) }
|
||||
},
|
||||
notation = line,
|
||||
)
|
||||
} else if (wantEngine && files.builtIn && netState is NetState.Loading) {
|
||||
Row(Modifier.fillMaxWidth().height(48.dp).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)
|
||||
Text(stringResource(R.string.preparing_engine), Modifier.padding(start = 12.dp), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
if (p != null) PreviewBar(p.step + 1, p.line.steps.size, onClose = { preview = null })
|
||||
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||
when {
|
||||
g != null -> Notation(g, items, where, current, notation, san, onMove = ::go, modifier = Modifier.fillMaxSize())
|
||||
failed -> Text(
|
||||
stringResource(R.string.game_failed),
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.align(Alignment.Center),
|
||||
)
|
||||
else -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
}
|
||||
} else {
|
||||
Column(inner) {
|
||||
board(Modifier.fillMaxWidth())
|
||||
side(Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -462,10 +503,10 @@ fun GameScreen(db: String, startPlace: Int, onBack: () -> Unit, onSettings: () -
|
|||
title = { Text(stringResource(R.string.game_info)) },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
g.tags.filter { it.value.isNotBlank() && it.value != "?" }.forEach { t ->
|
||||
g.tags.filter { it.value.isNotBlank() && it.value != "?" && !it.value.startsWith("????") }.forEach { t ->
|
||||
Row(Modifier.padding(vertical = 4.dp)) {
|
||||
Text(t.name, Modifier.width(96.dp), color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodyMedium)
|
||||
Text(t.value, style = MaterialTheme.typography.bodyMedium)
|
||||
Text(tagLabel(t.name), Modifier.width(112.dp), color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodyMedium)
|
||||
Text(if (t.name == "Date" || t.name == "EventDate") pgnDate(t.value) else t.value, style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
if (g.notes.isNotEmpty()) {
|
||||
|
|
@ -623,6 +664,36 @@ private fun BarButton(
|
|||
}
|
||||
}
|
||||
|
||||
/// The names of the usual PGN tags in the language of the interface; others as they are.
|
||||
@Composable
|
||||
private fun tagLabel(name: String): String = when (name) {
|
||||
"Event" -> stringResource(R.string.tag_event)
|
||||
"Site" -> stringResource(R.string.tag_site)
|
||||
"Date" -> stringResource(R.string.tag_date)
|
||||
"Round" -> stringResource(R.string.tag_round)
|
||||
"White" -> stringResource(R.string.tag_white)
|
||||
"Black" -> stringResource(R.string.tag_black)
|
||||
"Result" -> stringResource(R.string.tag_result)
|
||||
"WhiteElo" -> stringResource(R.string.tag_white_elo)
|
||||
"BlackElo" -> stringResource(R.string.tag_black_elo)
|
||||
"ECO" -> "ECO"
|
||||
"Annotator" -> stringResource(R.string.tag_annotator)
|
||||
"PlyCount" -> stringResource(R.string.tag_plies)
|
||||
else -> name
|
||||
}
|
||||
|
||||
/// "1858.??.??" → "1858", "1927.09.16" → "16.09.1927".
|
||||
private fun pgnDate(date: String): String {
|
||||
val parts = date.split('.')
|
||||
if (parts.size != 3) return date
|
||||
val (y, m, d) = parts
|
||||
return when {
|
||||
m.all { it.isDigit() } && d.all { it.isDigit() } -> "$d.$m.$y"
|
||||
m.all { it.isDigit() } -> "$m.$y"
|
||||
else -> y
|
||||
}
|
||||
}
|
||||
|
||||
/// "Carlsen, Magnus" → "Carlsen"; "Magnus Carlsen" stays as it is.
|
||||
private fun surname(name: String): String = name.substringBefore(',').trim().ifEmpty { "?" }
|
||||
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ import androidx.compose.material3.MaterialTheme
|
|||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TextFieldDefaults
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
|
|
@ -58,6 +59,7 @@ import io.github.vrubelroman.chesspenguin.theme.Tabular
|
|||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
import uniffi.mobile_api.ApiException
|
||||
import uniffi.mobile_api.Database
|
||||
import uniffi.mobile_api.GameRow
|
||||
|
||||
|
|
@ -66,18 +68,19 @@ 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: (Int) -> 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 }
|
||||
var database by remember { mutableStateOf<Database?>(null) }
|
||||
var failed by remember { mutableStateOf<String?>(null) }
|
||||
var failed by remember { mutableStateOf<Throwable?>(null) }
|
||||
LaunchedEffect(db) {
|
||||
app.library.database(db).onSuccess { database = it }.onFailure { failed = it.message ?: "" }
|
||||
app.library.database(db).onSuccess { database = it }.onFailure { failed = it }
|
||||
}
|
||||
var searching by rememberSaveable { mutableStateOf(false) }
|
||||
var query by rememberSaveable { mutableStateOf("") }
|
||||
var shown by remember { mutableStateOf<List<UInt>?>(null) }
|
||||
val list = rememberLazyListState()
|
||||
val rows = remember { mutableStateMapOf<Int, List<GameRow>>() }
|
||||
LaunchedEffect(database, query) {
|
||||
val d = database ?: return@LaunchedEffect
|
||||
|
|
@ -85,9 +88,10 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (Int) -> Unit) {
|
|||
val found = withContext(Dispatchers.Default) { d.find(query) }
|
||||
rows.clear()
|
||||
shown = found
|
||||
// New results start at the top.
|
||||
list.scrollToItem(0)
|
||||
app.shown[db] = found
|
||||
}
|
||||
val list = rememberLazyListState()
|
||||
val scroll = TopAppBarDefaults.pinnedScrollBehavior()
|
||||
val focus = remember { FocusRequester() }
|
||||
val keyboard = LocalSoftwareKeyboardController.current
|
||||
|
|
@ -156,7 +160,13 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (Int) -> Unit) {
|
|||
Box(Modifier.fillMaxSize().padding(padding)) {
|
||||
val games = shown
|
||||
when {
|
||||
failed != null -> Message(stringResource(R.string.open_failed), failed!!)
|
||||
failed != null -> Message(stringResource(R.string.open_failed), openProblem(failed!!)) {
|
||||
// The way out: take the database off the list, add the file again.
|
||||
TextButton(onClick = {
|
||||
app.library.remove(db)?.let { app.library.forget(it.second) }
|
||||
onBack()
|
||||
}) { Text(stringResource(R.string.remove)) }
|
||||
}
|
||||
games == null -> Column(Modifier.align(Alignment.Center), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
CircularProgressIndicator()
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
|
@ -174,7 +184,7 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (Int) -> Unit) {
|
|||
rows[chunk] = withContext(Dispatchers.Default) { d.rowsOf(part) }
|
||||
}
|
||||
}
|
||||
GameRowView(loaded?.getOrNull(place % CHUNK)) { onGame(place) }
|
||||
GameRowView(loaded?.getOrNull(place % CHUNK)) { onGame(place, query) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -183,16 +193,30 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (Int) -> Unit) {
|
|||
}
|
||||
|
||||
@Composable
|
||||
private fun Message(title: String, detail: String) {
|
||||
private fun Message(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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a database did not open, in plain words with the next step (§11).
|
||||
@Composable
|
||||
private fun openProblem(e: Throwable): String = when (e) {
|
||||
is SecurityException, is java.io.FileNotFoundException, is ApiException.Io -> stringResource(R.string.open_no_access)
|
||||
is ApiException.Corrupt -> stringResource(R.string.open_corrupt)
|
||||
is ApiException.Empty -> stringResource(R.string.open_empty)
|
||||
is ApiException.Unsupported -> stringResource(R.string.open_unsupported, e.detail)
|
||||
else -> ""
|
||||
}
|
||||
|
||||
/// One game: "White – Black" and the result, then event · year · ECO (§6.2). An
|
||||
/// unfinished game ("*", most book positions) shows no result.
|
||||
@Composable
|
||||
|
|
|
|||
|
|
@ -123,7 +123,6 @@
|
|||
<string name="copy_pgn">Копировать PGN</string>
|
||||
<string name="copy_fen">Копировать FEN</string>
|
||||
<string name="share_game">Поделиться партией</string>
|
||||
<string name="copied">Скопировано</string>
|
||||
<string name="notes">Замечания</string>
|
||||
<string name="engine_state_on">включён</string>
|
||||
<string name="engine_state_off">выключен</string>
|
||||
|
|
@ -134,4 +133,23 @@
|
|||
<string name="move_black">%1$d, чёрные, %2$s</string>
|
||||
<string name="current_move">текущий ход</string>
|
||||
<string name="language">Язык</string>
|
||||
<string name="checkmate">Мат</string>
|
||||
<string name="stalemate">Пат</string>
|
||||
<string name="pgn_copied">PGN скопирован</string>
|
||||
<string name="fen_copied">FEN скопирован</string>
|
||||
<string name="tag_event">Турнир</string>
|
||||
<string name="tag_site">Место</string>
|
||||
<string name="tag_date">Дата</string>
|
||||
<string name="tag_round">Тур</string>
|
||||
<string name="tag_white">Белые</string>
|
||||
<string name="tag_black">Чёрные</string>
|
||||
<string name="tag_result">Результат</string>
|
||||
<string name="tag_white_elo">Эло белых</string>
|
||||
<string name="tag_black_elo">Эло чёрных</string>
|
||||
<string name="tag_annotator">Комментатор</string>
|
||||
<string name="tag_plies">Полуходов</string>
|
||||
<string name="open_no_access">Нет доступа к файлу: его переместили, удалили или отозвали разрешение. Уберите базу из списка и добавьте снова.</string>
|
||||
<string name="open_corrupt">Файл повреждён или это не шахматная база.</string>
|
||||
<string name="open_empty">В архиве нет базы PGN или ChessBase.</string>
|
||||
<string name="open_unsupported">Такую базу прочитать нельзя: %1$s</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -122,7 +122,6 @@
|
|||
<string name="copy_pgn">Copy PGN</string>
|
||||
<string name="copy_fen">Copy FEN</string>
|
||||
<string name="share_game">Share game</string>
|
||||
<string name="copied">Copied</string>
|
||||
<string name="notes">Notes</string>
|
||||
<string name="engine_state_on">on</string>
|
||||
<string name="engine_state_off">off</string>
|
||||
|
|
@ -133,4 +132,23 @@
|
|||
<string name="move_black">%1$d, Black, %2$s</string>
|
||||
<string name="current_move">current move</string>
|
||||
<string name="language">Language</string>
|
||||
<string name="checkmate">Checkmate</string>
|
||||
<string name="stalemate">Stalemate</string>
|
||||
<string name="pgn_copied">PGN copied</string>
|
||||
<string name="fen_copied">FEN copied</string>
|
||||
<string name="tag_event">Event</string>
|
||||
<string name="tag_site">Site</string>
|
||||
<string name="tag_date">Date</string>
|
||||
<string name="tag_round">Round</string>
|
||||
<string name="tag_white">White</string>
|
||||
<string name="tag_black">Black</string>
|
||||
<string name="tag_result">Result</string>
|
||||
<string name="tag_white_elo">White Elo</string>
|
||||
<string name="tag_black_elo">Black Elo</string>
|
||||
<string name="tag_annotator">Annotator</string>
|
||||
<string name="tag_plies">Plies</string>
|
||||
<string name="open_no_access">No access to the file: it was moved, deleted or its permission was taken back. Remove it from the list and add it again.</string>
|
||||
<string name="open_corrupt">The file is damaged or is not a chess database.</string>
|
||||
<string name="open_empty">There is no PGN or ChessBase database in the archive.</string>
|
||||
<string name="open_unsupported">This kind of database cannot be read: %1$s</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -36,7 +36,7 @@ pub enum EngineFailure {
|
|||
pub struct EngineLine {
|
||||
/// 1 for the best line.
|
||||
pub multipv: u32,
|
||||
/// "+0.45", "−1.20", "0.00", "#3" (White mates), "−#2" (Black mates).
|
||||
/// "+0.45", "−1.20", "0.00", "#3" (White mates), "#−2" (Black mates).
|
||||
pub eval: String,
|
||||
/// Centipawns for White, when the score is not a mate.
|
||||
pub cp: Option<i32>,
|
||||
|
|
@ -288,7 +288,7 @@ fn engine_line(root: &Chess, multipv: u32, score: Score, pv: &[String]) -> Engin
|
|||
if winner == Side::White {
|
||||
(format!("#{n}"), None, Some(n))
|
||||
} else {
|
||||
(format!("\u{2212}#{n}"), None, Some(-n))
|
||||
(format!("#\u{2212}{n}"), None, Some(-n))
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
@ -366,7 +366,7 @@ mod tests {
|
|||
(Some("e7"), Some("e5"))
|
||||
);
|
||||
let m = engine_line(&black_to_move, 1, Score::Mate(2), &[]);
|
||||
assert_eq!((m.eval.as_str(), m.mate), ("\u{2212}#2", Some(-2)));
|
||||
assert_eq!((m.eval.as_str(), m.mate), ("#\u{2212}2", Some(-2)));
|
||||
assert_eq!(pawns(0), "0.00");
|
||||
assert_eq!(pawns(-120), "\u{2212}1.20");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ use std::sync::Arc;
|
|||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use chess_core::{Game, MoveKind, NodeId};
|
||||
use shakmaty::Position;
|
||||
|
||||
mod engine;
|
||||
|
||||
|
|
@ -118,6 +119,8 @@ pub struct MoveNode {
|
|||
pub uci: String,
|
||||
/// Arrows (`[%cal]`) and marked squares (`[%csl]`) of the comments after the move.
|
||||
pub marks: Vec<Mark>,
|
||||
/// "checkmate" or "stalemate" when the game cannot go on from here; "" otherwise.
|
||||
pub end: String,
|
||||
/// On the main line of the game (not inside a variation).
|
||||
pub main_line: bool,
|
||||
}
|
||||
|
|
@ -442,6 +445,19 @@ fn game_data(game: &Game, diagnostics: &[chess_core::Diagnostic]) -> GameData {
|
|||
null_move: mv.is_some_and(|m| matches!(m.kind, MoveKind::Null)),
|
||||
uci: uci.clone().unwrap_or_default(),
|
||||
marks: node.map(|n| marks(n.comments_after())).unwrap_or_default(),
|
||||
end: game
|
||||
.position(id)
|
||||
.map(|p| {
|
||||
if p.is_checkmate() {
|
||||
"checkmate"
|
||||
} else if p.is_stalemate() {
|
||||
"stalemate"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
})
|
||||
.unwrap_or("")
|
||||
.to_owned(),
|
||||
main_line: id == NodeId::ROOT || main.contains(&id),
|
||||
}
|
||||
})
|
||||
|
|
@ -504,6 +520,10 @@ mod tests {
|
|||
]
|
||||
);
|
||||
assert!(g.nodes[0].uci.is_empty());
|
||||
assert!(g.nodes.iter().all(|n| n.end.is_empty()));
|
||||
let mate = open_bytes("m.pgn".into(), b"1. f3 e5 2. g4 Qh4# 0-1\n".to_vec()).unwrap();
|
||||
let g = mate.game(0).unwrap();
|
||||
assert_eq!(g.nodes.last().unwrap().end, "checkmate");
|
||||
assert!(db.pgn(0).unwrap().contains("[%cal Ge2e4,Rd7d5]"));
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue