Android: games from Lichess and Chess.com, newest first, with «Download new games»

The downloads of the desktop (lookup by nickname, one database per site or both in one,
resuming without duplicates, games still being played fetched once they end) move into a
shared crate, online-games; the desktop keeps its window on top of it.

On Android, «Add a database» → «Games from Lichess and Chess.com»: a nickname, what each
site has, the download with its progress. It belongs to the app, not to the screen: the
list of databases shows how it goes and says how it ended. «Download new games» in the
database's menu and over its games list fetches only the new ones. The games of a
downloaded database are listed from the most recent one (by UTC date and time, both sites
interleaved). Both builds may now use the internet, only when the user asks.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-23 16:37:16 +03:00
parent 0ca444ed8d
commit f6072cb7c3
29 changed files with 3094 additions and 1299 deletions

View file

@ -4,6 +4,17 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https
## [Unreleased] ## [Unreleased]
- Android: **games from Lichess and Chess.com** — «Add a database» → «Games from Lichess
and Chess.com»: any player's games by nickname (yours, a pupil's, an opponent's; no login,
another nickname for Chess.com if it differs) become a database on the phone, both sites
merged into one by default. «Download new games» — in the database's menu and over its
games list — fetches only the games played since; a download that was stopped, failed or
cut off by a closed app continues where it stopped, without duplicates. The games of such
a database are listed from the most recent one. The download goes on when the screen is
left; the list shows its progress and says how it ended. Only standard chess is kept. The
app asks the sites only when told to (both builds may now use the internet for this).
- The downloads of games from Lichess and Chess.com are one shared part of the desktop and
Android apps.
- Android: the status bar and the navigation bar follow the theme chosen in the app: with - Android: the status bar and the navigation bar follow the theme chosen in the app: with
the dark theme on a light phone their icons are light again (they stayed dark on dark). the dark theme on a light phone their icons are light again (they stayed dark on dark).

12
Cargo.lock generated
View file

@ -806,6 +806,7 @@ dependencies = [
"game-review", "game-review",
"getrandom 0.3.4", "getrandom 0.3.4",
"image", "image",
"online-games",
"rfd", "rfd",
"rodio", "rodio",
"serde", "serde",
@ -2416,6 +2417,7 @@ dependencies = [
"chess-core", "chess-core",
"chess-import", "chess-import",
"game-review", "game-review",
"online-games",
"shakmaty", "shakmaty",
"thiserror 2.0.21", "thiserror 2.0.21",
"uci", "uci",
@ -3003,6 +3005,16 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "online-games"
version = "0.13.0"
dependencies = [
"chess-core",
"serde",
"serde_json",
"ureq",
]
[[package]] [[package]]
name = "option-ext" name = "option-ext"
version = "0.2.0" version = "0.2.0"

View file

@ -5,6 +5,7 @@ members = [
"crates/chess-import", "crates/chess-import",
"crates/uci", "crates/uci",
"crates/game-review", "crates/game-review",
"crates/online-games",
"crates/mobile-api", "crates/mobile-api",
"apps/desktop", "apps/desktop",
] ]
@ -37,6 +38,7 @@ chess-core = { path = "crates/chess-core" }
chess-import = { path = "crates/chess-import" } chess-import = { path = "crates/chess-import" }
uci = { path = "crates/uci" } uci = { path = "crates/uci" }
game-review = { path = "crates/game-review" } game-review = { path = "crates/game-review" }
online-games = { path = "crates/online-games" }
[profile.dev.package."*"] [profile.dev.package."*"]
opt-level = 2 opt-level = 2

View file

@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- Only this build goes online: to download the network of Stockfish on request. --> <!-- This build also downloads the network of Stockfish on request (on Wi-Fi or not). -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest> </manifest>

View file

@ -1,5 +1,7 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Games from Lichess and Chess.com, only when asked for (android-ui.md §23). -->
<uses-permission android:name="android.permission.INTERNET" />
<application <application
android:name=".ChessPenguinApp" android:name=".ChessPenguinApp"

View file

@ -9,6 +9,7 @@ import android.provider.OpenableColumns
import io.github.vrubelroman.chesspenguin.data.DbEntry import io.github.vrubelroman.chesspenguin.data.DbEntry
import io.github.vrubelroman.chesspenguin.data.EngineFiles import io.github.vrubelroman.chesspenguin.data.EngineFiles
import io.github.vrubelroman.chesspenguin.data.Library import io.github.vrubelroman.chesspenguin.data.Library
import io.github.vrubelroman.chesspenguin.data.OnlineDownloads
import io.github.vrubelroman.chesspenguin.data.Settings import io.github.vrubelroman.chesspenguin.data.Settings
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
@ -28,6 +29,8 @@ class ChessPenguinApp : Application() {
val library by lazy { Library(this) } val library by lazy { Library(this) }
val settings by lazy { Settings(this) } val settings by lazy { Settings(this) }
val engineFiles by lazy { EngineFiles(this, scope) } val engineFiles by lazy { EngineFiles(this, scope) }
/// Games from Lichess and Chess.com being downloaded (android-ui.md §23).
val downloads by lazy { OnlineDownloads(library, scope) }
/// The games shown on the list of each database (after a search), for paging /// The games shown on the list of each database (after a search), for paging
/// games from the game screen: database id → game numbers. /// games from the game screen: database id → game numbers.

View file

@ -29,6 +29,8 @@ import io.github.vrubelroman.chesspenguin.ui.app
import io.github.vrubelroman.chesspenguin.ui.openProblem import io.github.vrubelroman.chesspenguin.ui.openProblem
import androidx.navigation3.runtime.NavKey import androidx.navigation3.runtime.NavKey
import androidx.navigation3.runtime.entryProvider import androidx.navigation3.runtime.entryProvider
import androidx.navigation3.runtime.rememberSaveableStateHolderNavEntryDecorator
import androidx.lifecycle.viewmodel.navigation3.rememberViewModelStoreNavEntryDecorator
import androidx.navigation3.runtime.rememberNavBackStack import androidx.navigation3.runtime.rememberNavBackStack
import androidx.navigation3.ui.NavDisplay import androidx.navigation3.ui.NavDisplay
import io.github.vrubelroman.chesspenguin.ui.AboutScreen import io.github.vrubelroman.chesspenguin.ui.AboutScreen
@ -37,6 +39,7 @@ import io.github.vrubelroman.chesspenguin.ui.DatabasesScreen
import io.github.vrubelroman.chesspenguin.ui.SettingsScreen import io.github.vrubelroman.chesspenguin.ui.SettingsScreen
import io.github.vrubelroman.chesspenguin.ui.GameScreen import io.github.vrubelroman.chesspenguin.ui.GameScreen
import io.github.vrubelroman.chesspenguin.ui.GamesScreen import io.github.vrubelroman.chesspenguin.ui.GamesScreen
import io.github.vrubelroman.chesspenguin.ui.OnlineScreen
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
@Serializable data object Databases : NavKey @Serializable data object Databases : NavKey
@ -53,6 +56,8 @@ import kotlinx.serialization.Serializable
@Serializable data object BoardStyleKey : NavKey @Serializable data object BoardStyleKey : NavKey
@Serializable data object OnlineKey : NavKey
@Composable @Composable
fun MainNavigation() { fun MainNavigation() {
val backStack = rememberNavBackStack(Databases) val backStack = rememberNavBackStack(Databases)
@ -92,9 +97,20 @@ fun MainNavigation() {
NavDisplay( NavDisplay(
backStack = backStack, backStack = backStack,
onBack = { backStack.removeLastOrNull() }, onBack = { backStack.removeLastOrNull() },
// Each screen keeps its own saved state and view models: they go with the screen
// when it leaves the stack (the search of the online screen must not outlive it).
entryDecorators = listOf(
rememberSaveableStateHolderNavEntryDecorator(),
rememberViewModelStoreNavEntryDecorator(),
),
entryProvider = entryProvider { entryProvider = entryProvider {
entry<Databases> { entry<Databases> {
DatabasesScreen(onOpen = { backStack.add(Games(it)) }, onAdded = ::show, onSettings = { backStack.add(SettingsKey) }) DatabasesScreen(
onOpen = { backStack.add(Games(it)) },
onAdded = ::show,
onSettings = { backStack.add(SettingsKey) },
onOnline = { backStack.add(OnlineKey) },
)
} }
entry<Games> { key -> entry<Games> { key ->
GamesScreen(key.db, onBack = { backStack.removeLastOrNull() }, onGame = { place, query -> backStack.add(GameAt(key.db, place, query)) }) GamesScreen(key.db, onBack = { backStack.removeLastOrNull() }, onGame = { place, query -> backStack.add(GameAt(key.db, place, query)) })
@ -112,6 +128,16 @@ fun MainNavigation() {
entry<BoardStyleKey> { entry<BoardStyleKey> {
BoardStyleScreen(onBack = { backStack.removeLastOrNull() }) BoardStyleScreen(onBack = { backStack.removeLastOrNull() })
} }
entry<OnlineKey> {
OnlineScreen(
onBack = { backStack.removeLastOrNull() },
// The downloaded database instead of this screen: "back" goes to the list.
onOpen = { id ->
backStack.removeLastOrNull()
backStack.add(Games(id))
},
)
}
entry<AboutKey> { entry<AboutKey> {
AboutScreen(onBack = { backStack.removeLastOrNull() }) AboutScreen(onBack = { backStack.removeLastOrNull() })
} }

View file

@ -39,6 +39,10 @@ enum class Source {
/// A copy kept inside the app (`files/copies/`): games pasted from the clipboard, a /// A copy kept inside the app (`files/copies/`): games pasted from the clipboard, a
/// file opened from another app, which gives access to it only for a while. /// file opened from another app, which gives access to it only for a while.
Copy, Copy,
/// A player's games downloaded from Lichess and Chess.com (`files/online/`, with the
/// state of the download beside it, android-ui.md §23).
Online,
} }
/// A database on the list. The file itself is never changed. /// A database on the list. The file itself is never changed.
@ -63,6 +67,8 @@ data class DbEntry(
val renamed: Boolean = false, val renamed: Boolean = false,
/// A copy's SHA-256: the same file opened again is not copied twice. /// A copy's SHA-256: the same file opened again is not copied twice.
val sha256: String? = null, val sha256: String? = null,
/// A downloaded database: when its last download finished (Unix seconds).
val updated: Long? = null,
) )
/// Text or a file with no games in it. /// Text or a file with no games in it.
@ -111,6 +117,8 @@ data class FolderScan(val tree: Uri, val name: String, val found: List<Found>)
class Library(private val context: Context) { class Library(private val context: Context) {
private val file = File(context.filesDir, "library.json") private val file = File(context.filesDir, "library.json")
private val copies = File(context.filesDir, "copies") private val copies = File(context.filesDir, "copies")
/// Downloaded databases (android-ui.md §23).
val onlineDir = File(context.filesDir, "online")
private val json = Json { ignoreUnknownKeys = true } private val json = Json { ignoreUnknownKeys = true }
private val _entries = MutableStateFlow(load()) private val _entries = MutableStateFlow(load())
val entries: StateFlow<List<DbEntry>> = _entries.asStateFlow() val entries: StateFlow<List<DbEntry>> = _entries.asStateFlow()
@ -124,6 +132,16 @@ class Library(private val context: Context) {
init { init {
releaseUnused() releaseUnused()
// A download cut short by a closed app wrote games the list does not know of yet.
update { list -> list.map(::withOnlineState) }
}
/// A downloaded database with the number of games and the time of its last download
/// as its state file has them (they change while the list does not look).
private fun withOnlineState(e: DbEntry): DbEntry {
if (e.source != Source.Online) return e
val info = uniffi.mobile_api.onlineDatabase(onlineFile(e).path) ?: return e
return e.copy(games = info.games.toInt(), updated = info.updated ?: e.updated)
} }
/// Gives back the access to files and folders no database on the list uses (a /// Gives back the access to files and folders no database on the list uses (a
@ -132,6 +150,13 @@ class Library(private val context: Context) {
private fun releaseUnused() { private fun releaseUnused() {
val kept = _entries.value.filter { it.source == Source.Copy }.map { it.location }.toSet() val kept = _entries.value.filter { it.source == Source.Copy }.map { it.location }.toSet()
copies.listFiles()?.filter { it.name !in kept }?.forEach { it.delete() } copies.listFiles()?.filter { it.name !in kept }?.forEach { it.delete() }
// A downloaded database left behind (the app closed while "Undo" was offered).
// Names may hold dots ("Name (Lichess + Chess.com).pgn"): whole names are compared.
val online = _entries.value.filter { it.source == Source.Online }.flatMap {
val stem = it.location.removeSuffix(".pgn")
listOf("$stem.pgn", "$stem.online.json", "$stem.online.lock")
}.toSet()
onlineDir.listFiles()?.filter { it.name !in online }?.forEach { it.delete() }
val used = _entries.value.mapNotNull { it.tree ?: it.location.takeIf { _ -> it.source == Source.File || it.source == Source.ChessBase } }.toSet() val used = _entries.value.mapNotNull { it.tree ?: it.location.takeIf { _ -> it.source == Source.File || it.source == Source.ChessBase } }.toSet()
for (p in context.contentResolver.persistedUriPermissions) { for (p in context.contentResolver.persistedUriPermissions) {
if (p.uri.toString() !in used) { if (p.uri.toString() !in used) {
@ -263,6 +288,42 @@ class Library(private val context: Context) {
} }
} }
/// The file of a downloaded database.
fun onlineFile(e: DbEntry): File = File(onlineDir, e.location)
/// Puts a downloaded database (a file of [onlineDir]) on the list, or gives its entry.
fun addOnline(file: File): DbEntry = synchronized(this) {
_entries.value.firstOrNull { it.source == Source.Online && it.location == file.name }?.let { return it }
val entry = DbEntry(
id = UUID.randomUUID().toString(),
name = file.name.substringBeforeLast('.'),
source = Source.Online,
location = file.name,
fileName = file.name,
games = 0,
format = "PGN",
)
update { it + entry }
entry
}
/// A downloaded database got new games: it is read again when next opened. The old
/// one is not closed: a screen may still show it; it is freed once nothing holds it.
suspend fun downloaded(id: String, games: Int, updated: Long?) {
lock.withLock {
open.remove(id)
update { list -> list.map { if (it.id == id) it.copy(games = games, updated = updated ?: it.updated) else it } }
}
}
/// Takes a downloaded database that got no games off the list, with its files.
fun dropEmpty(id: String) {
val e = entry(id) ?: return
update { it.filterNot { x -> x.id == id } }
open.remove(id)?.close()
uniffi.mobile_api.deleteOnlineDatabase(onlineFile(e).path)
}
fun rename(id: String, name: String) = update { list -> list.map { if (it.id == id) it.copy(name = name, renamed = true) else it } } 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, /// Takes the database off the list (the file stays where it is). Returns its place,
@ -286,6 +347,10 @@ class Library(private val context: Context) {
File(copies, entry.location).delete() File(copies, entry.location).delete()
return return
} }
if (entry.source == Source.Online) {
uniffi.mobile_api.deleteOnlineDatabase(onlineFile(entry).path)
return
}
// The permission of a folder is given back with the last of its databases, also // The permission of a folder is given back with the last of its databases, also
// counting those whose "Undo" is still offered. // counting those whose "Undo" is still offered.
val granted = entry.tree ?: entry.location val granted = entry.tree ?: entry.location
@ -433,7 +498,8 @@ class Library(private val context: Context) {
fun restore(place: Int, entry: DbEntry) { fun restore(place: Int, entry: DbEntry) {
pending.remove(entry) pending.remove(entry)
update { it.toMutableList().apply { add(place.coerceIn(0, size), entry) } } // A download may have gone on while it was off the list.
update { it.toMutableList().apply { add(place.coerceIn(0, size), withOnlineState(entry)) } }
} }
/// The same file on the list, picked through another way (its URI differs). /// The same file on the list, picked through another way (its URI differs).
@ -452,6 +518,14 @@ class Library(private val context: Context) {
} }
}.getOrNull() }.getOrNull()
/// The games of a database that `query` finds, in the order the list shows them: a
/// downloaded database from the most recent game down (android-ui.md §23), the others
/// as in the file. Slow for a big database: call it off the main thread.
fun listed(id: String, db: Database, query: String): List<UInt> {
val found = db.find(query)
return if (entry(id)?.source == Source.Online) db.newestFirst(found) else found
}
/// The open database of an entry (opened in the background the first time). /// The open database of an entry (opened in the background the first time).
suspend fun database(id: String): Result<Database> = lock.withLock { suspend fun database(id: String): Result<Database> = lock.withLock {
open[id]?.let { return@withLock Result.success(it) } open[id]?.let { return@withLock Result.success(it) }
@ -466,6 +540,10 @@ class Library(private val context: Context) {
e.fileName, e.fileName,
android.os.ParcelFileDescriptor.open(File(copies, e.location), android.os.ParcelFileDescriptor.MODE_READ_ONLY).detachFd(), android.os.ParcelFileDescriptor.open(File(copies, e.location), android.os.ParcelFileDescriptor.MODE_READ_ONLY).detachFd(),
) )
Source.Online -> openFile(
e.fileName,
android.os.ParcelFileDescriptor.open(onlineFile(e), android.os.ParcelFileDescriptor.MODE_READ_ONLY).detachFd(),
)
} }
} }
} }

View file

@ -0,0 +1,89 @@
package io.github.vrubelroman.chesspenguin.data
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import uniffi.mobile_api.DownloadState
import uniffi.mobile_api.OnlineAccount
import uniffi.mobile_api.OnlineDownload
import uniffi.mobile_api.onlineDatabase
import java.io.File
import java.util.concurrent.ConcurrentHashMap
/// A download of a database and how it stands (or how it ended); `fresh` when the
/// database did not exist before it (its first download).
data class DownloadView(val accounts: List<OnlineAccount>, val state: DownloadState, val fresh: Boolean = false)
/// A download that has ended, for the snackbar of the screen that is shown then.
data class Finished(val id: String, val name: String, val view: DownloadView, val games: Int)
/// The downloads of games from Lichess and Chess.com (android-ui.md §23). They belong to
/// the app, not to a screen: leaving the screen does not stop them, and the list of
/// databases shows how they go.
class OnlineDownloads(private val library: Library, private val scope: CoroutineScope) {
private val _views = MutableStateFlow<Map<String, DownloadView>>(emptyMap())
/// By database id: the running downloads, and the last one of each database.
val views: StateFlow<Map<String, DownloadView>> = _views.asStateFlow()
private val running = ConcurrentHashMap<String, OnlineDownload>()
private val _finished = MutableSharedFlow<Finished>(extraBufferCapacity = 8)
/// Each download as it ends (android-ui.md §23.3: a snackbar says how it went).
val finished: SharedFlow<Finished> = _finished.asSharedFlow()
/// Where the downloaded databases are kept.
val dir: File get() = library.onlineDir
/// Starts fetching the new games of `accounts` into the database file `path` (put on
/// the list at once); one download per database. Returns the database's entry.
fun start(accounts: List<OnlineAccount>, path: String): DbEntry {
val fresh = !File(path).exists()
val entry = library.addOnline(File(path))
if (running.containsKey(entry.id)) return entry
val d = OnlineDownload.start(accounts, path)
running[entry.id] = d
scope.launch(Dispatchers.IO) {
while (true) {
val s = d.state()
_views.update { it + (entry.id to DownloadView(accounts, s, fresh)) }
if (!s.running) break
delay(POLL_MS)
}
running.remove(entry.id)
d.close()
val info = onlineDatabase(path)
val games = info?.games?.toInt() ?: 0
// No game at all (no standard chess there, or it failed at once): not a database.
val name = library.entry(entry.id)?.name ?: entry.name
if (games == 0) library.dropEmpty(entry.id) else library.downloaded(entry.id, games, info?.updated)
_views.value[entry.id]?.let { _finished.tryEmit(Finished(entry.id, name, it, games)) }
}
return entry
}
/// Fetches the games played since the last download of a database.
fun update(entry: DbEntry) {
val path = library.onlineFile(entry).path
val info = onlineDatabase(path) ?: return
start(info.accounts, path)
}
/// Stops a download; what it fetched stays.
fun cancel(id: String) {
running[id]?.cancel()
}
fun isRunning(id: String): Boolean = running.containsKey(id)
private companion object {
const val POLL_MS = 400L
}
}

View file

@ -17,6 +17,7 @@ import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.selection.toggleable import androidx.compose.foundation.selection.toggleable
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.CloudDownload
import androidx.compose.material.icons.outlined.ContentPaste import androidx.compose.material.icons.outlined.ContentPaste
import androidx.compose.material.icons.outlined.Description import androidx.compose.material.icons.outlined.Description
import androidx.compose.material.icons.outlined.Folder import androidx.compose.material.icons.outlined.Folder
@ -52,10 +53,11 @@ import io.github.vrubelroman.chesspenguin.data.FolderScan
import io.github.vrubelroman.chesspenguin.data.Found import io.github.vrubelroman.chesspenguin.data.Found
import io.github.vrubelroman.chesspenguin.data.Source import io.github.vrubelroman.chesspenguin.data.Source
/// "Add a database": games in the clipboard, a file, or every database in a folder. /// "Add a database": games in the clipboard, a file, every database in a folder, or a
/// player's games from Lichess and Chess.com.
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun AddSheet(onFile: () -> Unit, onFolder: () -> Unit, onPaste: (() -> Unit)?, onDismiss: () -> Unit) { fun AddSheet(onFile: () -> Unit, onFolder: () -> Unit, onPaste: (() -> Unit)?, onOnline: () -> Unit, onDismiss: () -> Unit) {
ModalBottomSheet(onDismissRequest = onDismiss) { ModalBottomSheet(onDismissRequest = onDismiss) {
Column(Modifier.navigationBarsPadding().padding(bottom = 24.dp)) { Column(Modifier.navigationBarsPadding().padding(bottom = 24.dp)) {
Text( Text(
@ -74,6 +76,13 @@ fun AddSheet(onFile: () -> Unit, onFolder: () -> Unit, onPaste: (() -> Unit)?, o
modifier = Modifier.clickable(role = Role.Button, onClick = onPaste).padding(horizontal = 8.dp), modifier = Modifier.clickable(role = Role.Button, onClick = onPaste).padding(horizontal = 8.dp),
) )
} }
ListItem(
headlineContent = { Text(stringResource(R.string.online_title)) },
supportingContent = { Text(stringResource(R.string.add_online_hint)) },
leadingContent = { Icon(Icons.Outlined.CloudDownload, null) },
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
modifier = Modifier.clickable(role = Role.Button, onClick = onOnline).padding(horizontal = 8.dp),
)
ListItem( ListItem(
headlineContent = { Text(stringResource(R.string.add_file)) }, headlineContent = { Text(stringResource(R.string.add_file)) },
supportingContent = { Text(stringResource(R.string.add_file_hint)) }, supportingContent = { Text(stringResource(R.string.add_file_hint)) },

View file

@ -37,6 +37,7 @@ import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult import androidx.compose.material3.SnackbarResult
@ -69,6 +70,9 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import io.github.vrubelroman.chesspenguin.R import io.github.vrubelroman.chesspenguin.R
import androidx.compose.material3.LinearProgressIndicator
import io.github.vrubelroman.chesspenguin.data.DownloadView
import io.github.vrubelroman.chesspenguin.data.Finished
import io.github.vrubelroman.chesspenguin.data.DbEntry import io.github.vrubelroman.chesspenguin.data.DbEntry
import io.github.vrubelroman.chesspenguin.data.FolderScan import io.github.vrubelroman.chesspenguin.data.FolderScan
import io.github.vrubelroman.chesspenguin.data.Source import io.github.vrubelroman.chesspenguin.data.Source
@ -78,13 +82,27 @@ import kotlinx.coroutines.launch
/// The first screen: the databases on the list (android-ui.md §3). /// The first screen: the databases on the list (android-ui.md §3).
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSettings: () -> Unit) { fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSettings: () -> Unit, onOnline: () -> Unit) {
val library = app().library val library = app().library
val downloads = app().downloads
val views by downloads.views.collectAsState()
val entries by library.entries.collectAsState() val entries by library.entries.collectAsState()
val snackbar = remember { SnackbarHostState() } val snackbar = remember { SnackbarHostState() }
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
val removedText = stringResource(R.string.removed) val removedText = stringResource(R.string.removed)
val removedCopyText = stringResource(R.string.removed_copy) val removedCopyText = stringResource(R.string.removed_copy)
val removedOnlineText = stringResource(R.string.online_removed)
val resourcesForSnack = LocalResources.current
val openText = stringResource(R.string.online_open_short)
// How a download ended, said while this screen is shown (android-ui.md §23.3).
LaunchedEffect(Unit) {
downloads.finished.collect { f ->
val text = finishedText(resourcesForSnack, f) ?: return@collect
snackbar.currentSnackbarData?.dismiss()
val canOpen = f.games > 0 && library.entry(f.id) != null
if (snackbar.showSnackbar(text, if (canOpen) openText else null, withDismissAction = false) == SnackbarResult.ActionPerformed) onOpen(f.id)
}
}
val undoText = stringResource(R.string.undo) val undoText = stringResource(R.string.undo)
val pick = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> val pick = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) onOpen(library.addFile(uri).id) if (uri != null) onOpen(library.addFile(uri).id)
@ -157,17 +175,27 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett
items(entries, key = { it.id }) { e -> items(entries, key = { it.id }) { e ->
DatabaseRow( DatabaseRow(
e, e,
download = views[e.id],
onOpen = { onOpen(e.id) }, onOpen = { onOpen(e.id) },
onRename = { renaming = e }, onRename = { renaming = e },
onUpdate = { downloads.update(e) },
onStop = { downloads.cancel(e.id) },
onRemove = { onRemove = {
// A download into it stops first: its file goes with it.
downloads.cancel(e.id)
val removed = library.remove(e.id) ?: return@DatabaseRow val removed = library.remove(e.id) ?: return@DatabaseRow
scope.launch { scope.launch {
snackbar.currentSnackbarData?.dismiss() snackbar.currentSnackbarData?.dismiss()
var restored = false var restored = false
try { try {
// A copy is deleted, not only taken off the list. // A copy is deleted, not only taken off the list.
val text = if (e.source == Source.Copy) removedCopyText else removedText val text = when (e.source) {
if (snackbar.showSnackbar(text, undoText, withDismissAction = false) == SnackbarResult.ActionPerformed) { Source.Copy -> removedCopyText
Source.Online -> removedOnlineText
else -> removedText
}
// Not for ever: the deleted file goes once "Undo" is gone.
if (snackbar.showSnackbar(text, undoText, withDismissAction = false, duration = SnackbarDuration.Long) == SnackbarResult.ActionPerformed) {
library.restore(removed.first, removed.second) library.restore(removed.first, removed.second)
restored = true restored = true
} }
@ -216,6 +244,10 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett
} }
} }
}, },
onOnline = {
choosing = false
onOnline()
},
onDismiss = { choosing = false }, onDismiss = { choosing = false },
) )
} }
@ -283,45 +315,85 @@ private fun Empty(modifier: Modifier, onAdd: () -> Unit, onSamples: () -> Unit)
@OptIn(ExperimentalFoundationApi::class) @OptIn(ExperimentalFoundationApi::class)
@Composable @Composable
private fun DatabaseRow(e: DbEntry, onOpen: () -> Unit, onRename: () -> Unit, onRemove: () -> Unit, modifier: Modifier) { private fun DatabaseRow(
e: DbEntry,
download: DownloadView?,
onOpen: () -> Unit,
onRename: () -> Unit,
onUpdate: () -> Unit,
onStop: () -> Unit,
onRemove: () -> Unit,
modifier: Modifier,
) {
var menu by remember { mutableStateOf(false) } var menu by remember { mutableStateOf(false) }
val format = badge(e) val format = badge(e)
val running = download?.state?.running == true
val failure = download?.state?.failure?.takeIf { !running }
val subtitle = e.games?.let { val subtitle = e.games?.let {
stringResource(R.string.games_with_format, pluralStringResource(R.plurals.games_count, it, groupDigits(it)), e.format ?: format) stringResource(R.string.games_with_format, pluralStringResource(R.plurals.games_count, it, groupDigits(it)), e.format ?: format)
} ?: stringResource(R.string.not_opened, formatName(e)) } ?: stringResource(R.string.not_opened, formatName(e))
// A copy kept in the app says so: removing it deletes it. val shownSubtitle = when {
val shownSubtitle = if (e.source == Source.Copy) subtitle + " · " + stringResource(R.string.db_copy) else subtitle // A copy kept in the app says so: removing it deletes it.
Row( e.source == Source.Copy -> subtitle + " · " + stringResource(R.string.db_copy)
modifier e.source != Source.Online -> subtitle
.fillMaxWidth() // A downloaded database: how its download goes, or when it was last brought up to date.
.height(72.dp) running -> stringResource(R.string.online_downloading, groupDigits(((e.games ?: 0) + download.state.added.toInt())))
.combinedClickable(onClick = onOpen, onLongClick = { menu = true }) else -> pluralStringResource(R.plurals.games_count, e.games ?: 0, groupDigits(e.games ?: 0)) + " · " + when {
.padding(start = 16.dp, end = 4.dp), // The games stay in the line: the database is not empty because a site failed.
verticalAlignment = Alignment.CenterVertically, failure != null -> onlineProblemShort(failure)
) { e.updated == null -> stringResource(R.string.online_unfinished)
FormatBadge(format) System.currentTimeMillis() - e.updated * 1000 < 60_000 -> stringResource(R.string.online_updated_now)
Column(Modifier.weight(1f).padding(start = 16.dp)) { else -> stringResource(
Text(displayName(e), style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) R.string.online_updated,
Text( DateUtils.getRelativeTimeSpanString(e.updated * 1000, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS).toString(),
shownSubtitle,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
) )
} }
Box { }
IconButton(onClick = { menu = true }) { Icon(Icons.Rounded.MoreVert, stringResource(R.string.menu)) } Box(modifier) {
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { Row(
DropdownMenuItem(text = { Text(stringResource(R.string.rename)) }, onClick = { Modifier
menu = false .fillMaxWidth()
onRename() .height(72.dp)
}) .combinedClickable(onClick = onOpen, onLongClick = { menu = true })
DropdownMenuItem(text = { Text(stringResource(R.string.remove)) }, onClick = { .padding(start = 16.dp, end = 4.dp),
menu = false verticalAlignment = Alignment.CenterVertically,
onRemove() ) {
}) FormatBadge(format)
Column(Modifier.weight(1f).padding(start = 16.dp)) {
Text(displayName(e), style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
shownSubtitle,
style = MaterialTheme.typography.bodyMedium,
color = if (failure != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
} }
Box {
IconButton(onClick = { menu = true }) { Icon(Icons.Rounded.MoreVert, stringResource(R.string.menu)) }
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
if (e.source == Source.Online) {
DropdownMenuItem(text = { Text(stringResource(if (running) R.string.online_stop_download else R.string.online_update)) }, onClick = {
menu = false
if (running) onStop() else onUpdate()
})
}
DropdownMenuItem(text = { Text(stringResource(R.string.rename)) }, onClick = {
menu = false
onRename()
})
DropdownMenuItem(text = { Text(stringResource(R.string.remove)) }, onClick = {
menu = false
onRemove()
})
}
}
}
// A download going on: a thin bar along the bottom of the row (§23.3).
if (running) {
val share = downloadShare(download)
val bar = Modifier.fillMaxWidth().height(2.dp).align(Alignment.BottomStart)
if (share != null) LinearProgressIndicator(progress = { share }, modifier = bar) else LinearProgressIndicator(bar)
} }
} }
} }
@ -358,3 +430,16 @@ private fun pastedName(db: Database, dated: String): String {
} }
return dated return dated
} }
/// The snackbar of a finished download: "“Name”: +12, 1 246 games in all", "“Name”: no
/// new games", "“Name”: Lichess does not answer"; none when it was stopped or got nothing.
fun finishedText(res: android.content.res.Resources, f: Finished): String? {
val s = f.view.state
val games = res.getQuantityString(R.plurals.games_count, f.games, groupDigits(f.games))
s.failure?.let { return res.getString(R.string.online_snack_failed, f.name, problemShort(res, it)) }
return when {
s.cancelled || f.games == 0 -> null
s.added == 0UL -> res.getString(R.string.online_snack_none, f.name)
else -> res.getString(R.string.online_snack_added, f.name, groupDigits(s.added.toInt()), games)
}
}

View file

@ -145,7 +145,7 @@ fun GameScreen(db: String, startPlace: Int, query: String, onBack: () -> Unit, o
return@LaunchedEffect return@LaunchedEffect
} }
// After the process was restarted the list is gone: the same search finds it again. // 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 { val list = games ?: withContext(Dispatchers.Default) { app.library.listed(db, database, query) }.also {
games = it games = it
app.shown[db] = it app.shown[db] = it
} }

View file

@ -57,6 +57,13 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import io.github.vrubelroman.chesspenguin.R import io.github.vrubelroman.chesspenguin.R
import io.github.vrubelroman.chesspenguin.data.Source
import androidx.compose.ui.zIndex
import androidx.compose.ui.platform.LocalResources
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material.icons.rounded.Download
import io.github.vrubelroman.chesspenguin.theme.Tabular import io.github.vrubelroman.chesspenguin.theme.Tabular
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
@ -76,7 +83,8 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (place: Int, query: Stri
val entry = entries.firstOrNull { it.id == db } val entry = entries.firstOrNull { it.id == db }
var database by remember { mutableStateOf<Database?>(null) } var database by remember { mutableStateOf<Database?>(null) }
var failed by remember { mutableStateOf<Throwable?>(null) } var failed by remember { mutableStateOf<Throwable?>(null) }
LaunchedEffect(db) { // Read again when a download brought new games into it (android-ui.md §23).
LaunchedEffect(db, entry?.games, entry?.updated) {
app.library.database(db).onSuccess { database = it }.onFailure { failed = it } app.library.database(db).onSuccess { database = it }.onFailure { failed = it }
} }
var searching by rememberSaveable { mutableStateOf(false) } var searching by rememberSaveable { mutableStateOf(false) }
@ -87,7 +95,7 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (place: Int, query: Stri
LaunchedEffect(database, query) { LaunchedEffect(database, query) {
val d = database ?: return@LaunchedEffect val d = database ?: return@LaunchedEffect
if (query.isNotEmpty()) delay(250) if (query.isNotEmpty()) delay(250)
val found = withContext(Dispatchers.Default) { d.find(query) } val found = withContext(Dispatchers.Default) { app.library.listed(db, d, query) }
rows.clear() rows.clear()
shown = found shown = found
// New results start at the top. // New results start at the top.
@ -95,6 +103,18 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (place: Int, query: Stri
app.shown[db] = found app.shown[db] = found
} }
val scroll = TopAppBarDefaults.pinnedScrollBehavior() val scroll = TopAppBarDefaults.pinnedScrollBehavior()
val download = app.downloads.views.collectAsState().value[db]
val snackbar = remember { SnackbarHostState() }
val resources = LocalResources.current
// How a download of this database ended (§23.3); the list reads it again by itself.
LaunchedEffect(db) {
app.downloads.finished.collect { f ->
if (f.id != db) return@collect
val text = finishedText(resources, f) ?: return@collect
snackbar.currentSnackbarData?.dismiss()
snackbar.showSnackbar(text)
}
}
val focus = remember { FocusRequester() } val focus = remember { FocusRequester() }
val keyboard = LocalSoftwareKeyboardController.current val keyboard = LocalSoftwareKeyboardController.current
BackHandler(searching) { BackHandler(searching) {
@ -153,13 +173,28 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (place: Int, query: Stri
}) { Icon(Icons.Rounded.Close, stringResource(R.string.clear)) } }) { Icon(Icons.Rounded.Close, stringResource(R.string.clear)) }
} else if (database != null) { } else if (database != null) {
IconButton(onClick = { searching = true }) { Icon(Icons.Rounded.Search, stringResource(R.string.search)) } 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.
if (entry?.source == Source.Online) {
if (download?.state?.running == true) {
IconButton(onClick = { app.downloads.cancel(db) }) { Icon(Icons.Rounded.Close, stringResource(R.string.online_stop_download)) }
} else {
IconButton(onClick = { entry.let { app.downloads.update(it) } }) { Icon(Icons.Rounded.Download, stringResource(R.string.online_update)) }
}
}
} }
}, },
scrollBehavior = scroll, scrollBehavior = scroll,
) )
}, },
snackbarHost = { SnackbarHost(snackbar) },
) { padding -> ) { padding ->
Box(Modifier.fillMaxSize().padding(padding)) { Box(Modifier.fillMaxSize().padding(padding)) {
download?.takeIf { it.state.running }?.let { v ->
val share = downloadShare(v)
val bar = Modifier.fillMaxWidth().height(2.dp).align(Alignment.TopStart).zIndex(1f)
if (share != null) LinearProgressIndicator(progress = { share }, modifier = bar) else LinearProgressIndicator(bar)
}
val games = shown val games = shown
when { when {
failed != null -> Message(stringResource(R.string.open_failed), openProblem(failed!!)) { failed != null -> Message(stringResource(R.string.open_failed), openProblem(failed!!)) {

View file

@ -0,0 +1,500 @@
package io.github.vrubelroman.chesspenguin.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
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.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
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.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
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.platform.LocalSoftwareKeyboardController
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.heading
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import io.github.vrubelroman.chesspenguin.R
import io.github.vrubelroman.chesspenguin.data.DownloadView
import io.github.vrubelroman.chesspenguin.data.Source
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import uniffi.mobile_api.AccountLookup
import uniffi.mobile_api.OnlineAccount
import uniffi.mobile_api.OnlineFailure
import uniffi.mobile_api.OnlineProblem
import uniffi.mobile_api.Site
import uniffi.mobile_api.findAccount
import uniffi.mobile_api.onlineDatabase
import uniffi.mobile_api.onlineTargets
import uniffi.mobile_api.validNickname
import java.io.File
import kotlin.math.ceil
/// Lichess gives about this many games a second to an anonymous export.
private const val LICHESS_GAMES_PER_SECOND = 20.0
fun siteName(s: Site): String = when (s) {
Site.LICHESS -> "Lichess"
Site.CHESS_COM -> "Chess.com"
}
/// "1 234 games" in the language of the interface.
@Composable
fun gamesText(n: Long): String {
val k = n.coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
return pluralStringResource(R.plurals.games_count, k, groupDigits(k))
}
/// Seconds Lichess needs for `games` games.
private fun lichessSeconds(games: Long): Double = games / LICHESS_GAMES_PER_SECOND
/// What went wrong, in words for a chess player (android-ui.md §23.4).
@Composable
fun onlineProblemText(f: OnlineFailure): String {
val site = f.site?.let(::siteName) ?: "—"
return when (f.problem) {
OnlineProblem.NETWORK -> stringResource(R.string.online_err_network, site)
OnlineProblem.RATE_LIMITED -> stringResource(R.string.online_err_rate, site)
OnlineProblem.UNEXPECTED -> stringResource(R.string.online_err_unexpected, site)
OnlineProblem.DISK -> stringResource(R.string.online_err_disk)
OnlineProblem.BUSY -> stringResource(R.string.online_err_busy)
}
}
/// The short form, for the subtitle of a database and the snackbar (§23.3).
fun problemShort(res: android.content.res.Resources, f: OnlineFailure): String {
val site = f.site?.let(::siteName)
return when {
site != null && f.problem == OnlineProblem.NETWORK -> res.getString(R.string.online_short_network, site)
site != null && f.problem == OnlineProblem.RATE_LIMITED -> res.getString(R.string.online_short_rate, site)
else -> res.getString(R.string.online_short_failed)
}
}
@Composable
fun onlineProblemShort(f: OnlineFailure): String = problemShort(androidx.compose.ui.platform.LocalResources.current, f)
/// What a running download is doing: "Lichess: 1 200 of about 6 541 · about 5 min left",
/// "Chess.com: month 12 of 84 · 340 games".
@Composable
fun downloadProgressText(v: DownloadView): String {
val s = v.state
val account = v.accounts.getOrNull(s.account.toInt())
val games = s.accountGames.toLong()
return when (account?.site) {
Site.LICHESS -> {
val total = account.games?.toLong() ?: 0
if (total > games) {
val minutes = ceil(lichessSeconds(total - games) / 60.0).toInt().coerceAtLeast(1)
stringResource(R.string.online_progress_lichess, groupDigits(games.toInt()), groupDigits(total.toInt()), minutes)
} else {
stringResource(R.string.online_progress_count, "Lichess", gamesText(games))
}
}
Site.CHESS_COM -> if (s.monthsTotal > 0u) {
stringResource(R.string.online_progress_chesscom, s.monthsDone.toInt(), s.monthsTotal.toInt(), gamesText(games))
} else {
stringResource(R.string.online_progress_count, "Chess.com", gamesText(games))
}
null -> stringResource(R.string.online_downloading, groupDigits(s.added.toInt()))
}
}
/// How a finished download went: "Done: 473 games" the first time, "+12, 1 246 games in
/// all" later.
@Composable
fun downloadResultText(v: DownloadView): String {
val s = v.state
s.failure?.let { return onlineProblemText(it) }
val total = s.total?.toLong() ?: 0
return when {
s.cancelled -> stringResource(R.string.online_stopped, gamesText(total))
total == 0L -> stringResource(R.string.online_no_games)
s.added == 0UL -> stringResource(R.string.online_no_new, gamesText(total))
v.fresh -> stringResource(R.string.online_done, gamesText(total))
else -> stringResource(R.string.online_added, groupDigits(s.added.toInt()), gamesText(total))
}
}
/// The share of the whole download done, when it is known: each account is an equal part
/// (Lichess counted by its games, Chess.com by months).
fun downloadShare(v: DownloadView): Float? {
val s = v.state
val i = s.account.toInt()
val account = v.accounts.getOrNull(i) ?: return null
val part = when (account.site) {
Site.LICHESS -> account.games?.takeIf { it > 0UL }?.let { (s.accountGames.toDouble() / it.toDouble()).toFloat() }
Site.CHESS_COM -> s.monthsTotal.takeIf { it > 0u }?.let { s.monthsDone.toFloat() / it.toFloat() }
} ?: return null
return ((i + part.coerceIn(0f, 1f)) / v.accounts.size).coerceIn(0f, 1f)
}
/// The search of the screen: kept when the phone is turned (android-ui.md §23.2).
class OnlineSearch : ViewModel() {
var found by mutableStateOf<Map<Site, AccountLookup>?>(null)
var chosen by mutableStateOf(setOf<Site>())
var searching by mutableStateOf(false)
fun find(forLichess: String, forChessCom: String) {
if (searching) return
searching = true
viewModelScope.launch {
val result = withContext(Dispatchers.IO) {
val li = async { findAccount(Site.LICHESS, forLichess) }
val cc = async { findAccount(Site.CHESS_COM, forChessCom) }
mapOf(Site.LICHESS to li.await(), Site.CHESS_COM to cc.await())
}
found = result
chosen = result.filterValues { it is AccountLookup.Found }.keys
searching = false
}
}
fun forget() {
found = null
}
}
/// A nickname is shown as wrong only for a character it may not have or when it is too
/// long; a short one is still being typed.
private fun badNick(nick: String): Boolean {
val t = nick.trim()
return t.length > 30 || t.any { !(it.isLetterOrDigit() && it.code < 128) && it != '_' && it != '-' }
}
/// "Games from Lichess and Chess.com" (android-ui.md §23.2): a nickname, what was found on
/// each site, the download and how it goes.
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun OnlineScreen(onBack: () -> Unit, onOpen: (String) -> Unit) {
val app = app()
val downloads = app.downloads
val views by downloads.views.collectAsState()
val entries by app.library.entries.collectAsState()
val search: OnlineSearch = viewModel()
val keyboard = LocalSoftwareKeyboardController.current
var nick by rememberSaveable { mutableStateOf("") }
// A different nickname on Chess.com, once asked for.
var other by rememberSaveable { mutableStateOf<String?>(null) }
var together by rememberSaveable { mutableStateOf(true) }
// The databases this screen started downloading; the found accounts are hidden then,
// until the next search.
var started by rememberSaveable { mutableStateOf(listOf<String>()) }
var launched by rememberSaveable { mutableStateOf(false) }
val nickOk = validNickname(nick)
val otherOk = other?.let { it.isBlank() || validNickname(it) } ?: true
fun find() {
if (!nickOk || !otherOk) return
keyboard?.hide()
launched = false
val forLichess = nick.trim()
search.find(forLichess, other?.trim()?.takeIf { it.isNotEmpty() } ?: forLichess)
}
val found = search.found
val accounts: List<OnlineAccount> = found.orEmpty()
.filterKeys { it in search.chosen }
.values.mapNotNull { (it as? AccountLookup.Found)?.account }
val merge = together && accounts.size > 1
// Where the games go, and how many are there already; read again when a download ends.
val ended = started.count { views[it]?.state?.running == false }
val targets by produceState(emptyList<Pair<String, Long?>>(), accounts, merge, ended) {
value = withContext(Dispatchers.IO) {
if (accounts.isEmpty()) {
emptyList()
} else {
onlineTargets(downloads.dir.path, accounts, merge).map { t ->
t.path to (if (t.exists) onlineDatabase(t.path)?.games?.toLong() else null)
}
}
}
}
// A database's name as on the list (it may have been renamed), else its file's.
fun nameOf(path: String): String {
val file = File(path).name
return entries.firstOrNull { it.source == Source.Online && it.location == file }?.name ?: file.removeSuffix(".pgn")
}
Scaffold(
topBar = {
TopAppBar(
navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) } },
title = { Text(stringResource(R.string.online_title)) },
)
},
) { padding ->
Column(
Modifier
.fillMaxSize()
.padding(padding)
.imePadding()
.verticalScroll(rememberScrollState())
.navigationBarsPadding()
.padding(horizontal = 16.dp, vertical = 8.dp),
) {
Text(stringResource(R.string.online_intro), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
Spacer(Modifier.height(16.dp))
NickField(
value = nick,
label = stringResource(if (other == null) R.string.online_nick else R.string.online_nick_lichess),
bad = badNick(nick),
onChange = {
nick = it
search.forget()
},
onDone = ::find,
)
if (other == null) {
TextButton(onClick = { other = "" }, contentPadding = PaddingValues(0.dp)) { Text(stringResource(R.string.online_other)) }
} else {
Spacer(Modifier.height(8.dp))
NickField(
value = other.orEmpty(),
label = stringResource(R.string.online_other_nick),
bad = badNick(other.orEmpty()),
onChange = {
other = it
search.forget()
},
onDone = ::find,
)
TextButton(onClick = {
other = null
search.forget()
}, contentPadding = PaddingValues(0.dp)) { Text(stringResource(R.string.online_same_nick)) }
}
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {
if (search.searching) {
CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)
Spacer(Modifier.size(12.dp))
Text(stringResource(R.string.online_searching), style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
}
val enabled = nickOk && otherOk && !search.searching
// After a search the main button of the screen is "Download".
if (found != null && !launched) {
OutlinedButton(onClick = ::find, enabled = enabled) { Text(stringResource(R.string.online_find)) }
} else {
Button(onClick = ::find, enabled = enabled) { Text(stringResource(R.string.online_find)) }
}
}
if (found != null && !launched) {
Spacer(Modifier.height(16.dp))
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
Spacer(Modifier.height(8.dp))
for (site in listOf(Site.LICHESS, Site.CHESS_COM)) {
val r = found[site] ?: continue
FoundRow(site, r, site in search.chosen, onToggle = { on -> search.chosen = if (on) search.chosen + site else search.chosen - site }, onRetry = ::find)
}
if (found.values.count { it is AccountLookup.Found } > 1 && search.chosen.size > 1) {
Row(
Modifier
.fillMaxWidth()
.heightIn(min = 64.dp)
.toggleable(value = together, role = Role.Switch, onValueChange = { together = it }),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.online_merge), style = MaterialTheme.typography.bodyLarge)
Text(stringResource(R.string.online_merge_hint), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Switch(checked = together, onCheckedChange = null)
}
}
for ((path, games) in targets) {
val name = nameOf(path)
Text(
if (games != null) {
stringResource(R.string.online_into_existing, name, gamesText(games))
} else {
stringResource(R.string.online_into_new, name)
},
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(vertical = 4.dp),
)
}
if (accounts.isNotEmpty()) {
Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.End) {
Button(onClick = {
val groups = onlineTargets(downloads.dir.path, accounts, merge)
started = groups.map { downloads.start(it.accounts, it.path).id }
launched = true
}) { Text(stringResource(R.string.online_download)) }
}
}
}
// The downloads started here: how they go, then how they went.
for (id in started) {
val v = views[id] ?: continue
Spacer(Modifier.height(16.dp))
DownloadCard(
name = entries.firstOrNull { it.id == id }?.name ?: v.accounts.joinToString(" + ") { it.username },
view = v,
onStop = { downloads.cancel(id) },
onOpen = if (!v.state.running && (v.state.total ?: 0UL) > 0UL && entries.any { it.id == id }) ({ onOpen(id) }) else null,
)
}
}
}
}
@Composable
private fun NickField(value: String, label: String, bad: Boolean, onChange: (String) -> Unit, onDone: () -> Unit) {
OutlinedTextField(
value = value,
onValueChange = onChange,
label = { Text(label) },
placeholder = { Text(stringResource(R.string.online_nick_hint)) },
singleLine = true,
isError = bad,
supportingText = if (bad) ({ Text(stringResource(R.string.online_nick_rule)) }) else null,
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.None,
autoCorrectEnabled = false,
keyboardType = KeyboardType.Ascii,
imeAction = ImeAction.Search,
),
keyboardActions = KeyboardActions(onSearch = { onDone() }),
modifier = Modifier.fillMaxWidth(),
)
}
/// What one site gave for the nickname: the account to tick, "no such player", or why it
/// did not answer.
@Composable
private fun FoundRow(site: Site, r: AccountLookup, checked: Boolean, onToggle: (Boolean) -> Unit, onRetry: () -> Unit) {
when (r) {
is AccountLookup.Found -> {
val a = r.account
val lichess = a.games?.toLong()
val detail = when {
lichess != null -> {
val upTo = pluralStringResource(R.plurals.games_up_to, lichess.coerceAtMost(Int.MAX_VALUE.toLong()).toInt(), groupDigits(lichess.toInt()))
val secs = lichessSeconds(lichess)
if (secs < 60) {
stringResource(R.string.online_lichess_quick, upTo)
} else {
stringResource(R.string.online_lichess_found, upTo, ceil(secs / 60.0).toInt())
}
}
a.months != null -> stringResource(R.string.online_chesscom_found, a.months!!.toInt())
else -> ""
}
Row(
Modifier
.fillMaxWidth()
.heightIn(min = 64.dp)
.toggleable(value = checked, role = Role.Checkbox, onValueChange = onToggle),
verticalAlignment = Alignment.CenterVertically,
) {
Checkbox(checked = checked, onCheckedChange = null)
Column(Modifier.weight(1f).padding(start = 12.dp)) {
Text("${siteName(site)} · ${a.username}", style = MaterialTheme.typography.bodyLarge)
if (detail.isNotEmpty()) {
Text(detail, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
}
AccountLookup.NotFound -> Text(
stringResource(R.string.online_not_found, siteName(site)),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.heightIn(min = 48.dp).padding(start = 36.dp, top = 12.dp),
)
is AccountLookup.Failed -> Column(Modifier.padding(start = 36.dp, top = 8.dp)) {
Text(onlineProblemText(r.failure), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error)
TextButton(onClick = onRetry, contentPadding = PaddingValues(0.dp)) { Text(stringResource(R.string.online_try_again)) }
}
}
}
/// A download started on this screen: its progress and Stop, then its result and Open.
@Composable
private fun DownloadCard(name: String, view: DownloadView, onStop: () -> Unit, onOpen: (() -> Unit)?) {
val s = view.state
Column(Modifier.fillMaxWidth()) {
Text(name, style = MaterialTheme.typography.titleMedium, modifier = Modifier.semantics { heading() })
Spacer(Modifier.height(4.dp))
if (s.running) {
// Not a live region: it changes a few times a second (TalkBack would not stop).
Text(downloadProgressText(view), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
Spacer(Modifier.height(8.dp))
val share = downloadShare(view)
if (share != null) {
LinearProgressIndicator(progress = { share }, modifier = Modifier.fillMaxWidth())
} else {
LinearProgressIndicator(Modifier.fillMaxWidth())
}
Spacer(Modifier.height(8.dp))
Text(stringResource(R.string.online_leave), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
OutlinedButton(onClick = onStop, modifier = Modifier.padding(top = 8.dp)) { Text(stringResource(R.string.online_stop)) }
}
} else {
Text(
downloadResultText(view),
style = MaterialTheme.typography.bodyMedium,
color = if (s.failure != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite },
)
if (onOpen != null) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
Button(onClick = onOpen, modifier = Modifier.padding(top = 8.dp)) { Text(stringResource(R.string.online_open)) }
}
}
}
}
}

View file

@ -3,7 +3,7 @@
<string name="sample_alekhine">Aljechin</string> <string name="sample_alekhine">Aljechin</string>
<string name="empty_title">Hier erscheinen Ihre Datenbanken</string> <string name="empty_title">Hier erscheinen Ihre Datenbanken</string>
<string name="empty_text">Fügen Sie eine Datei oder einen Ordner mit Datenbanken hinzu: PGN, ChessBase, .zip- und .7z-Archive — vom Telefon oder aus der Cloud.</string> <string name="empty_text">Fügen Sie eine PGN-Datei, eine ChessBase-Datenbank oder ein .zip/.7z-Archiv hinzu – vom Telefon oder aus der Cloud – oder laden Sie Partien von Lichess und Chess.com.</string>
<string name="add_database">Datenbank hinzufügen</string> <string name="add_database">Datenbank hinzufügen</string>
<string name="open_samples">Beispielpartien öffnen</string> <string name="open_samples">Beispielpartien öffnen</string>
<string name="not_opened">noch nicht geöffnet · %1$s</string> <string name="not_opened">noch nicht geöffnet · %1$s</string>
@ -271,4 +271,61 @@
<item quantity="one">%1$d Stellung, etwa %2$s</item> <item quantity="one">%1$d Stellung, etwa %2$s</item>
<item quantity="other">%1$d Stellungen, etwa %2$s</item> <item quantity="other">%1$d Stellungen, etwa %2$s</item>
</plurals> </plurals>
<!-- Games from Lichess and Chess.com (android-ui.md §23) -->
<string name="online_title">Partien von Lichess und Chess.com</string>
<string name="add_online_hint">Partien beliebiger Spieler per Nickname: eigene, eines Schülers, eines Gegners</string>
<string name="online_intro">Die Partien des Spielers werden zu einer Datenbank auf dem Telefon – zum Suchen, Ansehen und Analysieren. Nur der Nickname ist nötig, keine Anmeldung.</string>
<string name="online_nick">Nickname des Spielers</string>
<string name="online_nick_hint">wie auf der Seite</string>
<string name="online_other">Anderer Nickname auf Chess.com</string>
<string name="online_other_nick">Nickname auf Chess.com</string>
<string name="online_same_nick">Derselbe Nickname</string>
<string name="online_nick_rule">Lateinische Buchstaben, Ziffern, _ und -, 2 bis 30 Zeichen</string>
<string name="online_find">Suchen</string>
<string name="online_searching">Suche auf den Seiten…</string>
<string name="online_lichess_found">%1$s · beim ersten Mal etwa %2$d Min.</string>
<string name="online_chesscom_found">Monate mit Partien: %1$d</string>
<string name="online_not_found">%1$s: kein Spieler mit diesem Nickname – Schreibweise prüfen</string>
<string name="online_merge">Beide Seiten in einer Datenbank zusammenführen</string>
<string name="online_merge_hint">Sonst bekommt jede Seite eine eigene Datenbank</string>
<string name="online_into_new">In die neue Datenbank „%1$s“</string>
<string name="online_into_existing">In „%1$s“ (schon %2$s dort; nur neue Partien kommen dazu)</string>
<string name="online_download">Herunterladen</string>
<string name="online_progress_lichess">Lichess: %1$s von etwa %2$s · noch etwa %3$d Min.</string>
<string name="online_progress_count">%1$s: %2$s</string>
<string name="online_progress_chesscom">Chess.com: Monat %1$d von %2$d · %3$s</string>
<string name="online_stop">Anhalten</string>
<string name="online_added">+%1$s, insgesamt %2$s</string>
<string name="online_no_new">Keine neuen Partien, %1$s in der Datenbank</string>
<string name="online_stopped">Angehalten, %1$s in der Datenbank</string>
<string name="online_no_games">Dort gibt es keine Partien im Standardschach.</string>
<string name="online_open">Datenbank öffnen</string>
<string name="online_try_again">Erneut versuchen</string>
<string name="online_err_network">%1$s antwortet nicht. Prüfen Sie die Internetverbindung und versuchen Sie es erneut.</string>
<string name="online_err_rate">%1$s bittet um eine Pause: zu viele Anfragen hintereinander. Warten Sie eine Minute und versuchen Sie es erneut; Geladenes bleibt erhalten.</string>
<string name="online_err_unexpected">%1$s hat unverständlich geantwortet: die Seite hat sich vielleicht geändert. Versuchen Sie es später oder aktualisieren Sie ChessPenguin.</string>
<string name="online_err_disk">Die Datenbank konnte nicht geschrieben werden: auf dem Telefon ist kein Platz mehr.</string>
<string name="online_err_busy">Diese Datenbank wird bereits geladen.</string>
<string name="online_short_network">%1$s antwortet nicht</string>
<string name="online_short_rate">%1$s bittet um eine Pause</string>
<string name="online_short_failed">Der Download wurde unterbrochen</string>
<string name="online_update">Neue Partien laden</string>
<string name="online_stop_download">Download anhalten</string>
<string name="online_downloading">Wird geladen · %1$s</string>
<string name="online_updated">aktualisiert %1$s</string>
<string name="online_unfinished">unvollständig</string>
<string name="online_removed">Geladene Datenbank gelöscht</string>
<string name="online_nick_lichess">Nickname auf Lichess</string>
<string name="online_lichess_quick">%1$s · beim ersten Mal unter einer Minute</string>
<string name="online_leave">Sie können diesen Bildschirm verlassen: die Datenbank ist in der Liste, der Download läuft weiter.</string>
<string name="online_done">Fertig: %1$s</string>
<string name="online_updated_now">gerade aktualisiert</string>
<string name="online_snack_added">„%1$s“: +%2$s, insgesamt %3$s</string>
<string name="online_snack_none">„%1$s“: keine neuen Partien</string>
<string name="online_snack_failed">„%1$s“: %2$s</string>
<string name="online_open_short">Öffnen</string>
<plurals name="games_up_to">
<item quantity="one">bis zu %1$s Partie</item>
<item quantity="other">bis zu %1$s Partien</item>
</plurals>
</resources> </resources>

View file

@ -3,7 +3,7 @@
<string name="sample_alekhine">Alekhine</string> <string name="sample_alekhine">Alekhine</string>
<string name="empty_title">Aquí aparecerán tus bases</string> <string name="empty_title">Aquí aparecerán tus bases</string>
<string name="empty_text">Añade un archivo o una carpeta de bases: PGN, ChessBase, archivos .zip y .7z — desde el teléfono o la nube.</string> <string name="empty_text">Añade un archivo PGN, una base ChessBase o un archivo .zip/.7z — desde el teléfono o la nube — o descarga partidas de Lichess y Chess.com.</string>
<string name="add_database">Añadir base</string> <string name="add_database">Añadir base</string>
<string name="open_samples">Abrir partidas de ejemplo</string> <string name="open_samples">Abrir partidas de ejemplo</string>
<string name="not_opened">aún sin abrir · %1$s</string> <string name="not_opened">aún sin abrir · %1$s</string>
@ -276,4 +276,62 @@
<item quantity="many">%1$d posiciones, unos %2$s</item> <item quantity="many">%1$d posiciones, unos %2$s</item>
<item quantity="other">%1$d posiciones, unos %2$s</item> <item quantity="other">%1$d posiciones, unos %2$s</item>
</plurals> </plurals>
<!-- Games from Lichess and Chess.com (android-ui.md §23) -->
<string name="online_title">Partidas de Lichess y Chess.com</string>
<string name="add_online_hint">Partidas de cualquier jugador por apodo: las tuyas, de un alumno, de un rival</string>
<string name="online_intro">Las partidas del jugador se convierten en una base en el teléfono, para buscar, ver y analizar. Solo hace falta el apodo, sin iniciar sesión.</string>
<string name="online_nick">Apodo del jugador</string>
<string name="online_nick_hint">como en el sitio</string>
<string name="online_other">Otro apodo en Chess.com</string>
<string name="online_other_nick">Apodo en Chess.com</string>
<string name="online_same_nick">El mismo apodo</string>
<string name="online_nick_rule">Letras latinas, dígitos, _ y -, de 2 a 30 caracteres</string>
<string name="online_find">Buscar</string>
<string name="online_searching">Buscando en los sitios…</string>
<string name="online_lichess_found">%1$s · la primera vez unos %2$d min</string>
<string name="online_chesscom_found">meses con partidas: %1$d</string>
<string name="online_not_found">%1$s: no hay ningún jugador con este apodo; revisa cómo se escribe</string>
<string name="online_merge">Unir ambos sitios en una sola base</string>
<string name="online_merge_hint">Si no, cada sitio tendrá su propia base</string>
<string name="online_into_new">En la nueva base «%1$s»</string>
<string name="online_into_existing">En «%1$s» (ya hay %2$s; solo se añaden las nuevas)</string>
<string name="online_download">Descargar</string>
<string name="online_progress_lichess">Lichess: %1$s de unas %2$s · quedan unos %3$d min</string>
<string name="online_progress_count">%1$s: %2$s</string>
<string name="online_progress_chesscom">Chess.com: mes %1$d de %2$d · %3$s</string>
<string name="online_stop">Detener</string>
<string name="online_added">+%1$s, %2$s en total</string>
<string name="online_no_new">No hay partidas nuevas, %1$s en la base</string>
<string name="online_stopped">Detenido, %1$s en la base</string>
<string name="online_no_games">Allí no hay partidas de ajedrez estándar.</string>
<string name="online_open">Abrir la base</string>
<string name="online_try_again">Reintentar</string>
<string name="online_err_network">%1$s no responde. Comprueba la conexión a internet e inténtalo de nuevo.</string>
<string name="online_err_rate">%1$s pide una pausa: demasiadas solicitudes seguidas. Espera un minuto e inténtalo de nuevo; lo descargado se conserva.</string>
<string name="online_err_unexpected">%1$s respondió de una forma que ChessPenguin no entiende: quizá el sitio cambió. Inténtalo más tarde o actualiza ChessPenguin.</string>
<string name="online_err_disk">No se pudo escribir la base: el teléfono no tiene espacio.</string>
<string name="online_err_busy">Esta base ya se está descargando.</string>
<string name="online_short_network">%1$s no responde</string>
<string name="online_short_rate">%1$s pide una pausa</string>
<string name="online_short_failed">La descarga se interrumpió</string>
<string name="online_update">Descargar partidas nuevas</string>
<string name="online_stop_download">Detener la descarga</string>
<string name="online_downloading">Descargando · %1$s</string>
<string name="online_updated">actualizada %1$s</string>
<string name="online_unfinished">incompleta</string>
<string name="online_removed">Base descargada eliminada</string>
<string name="online_nick_lichess">Apodo en Lichess</string>
<string name="online_lichess_quick">%1$s · la primera vez menos de un minuto</string>
<string name="online_leave">Puedes salir de esta pantalla: la base ya está en la lista y la descarga continúa.</string>
<string name="online_done">Listo: %1$s</string>
<string name="online_updated_now">actualizada ahora mismo</string>
<string name="online_snack_added">«%1$s»: +%2$s, %3$s en total</string>
<string name="online_snack_none">«%1$s»: no hay partidas nuevas</string>
<string name="online_snack_failed">«%1$s»: %2$s</string>
<string name="online_open_short">Abrir</string>
<plurals name="games_up_to">
<item quantity="one">hasta %1$s partida</item>
<item quantity="many">hasta %1$s partidas</item>
<item quantity="other">hasta %1$s partidas</item>
</plurals>
</resources> </resources>

View file

@ -3,7 +3,7 @@
<string name="sample_alekhine">Alekhine</string> <string name="sample_alekhine">Alekhine</string>
<string name="empty_title">Vos bases apparaîtront ici</string> <string name="empty_title">Vos bases apparaîtront ici</string>
<string name="empty_text">Ajoutez un fichier ou un dossier de bases : PGN, ChessBase, archives .zip et .7z — depuis votre téléphone ou le cloud.</string> <string name="empty_text">Ajoutez un fichier PGN, une base ChessBase ou une archive .zip/.7z — depuis le téléphone ou le cloud — ou téléchargez des parties de Lichess et Chess.com.</string>
<string name="add_database">Ajouter une base</string> <string name="add_database">Ajouter une base</string>
<string name="open_samples">Ouvrir les parties d’exemple</string> <string name="open_samples">Ouvrir les parties d’exemple</string>
<string name="not_opened">pas encore ouverte · %1$s</string> <string name="not_opened">pas encore ouverte · %1$s</string>
@ -276,4 +276,62 @@
<item quantity="many">%1$d positions, environ %2$s</item> <item quantity="many">%1$d positions, environ %2$s</item>
<item quantity="other">%1$d positions, environ %2$s</item> <item quantity="other">%1$d positions, environ %2$s</item>
</plurals> </plurals>
<!-- Games from Lichess and Chess.com (android-ui.md §23) -->
<string name="online_title">Parties de Lichess et Chess.com</string>
<string name="add_online_hint">Les parties de n\'importe quel joueur par pseudo : les vôtres, d\'un élève, d\'un adversaire</string>
<string name="online_intro">Les parties du joueur deviennent une base sur le téléphone, à chercher, voir et analyser. Seul le pseudo est nécessaire, sans connexion.</string>
<string name="online_nick">Pseudo du joueur</string>
<string name="online_nick_hint">comme sur le site</string>
<string name="online_other">Un autre pseudo sur Chess.com</string>
<string name="online_other_nick">Pseudo sur Chess.com</string>
<string name="online_same_nick">Le même pseudo</string>
<string name="online_nick_rule">Lettres latines, chiffres, _ et -, de 2 à 30 caractères</string>
<string name="online_find">Rechercher</string>
<string name="online_searching">Recherche sur les sites…</string>
<string name="online_lichess_found">%1$s · environ %2$d min la première fois</string>
<string name="online_chesscom_found">mois avec des parties : %1$d</string>
<string name="online_not_found">%1$s : aucun joueur avec ce pseudo — vérifiez l\'orthographe</string>
<string name="online_merge">Réunir les deux sites dans une seule base</string>
<string name="online_merge_hint">Sinon chaque site a sa propre base</string>
<string name="online_into_new">Dans la nouvelle base « %1$s »</string>
<string name="online_into_existing">Dans « %1$s » (déjà %2$s ; seules les nouvelles parties sont ajoutées)</string>
<string name="online_download">Télécharger</string>
<string name="online_progress_lichess">Lichess : %1$s sur environ %2$s · encore environ %3$d min</string>
<string name="online_progress_count">%1$s : %2$s</string>
<string name="online_progress_chesscom">Chess.com : mois %1$d sur %2$d · %3$s</string>
<string name="online_stop">Arrêter</string>
<string name="online_added">+%1$s, %2$s en tout</string>
<string name="online_no_new">Pas de nouvelles parties, %1$s dans la base</string>
<string name="online_stopped">Arrêté, %1$s dans la base</string>
<string name="online_no_games">Aucune partie d\'échecs standard là-bas.</string>
<string name="online_open">Ouvrir la base</string>
<string name="online_try_again">Réessayer</string>
<string name="online_err_network">%1$s ne répond pas. Vérifiez la connexion Internet et réessayez.</string>
<string name="online_err_rate">%1$s demande une pause : trop de requêtes d\'affilée. Attendez une minute et réessayez ; ce qui est téléchargé est conservé.</string>
<string name="online_err_unexpected">%1$s a répondu d\'une façon que ChessPenguin ne comprend pas : le site a peut-être changé. Réessayez plus tard ou mettez ChessPenguin à jour.</string>
<string name="online_err_disk">Impossible d\'écrire la base : le téléphone n\'a plus de place.</string>
<string name="online_err_busy">Cette base est déjà en cours de téléchargement.</string>
<string name="online_short_network">%1$s ne répond pas</string>
<string name="online_short_rate">%1$s demande une pause</string>
<string name="online_short_failed">Le téléchargement s\'est interrompu</string>
<string name="online_update">Télécharger les nouvelles parties</string>
<string name="online_stop_download">Arrêter le téléchargement</string>
<string name="online_downloading">Téléchargement · %1$s</string>
<string name="online_updated">mise à jour %1$s</string>
<string name="online_unfinished">incomplète</string>
<string name="online_removed">Base téléchargée supprimée</string>
<string name="online_nick_lichess">Pseudo sur Lichess</string>
<string name="online_lichess_quick">%1$s · moins d\'une minute la première fois</string>
<string name="online_leave">Vous pouvez quitter cet écran : la base est dans la liste et le téléchargement continue.</string>
<string name="online_done">Terminé : %1$s</string>
<string name="online_updated_now">mise à jour à l\'instant</string>
<string name="online_snack_added">« %1$s » : +%2$s, %3$s en tout</string>
<string name="online_snack_none">« %1$s » : pas de nouvelles parties</string>
<string name="online_snack_failed">« %1$s » : %2$s</string>
<string name="online_open_short">Ouvrir</string>
<plurals name="games_up_to">
<item quantity="one">jusqu\'à %1$s partie</item>
<item quantity="many">jusqu\'à %1$s parties</item>
<item quantity="other">jusqu\'à %1$s parties</item>
</plurals>
</resources> </resources>

View file

@ -3,7 +3,7 @@
<string name="sample_alekhine">Alekhine</string> <string name="sample_alekhine">Alekhine</string>
<string name="empty_title">Qui compariranno i tuoi database</string> <string name="empty_title">Qui compariranno i tuoi database</string>
<string name="empty_text">Aggiungi un file o una cartella di database: PGN, ChessBase, archivi .zip e .7z — dal telefono o dal cloud.</string> <string name="empty_text">Aggiungi un file PGN, un database ChessBase o un archivio .zip/.7z — dal telefono o dal cloud — oppure scarica partite da Lichess e Chess.com.</string>
<string name="add_database">Aggiungi database</string> <string name="add_database">Aggiungi database</string>
<string name="open_samples">Apri le partite di esempio</string> <string name="open_samples">Apri le partite di esempio</string>
<string name="not_opened">non ancora aperto · %1$s</string> <string name="not_opened">non ancora aperto · %1$s</string>
@ -276,4 +276,62 @@
<item quantity="many">%1$d posizioni, circa %2$s</item> <item quantity="many">%1$d posizioni, circa %2$s</item>
<item quantity="other">%1$d posizioni, circa %2$s</item> <item quantity="other">%1$d posizioni, circa %2$s</item>
</plurals> </plurals>
<!-- Games from Lichess and Chess.com (android-ui.md §23) -->
<string name="online_title">Partite da Lichess e Chess.com</string>
<string name="add_online_hint">Partite di qualsiasi giocatore per nickname: le tue, di un allievo, di un avversario</string>
<string name="online_intro">Le partite del giocatore diventano una base sul telefono, da cercare, vedere e analizzare. Serve solo il nickname, senza accesso.</string>
<string name="online_nick">Nickname del giocatore</string>
<string name="online_nick_hint">come sul sito</string>
<string name="online_other">Un altro nickname su Chess.com</string>
<string name="online_other_nick">Nickname su Chess.com</string>
<string name="online_same_nick">Lo stesso nickname</string>
<string name="online_nick_rule">Lettere latine, cifre, _ e -, da 2 a 30 caratteri</string>
<string name="online_find">Cerca</string>
<string name="online_searching">Cerco sui siti…</string>
<string name="online_lichess_found">%1$s · la prima volta circa %2$d min</string>
<string name="online_chesscom_found">mesi con partite: %1$d</string>
<string name="online_not_found">%1$s: nessun giocatore con questo nickname — controlla come è scritto</string>
<string name="online_merge">Unire entrambi i siti in una sola base</string>
<string name="online_merge_hint">Altrimenti ogni sito avrà la sua base</string>
<string name="online_into_new">Nella nuova base «%1$s»</string>
<string name="online_into_existing">In «%1$s» (già %2$s; si aggiungono solo le nuove)</string>
<string name="online_download">Scarica</string>
<string name="online_progress_lichess">Lichess: %1$s di circa %2$s · mancano circa %3$d min</string>
<string name="online_progress_count">%1$s: %2$s</string>
<string name="online_progress_chesscom">Chess.com: mese %1$d di %2$d · %3$s</string>
<string name="online_stop">Ferma</string>
<string name="online_added">+%1$s, %2$s in tutto</string>
<string name="online_no_new">Nessuna partita nuova, %1$s nella base</string>
<string name="online_stopped">Fermato, %1$s nella base</string>
<string name="online_no_games">Lì non ci sono partite di scacchi standard.</string>
<string name="online_open">Apri la base</string>
<string name="online_try_again">Riprova</string>
<string name="online_err_network">%1$s non risponde. Controlla la connessione a internet e riprova.</string>
<string name="online_err_rate">%1$s chiede una pausa: troppe richieste di fila. Aspetta un minuto e riprova; il già scaricato resta.</string>
<string name="online_err_unexpected">%1$s ha risposto in un modo che ChessPenguin non capisce: forse il sito è cambiato. Riprova più tardi o aggiorna ChessPenguin.</string>
<string name="online_err_disk">Impossibile scrivere la base: il telefono non ha spazio.</string>
<string name="online_err_busy">Questa base è già in download.</string>
<string name="online_short_network">%1$s non risponde</string>
<string name="online_short_rate">%1$s chiede una pausa</string>
<string name="online_short_failed">Il download si è interrotto</string>
<string name="online_update">Scarica le partite nuove</string>
<string name="online_stop_download">Ferma il download</string>
<string name="online_downloading">Download in corso · %1$s</string>
<string name="online_updated">aggiornata %1$s</string>
<string name="online_unfinished">incompleta</string>
<string name="online_removed">Base scaricata eliminata</string>
<string name="online_nick_lichess">Nickname su Lichess</string>
<string name="online_lichess_quick">%1$s · la prima volta meno di un minuto</string>
<string name="online_leave">Puoi uscire da questa schermata: la base è già nell\'elenco e il download continua.</string>
<string name="online_done">Fatto: %1$s</string>
<string name="online_updated_now">aggiornata adesso</string>
<string name="online_snack_added">«%1$s»: +%2$s, %3$s in tutto</string>
<string name="online_snack_none">«%1$s»: nessuna partita nuova</string>
<string name="online_snack_failed">«%1$s»: %2$s</string>
<string name="online_open_short">Apri</string>
<plurals name="games_up_to">
<item quantity="one">fino a %1$s partita</item>
<item quantity="many">fino a %1$s partite</item>
<item quantity="other">fino a %1$s partite</item>
</plurals>
</resources> </resources>

View file

@ -3,7 +3,7 @@
<string name="sample_alekhine">Алехин</string> <string name="sample_alekhine">Алехин</string>
<string name="empty_title">Здесь будут ваши базы</string> <string name="empty_title">Здесь будут ваши базы</string>
<string name="empty_text">Добавьте файл или папку с базами: PGN, ChessBase, архивы .zip и .7z — с телефона или из облака.</string> <string name="empty_text">Добавьте файл PGN, базу ChessBase или архив .zip/.7z — с телефона или из облака — или скачайте партии с Lichess и Chess.com.</string>
<string name="add_database">Добавить базу</string> <string name="add_database">Добавить базу</string>
<string name="open_samples">Открыть примеры партий</string> <string name="open_samples">Открыть примеры партий</string>
<string name="not_opened">ещё не открывалась · %1$s</string> <string name="not_opened">ещё не открывалась · %1$s</string>
@ -281,4 +281,63 @@
<item quantity="many">Позиций: %1$d, примерно %2$s</item> <item quantity="many">Позиций: %1$d, примерно %2$s</item>
<item quantity="other">Позиций: %1$d, примерно %2$s</item> <item quantity="other">Позиций: %1$d, примерно %2$s</item>
</plurals> </plurals>
<!-- Games from Lichess and Chess.com (android-ui.md §23) -->
<string name="online_title">Партии с Lichess и Chess.com</string>
<string name="add_online_hint">Партии любого игрока по нику: свои, ученика, соперника</string>
<string name="online_intro">Партии игрока станут базой на телефоне — искать, смотреть, анализировать. Нужен только ник, входить на сайт не нужно.</string>
<string name="online_nick">Ник игрока</string>
<string name="online_nick_hint">как на сайте</string>
<string name="online_other">На Chess.com другой ник</string>
<string name="online_other_nick">Ник на Chess.com</string>
<string name="online_same_nick">Тот же ник</string>
<string name="online_nick_rule">Латиница, цифры, _ и -, от 2 до 30 символов</string>
<string name="online_find">Найти</string>
<string name="online_searching">Ищу на сайтах…</string>
<string name="online_lichess_found">%1$s · первый раз около %2$d мин</string>
<string name="online_chesscom_found">месяцев с партиями: %1$d</string>
<string name="online_not_found">%1$s: игрока с таким ником нет — проверьте написание</string>
<string name="online_merge">Объединить оба сайта в одну базу</string>
<string name="online_merge_hint">Иначе у каждого сайта будет своя база</string>
<string name="online_into_new">В новую базу «%1$s»</string>
<string name="online_into_existing">В базу «%1$s» (там уже %2$s; добавятся только новые)</string>
<string name="online_download">Скачать</string>
<string name="online_progress_lichess">Lichess: %1$s из примерно %2$s · осталось около %3$d мин</string>
<string name="online_progress_count">%1$s: %2$s</string>
<string name="online_progress_chesscom">Chess.com: месяц %1$d из %2$d · %3$s</string>
<string name="online_stop">Остановить</string>
<string name="online_added">+%1$s, всего %2$s</string>
<string name="online_no_new">Новых партий нет, в базе %1$s</string>
<string name="online_stopped">Остановлено, в базе %1$s</string>
<string name="online_no_games">Партий в обычные шахматы там нет.</string>
<string name="online_open">Открыть базу</string>
<string name="online_try_again">Попробовать ещё раз</string>
<string name="online_err_network">%1$s не отвечает. Проверьте подключение к интернету и попробуйте ещё раз.</string>
<string name="online_err_rate">%1$s просит сделать паузу: слишком много запросов подряд. Подождите минуту и попробуйте снова — скачанное сохранится.</string>
<string name="online_err_unexpected">%1$s ответил непонятно — возможно, сайт что-то поменял. Попробуйте позже или обновите ChessPenguin.</string>
<string name="online_err_disk">Не удалось записать базу: на телефоне не хватает места.</string>
<string name="online_err_busy">Эта база уже скачивается.</string>
<string name="online_short_network">%1$s не отвечает</string>
<string name="online_short_rate">%1$s просит паузу</string>
<string name="online_short_failed">Скачивание прервалось</string>
<string name="online_update">Скачать новые партии</string>
<string name="online_stop_download">Остановить скачивание</string>
<string name="online_downloading">Скачивается · %1$s</string>
<string name="online_updated">обновлено %1$s</string>
<string name="online_unfinished">не докачана</string>
<string name="online_removed">Скачанная база удалена</string>
<string name="online_nick_lichess">Ник на Lichess</string>
<string name="online_lichess_quick">%1$s · первый раз меньше минуты</string>
<string name="online_leave">Можно уйти с этого экрана: база уже в списке, скачивание продолжится.</string>
<string name="online_done">Готово: %1$s</string>
<string name="online_updated_now">обновлено только что</string>
<string name="online_snack_added">«%1$s»: +%2$s, всего %3$s</string>
<string name="online_snack_none">«%1$s»: новых партий нет</string>
<string name="online_snack_failed">«%1$s»: %2$s</string>
<string name="online_open_short">Открыть</string>
<plurals name="games_up_to">
<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>
</resources> </resources>

View file

@ -4,7 +4,7 @@
<string name="sample_alekhine">Alekhine</string> <string name="sample_alekhine">Alekhine</string>
<string name="empty_title">Your databases will appear here</string> <string name="empty_title">Your databases will appear here</string>
<string name="empty_text">Add a file or a folder of databases: PGN, ChessBase, .zip and .7z archives — from your phone or the cloud.</string> <string name="empty_text">Add a PGN file, a ChessBase database or a .zip/.7z archive — from your phone or the cloud — or download games from Lichess and Chess.com.</string>
<string name="add_database">Add database</string> <string name="add_database">Add database</string>
<string name="open_samples">Open sample games</string> <string name="open_samples">Open sample games</string>
<string name="not_opened">not opened yet · %1$s</string> <string name="not_opened">not opened yet · %1$s</string>
@ -274,4 +274,61 @@
<item quantity="one">%1$d position, about %2$s</item> <item quantity="one">%1$d position, about %2$s</item>
<item quantity="other">%1$d positions, about %2$s</item> <item quantity="other">%1$d positions, about %2$s</item>
</plurals> </plurals>
<!-- Games from Lichess and Chess.com (android-ui.md §23) -->
<string name="online_title">Games from Lichess and Chess.com</string>
<string name="add_online_hint">Any player\'s games by nickname: yours, a pupil\'s, an opponent\'s</string>
<string name="online_intro">The player\'s games become a database on your phone, to search, view and analyse. Only the nickname is needed, no login.</string>
<string name="online_nick">Player\'s nickname</string>
<string name="online_nick_hint">as on the site</string>
<string name="online_other">A different nickname on Chess.com</string>
<string name="online_other_nick">Nickname on Chess.com</string>
<string name="online_same_nick">The same nickname</string>
<string name="online_nick_rule">Latin letters, digits, _ and -, 2 to 30 characters</string>
<string name="online_find">Find</string>
<string name="online_searching">Looking on the sites…</string>
<string name="online_lichess_found">%1$s · about %2$d min the first time</string>
<string name="online_chesscom_found">months with games: %1$d</string>
<string name="online_not_found">%1$s: no player with this nickname — check the spelling</string>
<string name="online_merge">Merge both sites into one database</string>
<string name="online_merge_hint">Otherwise each site gets a database of its own</string>
<string name="online_into_new">Into the new database “%1$s”</string>
<string name="online_into_existing">Into “%1$s” (%2$s there already; only new games are added)</string>
<string name="online_download">Download</string>
<string name="online_progress_lichess">Lichess: %1$s of about %2$s · about %3$d min left</string>
<string name="online_progress_count">%1$s: %2$s</string>
<string name="online_progress_chesscom">Chess.com: month %1$d of %2$d · %3$s</string>
<string name="online_stop">Stop</string>
<string name="online_added">+%1$s, %2$s in all</string>
<string name="online_no_new">No new games, %1$s in the database</string>
<string name="online_stopped">Stopped, %1$s in the database</string>
<string name="online_no_games">No games of standard chess there.</string>
<string name="online_open">Open the database</string>
<string name="online_try_again">Try again</string>
<string name="online_err_network">%1$s does not answer. Check the internet connection and try again.</string>
<string name="online_err_rate">%1$s asks for a pause: too many requests in a row. Wait a minute and try again; what is downloaded is kept.</string>
<string name="online_err_unexpected">%1$s answered in a way ChessPenguin does not understand: the site may have changed. Try later or update ChessPenguin.</string>
<string name="online_err_disk">Could not write the database: the phone is out of space.</string>
<string name="online_err_busy">This database is being downloaded already.</string>
<string name="online_short_network">%1$s does not answer</string>
<string name="online_short_rate">%1$s asks for a pause</string>
<string name="online_short_failed">The download stopped</string>
<string name="online_update">Download new games</string>
<string name="online_stop_download">Stop the download</string>
<string name="online_downloading">Downloading · %1$s</string>
<string name="online_updated">updated %1$s</string>
<string name="online_unfinished">not finished</string>
<string name="online_removed">Downloaded database deleted</string>
<string name="online_nick_lichess">Nickname on Lichess</string>
<string name="online_lichess_quick">%1$s · under a minute the first time</string>
<string name="online_leave">You can leave this screen: the database is on the list and the download goes on.</string>
<string name="online_done">Done: %1$s</string>
<string name="online_updated_now">updated just now</string>
<string name="online_snack_added">“%1$s”: +%2$s, %3$s in all</string>
<string name="online_snack_none">“%1$s”: no new games</string>
<string name="online_snack_failed">“%1$s”: %2$s</string>
<string name="online_open_short">Open</string>
<plurals name="games_up_to">
<item quantity="one">up to %1$s game</item>
<item quantity="other">up to %1$s games</item>
</plurals>
</resources> </resources>

View file

@ -25,6 +25,7 @@ rodio.workspace = true
directories.workspace = true directories.workspace = true
serde.workspace = true serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
online-games.workspace = true
# Downloading the official Stockfish on request (decision 14). # Downloading the official Stockfish on request (decision 14).
ureq = "3.4" ureq = "3.4"
flate2 = "1.1" flate2 = "1.1"

File diff suppressed because it is too large Load diff

View file

@ -73,31 +73,9 @@ pub struct OnlineDialog {
focus: bool, focus: bool,
} }
/// Where the found accounts go: all into one database (`together`) or each into its /// Where the found accounts go (see [`online_games::targets`]).
/// own. A database already holding the accounts is kept (also when one site does not
/// answer this time: its partner's games still go where they went before).
fn targets(start: &[Account], together: bool) -> Vec<(Vec<Account>, PathBuf)> { fn targets(start: &[Account], together: bool) -> Vec<(Vec<Account>, PathBuf)> {
let groups: Vec<Vec<Account>> = if together { online::targets(start, together)
vec![start.to_vec()]
} else {
start.iter().map(|a| vec![a.clone()]).collect()
};
// Only one account found: any database holding it (the merged one first).
let any = start.len() == 1;
groups
.into_iter()
.filter_map(|g| {
let existing = online::holding(&g[0]).into_iter().find(|p| {
online::State::load(p).is_some_and(|s| {
let mine = s.accounts();
any || (mine.len() == g.len()
&& g.iter().all(|a| mine.iter().any(|m| m.same(a))))
})
});
let path = existing.or_else(|| online::combined_path(&g))?;
Some((g, path))
})
.collect()
} }
/// The file name of a database without the extension. /// The file name of a database without the extension.

View file

@ -25,6 +25,7 @@ bindgen = ["uniffi/cli"]
chess-core.workspace = true chess-core.workspace = true
chess-import.workspace = true chess-import.workspace = true
game-review.workspace = true game-review.workspace = true
online-games.workspace = true
shakmaty.workspace = true shakmaty.workspace = true
thiserror.workspace = true thiserror.workspace = true
uci.workspace = true uci.workspace = true

View file

@ -12,9 +12,14 @@ use chess_core::{Game, MoveKind, NodeId};
use shakmaty::Position; use shakmaty::Position;
mod engine; mod engine;
mod online;
mod review; mod review;
pub use engine::{Analysis, Analyzer, EngineFailure, EngineLine, LineStep}; pub use engine::{Analysis, Analyzer, EngineFailure, EngineLine, LineStep};
pub use online::{
AccountLookup, DownloadState, OnlineAccount, OnlineDatabase, OnlineDownload, OnlineFailure,
OnlineProblem, OnlineTarget, Site,
};
pub use review::{GameReview, MoveJudgement, ReviewMove, ReviewPoint, ReviewState, SideReview}; pub use review::{GameReview, MoveJudgement, ReviewMove, ReviewPoint, ReviewState, SideReview};
uniffi::setup_scaffolding!(); uniffi::setup_scaffolding!();
@ -319,6 +324,29 @@ impl Database {
.collect() .collect()
} }
/// These games (from [`Database::find`]) from the most recent to the oldest, by the
/// time they were played (`UTCDate` and `UTCTime` when there, else `Date`); games of
/// the same time keep the newer place in the file first. For downloaded databases,
/// where both sites' games are appended oldest first.
pub fn newest_first(&self, indices: Vec<u32>) -> Vec<u32> {
let Some(pgn) = self.db.as_pgn() else {
return indices;
};
let entries = pgn.entries();
let when = |i: u32| {
let Some(e) = entries.get(i as usize) else {
return String::new();
};
match (e.tag("UTCDate"), e.tag("UTCTime")) {
(Some(d), Some(t)) => format!("{d} {t}"),
_ => e.tag("Date").unwrap_or("").to_owned(),
}
};
let mut keyed: Vec<(String, u32)> = indices.into_iter().map(|i| (when(i), i)).collect();
keyed.sort_by(|a, b| b.cmp(a));
keyed.into_iter().map(|(_, i)| i).collect()
}
/// The rows of these games (from [`Database::find`]), in this order. /// The rows of these games (from [`Database::find`]), in this order.
pub fn rows_of(&self, indices: Vec<u32>) -> Vec<GameRow> { pub fn rows_of(&self, indices: Vec<u32>) -> Vec<GameRow> {
let Some(pgn) = self.db.as_pgn() else { let Some(pgn) = self.db.as_pgn() else {
@ -611,6 +639,19 @@ mod tests {
assert!(g.nodes.iter().any(|n| !n.main_line)); assert!(g.nodes.iter().any(|n| !n.main_line));
} }
#[test]
fn downloaded_games_come_newest_first() {
let pgn = b"[White \"a\"][UTCDate \"2020.01.02\"][UTCTime \"10:00:00\"]\n\n1. e4 *\n\n\
[White \"b\"][UTCDate \"2020.01.02\"][UTCTime \"09:00:00\"]\n\n1. e4 *\n\n\
[White \"c\"][Date \"2021.05.01\"]\n\n1. e4 *\n\n\
[White \"d\"][UTCDate \"2019.12.31\"][UTCTime \"23:59:59\"]\n\n1. e4 *\n"
.to_vec();
let db = open_bytes("t.pgn".into(), pgn).unwrap();
let order = db.newest_first(db.find(String::new()));
let names: Vec<String> = db.rows_of(order).into_iter().map(|r| r.white).collect();
assert_eq!(names, ["c", "a", "b", "d"]);
}
#[test] #[test]
fn bytes_open_like_files() { fn bytes_open_like_files() {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../examples/classics.pgn"); let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../examples/classics.pgn");

View file

@ -0,0 +1,362 @@
//! A player's games from Lichess and Chess.com for the Android app: the `online-games`
//! crate (the same downloads, state files and resuming as on the desktop) with its
//! download on a thread of its own. The app looks accounts up, starts a download into a
//! file of its own folder, asks for the progress while it runs, and can stop it; what
//! was fetched stays, and the next download continues without duplicates.
//!
//! Every call that talks to a site blocks: call it off the main thread.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use online_games::{Account, Done, Failure, Lookup, Platform, Progress, State};
/// A site.
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum Site {
Lichess,
ChessCom,
}
impl From<Site> for Platform {
fn from(s: Site) -> Self {
match s {
Site::Lichess => Platform::Lichess,
Site::ChessCom => Platform::ChessCom,
}
}
}
impl From<Platform> for Site {
fn from(p: Platform) -> Self {
match p {
Platform::Lichess => Site::Lichess,
Platform::ChessCom => Site::ChessCom,
}
}
}
/// An account on a site.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct OnlineAccount {
pub site: Site,
/// As the site spells it.
pub username: String,
/// Lichess: the games of the account (of all kinds, so at most this many).
pub games: Option<u64>,
/// Chess.com: the months with games.
pub months: Option<u32>,
}
impl From<&Account> for OnlineAccount {
fn from(a: &Account) -> Self {
OnlineAccount {
site: a.platform.into(),
username: a.username.clone(),
games: a.games,
months: a.months.map(|m| m as u32),
}
}
}
impl From<&OnlineAccount> for Account {
fn from(a: &OnlineAccount) -> Self {
Account {
platform: a.site.into(),
username: a.username.clone(),
games: a.games,
months: a.months.map(|m| m as usize),
}
}
}
/// What went wrong talking to a site.
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum OnlineProblem {
/// No answer (offline, a timeout).
Network,
/// The site asks for a pause: too many requests.
RateLimited,
/// An answer this version does not understand (the site changed).
Unexpected,
/// The database could not be written (the phone is full).
Disk,
/// The database is being downloaded already.
Busy,
}
/// A problem, the site it came from (when known), and the technical text.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct OnlineFailure {
pub problem: OnlineProblem,
pub site: Option<Site>,
pub detail: String,
}
fn failure(e: &Failure, site: Option<Site>) -> OnlineFailure {
let problem = match e {
Failure::Network(_) => OnlineProblem::Network,
Failure::RateLimited => OnlineProblem::RateLimited,
Failure::Unexpected(_) => OnlineProblem::Unexpected,
Failure::Disk(_) => OnlineProblem::Disk,
Failure::Busy => OnlineProblem::Busy,
};
OnlineFailure {
problem,
site,
detail: e.to_string(),
}
}
/// What looking a nickname up on a site gave.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]
pub enum AccountLookup {
Found { account: OnlineAccount },
NotFound,
Failed { failure: OnlineFailure },
}
/// A nickname both sites could have: 2–30 letters, digits, `_` or `-`.
#[uniffi::export]
pub fn valid_nickname(nick: String) -> bool {
online_games::valid_nick(nick.trim())
}
/// Looks the nickname up on the site (blocks: it asks the site).
#[uniffi::export]
pub fn find_account(site: Site, nick: String) -> AccountLookup {
match online_games::lookup(site.into(), &nick) {
Lookup::Found(a) => AccountLookup::Found {
account: (&a).into(),
},
Lookup::NotFound => AccountLookup::NotFound,
Lookup::Failed(e) => AccountLookup::Failed {
failure: failure(&e, Some(site)),
},
}
}
/// Accounts and the database file they are downloaded into.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct OnlineTarget {
pub accounts: Vec<OnlineAccount>,
pub path: String,
/// The file is there already (its new games are fetched).
pub exists: bool,
}
/// Where the found accounts go in `dir`: all into one database (`together`) or each into
/// its own; a database already holding them is kept.
#[uniffi::export]
pub fn online_targets(
dir: String,
accounts: Vec<OnlineAccount>,
together: bool,
) -> Vec<OnlineTarget> {
let accounts: Vec<Account> = accounts.iter().map(Into::into).collect();
online_games::targets(Path::new(&dir), &accounts, together)
.into_iter()
.map(|(group, path)| OnlineTarget {
accounts: group.iter().map(Into::into).collect(),
exists: path.exists(),
path: path.to_string_lossy().into_owned(),
})
.collect()
}
/// What a downloaded database holds.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct OnlineDatabase {
pub accounts: Vec<OnlineAccount>,
/// Games written into it.
pub games: u64,
/// When the last download finished (Unix seconds); none while it never finished.
pub updated: Option<i64>,
}
/// The state of the database at `path`, when it is a downloaded one.
#[uniffi::export]
pub fn online_database(path: String) -> Option<OnlineDatabase> {
let s = State::load(Path::new(&path))?;
Some(OnlineDatabase {
accounts: s.accounts().iter().map(Into::into).collect(),
games: s.games,
updated: s.updated,
})
}
/// Deletes a downloaded database and the files beside it (its state).
#[uniffi::export]
pub fn delete_online_database(path: String) {
let p = PathBuf::from(path);
for f in [
p.clone(),
p.with_extension("online.json"),
p.with_extension("online.lock"),
] {
let _ = std::fs::remove_file(f);
}
}
/// How a download stands.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct DownloadState {
pub running: bool,
/// The account being fetched (an index into the download's accounts).
pub account: u32,
/// Games of that account so far.
pub account_games: u64,
/// Games added by this download so far.
pub added: u64,
/// Chess.com: months done of all.
pub months_done: u32,
pub months_total: u32,
/// When it has ended: the games added and in the database now; stopped by the user.
pub total: Option<u64>,
pub cancelled: bool,
pub failure: Option<OnlineFailure>,
}
struct Shared {
progress: AtomicUsize,
status: Progress,
cancel: AtomicBool,
result: Mutex<Option<Result<Done, OnlineFailure>>>,
}
/// A download of accounts into one database.
#[derive(uniffi::Object)]
pub struct OnlineDownload {
shared: Arc<Shared>,
}
#[uniffi::export]
impl OnlineDownload {
/// Starts fetching the games of `accounts` new since the last time into the database
/// at `path` (created when it is not there). Returns at once.
#[uniffi::constructor]
pub fn start(accounts: Vec<OnlineAccount>, path: String) -> Arc<Self> {
let shared = Arc::new(Shared {
progress: AtomicUsize::new(0),
status: Progress::default(),
cancel: AtomicBool::new(false),
result: Mutex::new(None),
});
let work = shared.clone();
let accounts: Vec<Account> = accounts.iter().map(Into::into).collect();
let spawned = std::thread::Builder::new()
.name("online-download".into())
.spawn(move || {
let r = online_games::download(
&accounts,
Path::new(&path),
&work.progress,
&work.cancel,
&work.status,
);
// The account being fetched when it failed: the site to name.
let site = accounts
.get(work.status.account.load(Ordering::Relaxed))
.map(|a| a.platform.into());
*lock(&work.result) = Some(r.map_err(|e| failure(&e, site)));
});
if let Err(e) = spawned {
*lock(&shared.result) = Some(Err(OnlineFailure {
problem: OnlineProblem::Disk,
site: None,
detail: e.to_string(),
}));
}
Arc::new(OnlineDownload { shared })
}
/// Stops it soon; what was fetched is kept.
pub fn cancel(&self) {
self.shared.cancel.store(true, Ordering::Relaxed);
}
pub fn state(&self) -> DownloadState {
let s = &self.shared;
let result = lock(&s.result).clone();
let (total, cancelled, failure) = match &result {
Some(Ok(d)) => (Some(d.total), d.cancelled, None),
Some(Err(f)) => (None, false, Some(f.clone())),
None => (None, false, None),
};
DownloadState {
running: result.is_none(),
account: s.status.account.load(Ordering::Relaxed) as u32,
account_games: s.status.games.load(Ordering::Relaxed) as u64,
added: result
.as_ref()
.and_then(|r| r.as_ref().ok())
.map_or(s.progress.load(Ordering::Relaxed) as u64, |d| d.added),
months_done: s.status.months_done.load(Ordering::Relaxed) as u32,
months_total: s.status.months_total.load(Ordering::Relaxed) as u32,
total,
cancelled,
failure,
}
}
}
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nicknames_and_targets() {
assert!(valid_nickname(" Magnus_C-1 ".into()));
assert!(!valid_nickname("../etc".into()));
let dir = std::env::temp_dir().join(format!("mobile-online-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let li = OnlineAccount {
site: Site::Lichess,
username: "Magnus".into(),
games: Some(10),
months: None,
};
let cc = OnlineAccount {
site: Site::ChessCom,
username: "magnus".into(),
games: None,
months: Some(3),
};
let d = dir.to_string_lossy().into_owned();
let one = online_targets(d.clone(), vec![li.clone(), cc.clone()], true);
assert_eq!(one.len(), 1);
assert!(one[0].path.ends_with("Magnus (Lichess + Chess.com).pgn"));
assert!(!one[0].exists);
let two = online_targets(d, vec![li, cc], false);
assert_eq!(two.len(), 2);
assert!(online_database(two[0].path.clone()).is_none());
}
#[test]
fn a_download_that_cannot_write_says_so() {
// A folder that cannot be made: the download ends with a disk problem.
let acc = OnlineAccount {
site: Site::Lichess,
username: "someone".into(),
games: None,
months: None,
};
let d = OnlineDownload::start(vec![acc], "/proc/cp-no-such-dir/db.pgn".into());
let mut s = d.state();
for _ in 0..100 {
if !s.running {
break;
}
std::thread::sleep(std::time::Duration::from_millis(20));
s = d.state();
}
assert!(!s.running);
assert_eq!(s.failure.map(|f| f.problem), Some(OnlineProblem::Disk));
assert_eq!(s.total, None);
}
}

View file

@ -0,0 +1,17 @@
[package]
name = "online-games"
description = "A player's games from Lichess and Chess.com by nickname, kept as a PGN database that later fetches only the new games (the desktop and Android apps share it)"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
authors.workspace = true
publish = false
[dependencies]
serde.workspace = true
serde_json.workspace = true
ureq = "3.4"
[dev-dependencies]
chess-core.workspace = true

File diff suppressed because it is too large Load diff

View file

@ -27,7 +27,7 @@
4. **Ходы листаются кнопками внизу, под большим пальцем.** Свайпов по доске и по нотации нет. Единственный жест «вбок» — системный «назад». 4. **Ходы листаются кнопками внизу, под большим пальцем.** Свайпов по доске и по нотации нет. Единственный жест «вбок» — системный «назад».
5. **Соседняя партия открывается стрелками ‹ › в верхней панели.** Перейти к ходу и перейти к партии невозможно перепутать: у кнопок разные места, формы и размеры значков. 5. **Соседняя партия открывается стрелками ‹ › в верхней панели.** Перейти к ходу и перейти к партии невозможно перепутать: у кнопок разные места, формы и размеры значков.
6. **Движок включается одной кнопкой — в каждой партии заново.** Открытая партия всегда начинается с выключенным движком. Он сам выключается, когда человек выходит из партии, приложение уходит в фон или гаснет экран. Старая оценка не показывается для новой позиции ни на миг. В сборке без движка эта же кнопка предлагает его скачать (§8.4). 6. **Движок включается одной кнопкой — в каждой партии заново.** Открытая партия всегда начинается с выключенным движком. Он сам выключается, когда человек выходит из партии, приложение уходит в фон или гаснет экран. Старая оценка не показывается для новой позиции ни на миг. В сборке без движка эта же кнопка предлагает его скачать (§8.4).
7. **Приложение работает без интернета.** Сеть нужна только для облачного файла и для скачивания движка в сборке без него. 7. **Приложение работает без интернета.** Сеть нужна только для облачного файла, для скачивания движка в сборке без него и для партий с Lichess и Chess.com (§23) — и только после нажатия человека.
8. **Вид — спокойный и аккуратный:** цвета и доска те же, что на компьютере и сайте, Material 3 без украшений (§10). 8. **Вид — спокойный и аккуратный:** цвета и доска те же, что на компьютере и сайте, Material 3 без украшений (§10).
## 1. Источники: что заимствуем ## 1. Источники: что заимствуем
@ -1337,6 +1337,51 @@ FAB открывает лист, а не сразу системный выбо
- `review_next` на компьютере «Перейти к следующей» согласуется только с «неточностью» и «ошибкой», а не с «зевком»; на телефоне — нейтрально «к следующему такому ходу». Компьютеру — по желанию то же. - `review_next` на компьютере «Перейти к следующей» согласуется только с «неточностью» и «ошибкой», а не с «зевком»; на телефоне — нейтрально «к следующему такому ходу». Компьютеру — по желанию то же.
- Остальные пять языков для строк с *: «Erneut» / «Von vorn» (de), «Empezar de nuevo» (es), «Recommencer» (fr), «Ricomincia» (it) для `review_restart`; «Analyse ausblenden», «Ocultar el análisis», «Masquer l'analyse», «Nascondi l'analisi» для `review_hide`; `review_next` — «Zum nächsten solchen Zug», «Ir a la siguiente jugada así», «Aller au coup suivant de ce type», «Vai alla prossima mossa di questo tipo»; `review_engine_paused` — с заглавной: «Pausiert: …», «En pausa: …», «En pause : …», «In pausa: …». - Остальные пять языков для строк с *: «Erneut» / «Von vorn» (de), «Empezar de nuevo» (es), «Recommencer» (fr), «Ricomincia» (it) для `review_restart`; «Analyse ausblenden», «Ocultar el análisis», «Masquer l'analyse», «Nascondi l'analisi» для `review_hide`; `review_next` — «Zum nächsten solchen Zug», «Ir a la siguiente jugada así», «Aller au coup suivant de ce type», «Vai alla prossima mossa di questo tipo»; `review_engine_paused` — с заглавной: «Pausiert: …», «En pausa: …», «En pause : …», «In pausa: …».
### 14.8. Партии с Lichess и Chess.com (§23)
Слова — как на компьютере (`apps/desktop/src/i18n.rs`, блок онлайн-партий), где строка там есть. ✎ — изменить, + — добавить. `{games}` — `games_count` («473 партии»), `{n}` — число с пробелами между разрядами (`groupDigits`), никогда не голый `%d` для числа партий.
| Ключ | RU | EN |
|---|---|---|
| `online_title` | Партии с Lichess и Chess.com | Games from Lichess and Chess.com |
| `online_title_short` + (только если длинный заголовок обрезается, §23.2) | Lichess и Chess.com | Lichess and Chess.com |
| `add_online_hint` | Партии любого игрока по нику: свои, ученика, соперника | Any player's games by nickname: yours, a pupil's, an opponent's |
| `online_intro` ✎ (не повторять подпись листа) | Партии игрока станут базой на телефоне — искать, смотреть, анализировать. Нужен только ник, входить на сайт не нужно. | The player's games become a database on your phone, to search, view and analyse. Only the nickname is needed, no login. |
| `online_nick` / `online_nick_lichess` + (когда открыто второе поле) | Ник игрока / Ник на Lichess | Player's nickname / Nickname on Lichess |
| `online_nick_hint` | как на сайте | as on the site |
| `online_other` / `online_other_nick` / `online_same_nick` | На Chess.com другой ник / Ник на Chess.com / Тот же ник | A different nickname on Chess.com / Nickname on Chess.com / The same nickname |
| `online_nick_rule` | Латиница, цифры, _ и -, от 2 до 30 символов | Latin letters, digits, _ and -, 2 to 30 characters |
| `online_find` / `online_searching` | Найти / Ищу на сайтах… | Find / Looking on the sites… |
| `games_up_to` + (plurals) | до {n} партии (one) / до {n} партий (few, many) / до {n} партии (other) | up to {n} game / up to {n} games |
| `online_lichess_found` ✎ | {up_to} · первый раз около {m} мин | {up_to} · about {m} min the first time |
| `online_lichess_quick` + | {up_to} · первый раз меньше минуты | {up_to} · under a minute the first time |
| `online_chesscom_found` | месяцев с партиями: {m} | months with games: {m} |
| `online_not_found` ✎ (как на компьютере) | {site}: игрока с таким ником нет — проверьте написание | {site}: no player with this nickname — check the spelling |
| `online_merge` / `online_merge_hint` | Объединить оба сайта в одну базу / Иначе у каждого сайта будет своя база | Merge both sites into one database / Otherwise each site gets a database of its own |
| `online_into_new` / `online_into_existing` | В новую базу «{name}» / В базу «{name}» (там уже {games}; добавятся только новые) | Into the new database “{name}” / Into “{name}” ({games} there already; only new games are added) |
| `online_download` / `online_stop` / `online_open` | Скачать / Остановить / Открыть базу | Download / Stop / Open the database |
| `online_progress_lichess` ✎ (`{t}` — число, без слова) | Lichess: {n} из примерно {t} · осталось около {m} мин | Lichess: {n} of about {t} · about {m} min left |
| `online_progress_chesscom` | Chess.com: месяц {i} из {k} · {games} | Chess.com: month {i} of {k} · {games} |
| `online_leave` + | Можно уйти с этого экрана: база уже в списке, скачивание продолжится. | You can leave this screen: the database is on the list and the download goes on. |
| `online_done` + (первое скачивание) | Готово: {games} | Done: {games} |
| `online_added` ✎ (`{n}` с разрядами) | +{n}, всего {games} | +{n}, {games} in all |
| `online_no_new` / `online_stopped` | Новых партий нет, в базе {games} / Остановлено, в базе {games} | No new games, {games} in the database / Stopped, {games} in the database |
| `online_no_games` | Партий в обычные шахматы там нет. | No games of standard chess there. |
| `online_try_again` | Попробовать ещё раз | Try again |
| `online_err_*` | §23.4, как на компьютере; `online_err_disk` — «на телефоне не хватает места» | as on the desktop; `online_err_disk` — “the phone is out of space” |
| `online_short_network` / `online_short_rate` / `online_short_failed` | {site} не отвечает / {site} просит паузу / Скачивание прервалось | {site} does not answer / {site} asks for a pause / The download stopped |
| `online_update` / `online_stop_download` | Скачать новые партии / Остановить скачивание | Download new games / Stop the download |
| `online_downloading` | Скачивается · {n} | Downloading · {n} |
| `online_updated` / `online_updated_now` + / `online_unfinished` | обновлено {when} / обновлено только что / не докачана | updated {when} / updated just now / not finished |
| `online_snack_added` + / `online_snack_none` + / `online_snack_failed` + | «{name}»: +{n}, всего {games} / «{name}»: новых партий нет / «{name}»: {short} | “{name}”: +{n}, {games} in all / “{name}”: no new games / “{name}”: {short} |
| `online_removed` | Скачанная база удалена | Downloaded database deleted |
| `db_empty_body` ✎ | Добавьте файл PGN, базу ChessBase или архив .zip/.7z — с телефона или из облака — или скачайте партии с Lichess и Chess.com. | Add a PGN file, a ChessBase database or a .zip/.7z archive — from your phone or the cloud — or download games from Lichess and Chess.com. |
- **Почему `games_up_to`.** «до» и «из примерно» требуют родительного падежа: «до 24 партий», а `games_count` даёт «24 партии». В `online_progress_lichess` проще всего, как на компьютере, подставить голое число. В de/es/fr/it падеж не меняется — там `games_up_to` повторяет `games_count` с предлогом: «bis zu {n} Partien», «hasta {n} partidas», «jusqu'à {n} parties», «fino a {n} partite».
- **`online_added`:** сейчас `+%1$d` — «+6541» без пробела, а рядом «6 541 партия». Подставлять `groupDigits`.
- **Новые строки, другие языки.** `online_leave`: «Sie können diesen Bildschirm verlassen: die Datenbank ist in der Liste, der Download läuft weiter.» / «Puedes salir de esta pantalla: la base ya está en la lista y la descarga continúa.» / «Vous pouvez quitter cet écran : la base est dans la liste et le téléchargement continue.» / «Puoi uscire da questa schermata: la base è già nell'elenco e il download continua.» `online_done`: «Fertig: {games}» / «Listo: {games}» / «Terminé : {games}» / «Fatto: {games}». `online_updated_now`: «gerade aktualisiert» / «actualizada ahora mismo» / «mise à jour à l'instant» / «aggiornata adesso». `online_nick_lichess`: «Nickname auf Lichess» / «Apodo en Lichess» / «Pseudo sur Lichess» / «Nickname su Lichess». `online_not_found`, `online_snack_*` — с компьютера (`✖` не ставить).
- **Мелочи остальных языков.** it `online_downloading` «Download · {n}» читается как кнопка — лучше «Download in corso · {n}». fr `online_title` как на компьютере («de Lichess et Chess.com») — оставить ради единства.
## 15. Первая версия и дальше ## 15. Первая версия и дальше
### 15.1. Первая версия ### 15.1. Первая версия
@ -1355,7 +1400,7 @@ FAB открывает лист, а не сразу системный выбо
3. Справочник позиции (как вкладка «Справочник» на компьютере) и поиск по позиции. 3. Справочник позиции (как вкладка «Справочник» на компьютере) и поиск по позиции.
4. Перевод комментариев (`translation-ui.md`). 4. Перевод комментариев (`translation-ui.md`).
5. Отчёт по партии. 5. Отчёт по партии.
6. Скачивание партий с Lichess и Chess.com по нику. 6. ~~Скачивание партий с Lichess и Chess.com по нику.~~ Сделано (§23).
7. «Поделиться» картинкой позиции. 7. «Поделиться» картинкой позиции.
8. Порядок баз перетаскиванием, фильтры для малых баз. 8. Порядок баз перетаскиванием, фильтры для малых баз.
9. Магазины приложений: F-Droid, Google Play. 9. Магазины приложений: F-Droid, Google Play.
@ -1538,3 +1583,104 @@ FAB открывает лист, а не сразу системный выбо
- §21.6 — «Пауза: идёт анализ партии» с заглавной, без ▾. - §21.6 — «Пауза: идёт анализ партии» с заглавной, без ▾.
- §12.3, §14.7 — озвучивание и таблица строк; правки «Скрыть анализ», «Лучшая линия · ход …», «к следующему такому ходу»; `review_no_line` удалить. - §12.3, §14.7 — озвучивание и таблица строк; правки «Скрыть анализ», «Лучшая линия · ход …», «к следующему такому ходу»; `review_no_line` удалить.
- По итогам тестирования (2026-10-23): поворот телефона во время анализа не останавливает его насовсем — анализ продолжается сам, как после возврата из фона; посчитанное пишется в кэш и по ходу работы (раз в 10 с), чтобы падение приложения не теряло минуты работы; «Дополнить» считает с тем же качеством, что и первый прогон (один отчёт — одно качество), поэтому оценка времени при «Дополнить» берёт прежнее качество, а выбор качества относится к «Заново»; у партии без ходов пункт ⋮ неактивен; пат в конце, как и мат, движку не отдаётся; в альбомной ориентации правая колонка не заходит под системные кнопки. - По итогам тестирования (2026-10-23): поворот телефона во время анализа не останавливает его насовсем — анализ продолжается сам, как после возврата из фона; посчитанное пишется в кэш и по ходу работы (раз в 10 с), чтобы падение приложения не теряло минуты работы; «Дополнить» считает с тем же качеством, что и первый прогон (один отчёт — одно качество), поэтому оценка времени при «Дополнить» берёт прежнее качество, а выбор качества относится к «Заново»; у партии без ходов пункт ⋮ неактивен; пат в конце, как и мат, движку не отдаётся; в альбомной ориентации правая колонка не заходит под системные кнопки.
## 23. Партии с Lichess и Chess.com (2026-10-23)
То же, что на компьютере (0.8.0, `CHANGELOG.md`): партии любого игрока по нику — свои, ученика, соперника — без входа на сайт, в базу PGN; позже «Скачать новые партии» добавляет только новые. Скачивание, файл состояния, продолжение после обрыва без повторов — общий крейт `online-games`, тот же, что на компьютере.
Сеть: обе сборки получают разрешение INTERNET (раньше сборка с движком в сеть не ходила). В сеть ничего не уходит, пока человек сам не нажал «Найти» или «Скачать»; при запуске сайты не опрашиваются (на компьютере опрашиваются — на телефоне это лишний трафик и батарея).
### 23.1. Пути пользователя
1. **Первый раз.** Базы → «Добавить базу» → «Партии с Lichess и Chess.com» (первая строка листа, после «Вставить из буфера», если она есть) → экран: ник → «Найти» → что нашлось на каждом сайте → «Скачать». Ход скачивания виден на этом же экране; с экрана можно уйти — база уже в списке, её строка показывает «Скачивается · 1 234». Когда готово — «Открыть базу».
2. **Новые партии.** Механизм — докачка (решение владельца): «Скачать новые партии» берёт только партии, сыгранные после прошлого скачивания. Два входа: строка базы → ⋮ и значок ⤓ в верхней панели «Партий» этой базы (§23.3). Итог — снекбар «Magnus: +12, всего 1 246» или «Magnus: новых партий нет», как на компьютере. Без снекбара человек не узнаёт, что докачка прошла впустую: подпись «обновлено 1 мин назад» этого не говорит.
3. **Разные ники.** Ссылка «На Chess.com другой ник» открывает второе поле; первое тогда называется «Ник на Lichess».
4. **Оба сайта.** Найдены оба — по умолчанию одна база «Ник (Lichess + Chess.com)»; выключенный переключатель «Объединить оба сайта в одну базу» делает две.
5. **Обрыв.** Нет сети, сайт просит паузу, приложение закрыли — скачанное остаётся в базе, подпись «не докачана» или текст ошибки, «Скачать новые партии» продолжает с того же места без повторов.
6. **Удаление.** «Убрать из списка» удаляет скачанную базу с телефона, как копию (§20), со снекбаром «Скачанная база удалена · Вернуть»; идущее скачивание при этом останавливается.
7. **Ничего не скачалось** (на сайте только варианты шахмат или ошибка с первого запроса) — базы с нулём партий не бывает: строка исчезает из списка, а на экране скачивания остаётся причина.
Отдельной кнопки «Lichess» на экране «Базы» нет: вход в листе «Добавить базу» достаточно заметен (это первая постоянная строка), а лишняя кнопка спорила бы с FAB. Пустой экран (§3.1) упоминает сайты в тексте `db_empty_body` — так новичок узнаёт о возможности до того, как откроет лист.
### 23.2. Экран «Партии с Lichess и Chess.com»
```
┌────────────────────────────────────┐
│ ← Партии с Lichess и Chess.com │
│ │
│ Скачать партии любого игрока по │
│ нику: свои, ученика, соперника. │
│ ┌ Ник игрока ──────────────────┐ │ поле, «как на сайте»
│ └──────────────────────────────┘ │
│ На Chess.com другой ник │ ссылка → второе поле
│ [Найти] │
│ ─────────────────────────────── │
│ ☑ Lichess · Magnus │ после поиска
│ до 6 541 партии · ≈ 6 мин │
│ ☑ Chess.com · magnus │
│ месяцев с партиями: 84 │
│ Объединить оба сайта в одну (●) │ только если отмечены оба
│ базу │
│ Иначе у каждого сайта своя база │
│ В новую базу «Magnus (Lichess + │
│ Chess.com)» │
│ [Скачать] │
└────────────────────────────────────┘
```
Уточнения после ревью (2026-10-23):
- **Поля экрана 16 dp** (§10.1), не 24: 24 — для листов. Ссылка «На Chess.com другой ник» выровнена по левому краю поля (у `TextButton` свой отступ 12 dp — его убрать `contentPadding`, иначе ссылка «съезжает» вправо, как на снимке).
- **Заголовок в верхней панели** — `online_title`. Он переносится на две строки и при шрифте 200 % занимает три; если тестировщик увидит обрезку, в панели показывать короткое `online_title_short` «Lichess и Chess.com», а полное имя оставить в листе «Добавить базу».
- **Вводный текст** `bodyMedium` (14sp), не `bodyLarge`: это пояснение, а не содержание; так поле ника поднимается выше клавиатуры.
- **Правило ника** — красным, только если в нике есть недопустимый знак или в нём больше 30 знаков. Ник из одной буквы, пока его печатают, не ошибка: «Найти» просто неактивна. Ребёнок не должен видеть красное после первой же буквы.
- **«Найти»** скрывает клавиатуру (результаты иначе остаются под ней) и прокручивает к ним. После поиска, пока ник не изменён, «Найти» становится контурной: главная кнопка на экране одна — «Скачать».
- **Строка Lichess:** «до 6 541 партии · первый раз около 6 мин». «До» — потому что в счёт сайта входят и варианты шахмат, которые не скачиваются. Число с предлогом склоняется отдельным plurals `games_up_to` (RU: «до 1 партии», «до 24 партий», «до 6 541 партии»), а не через `games_count` — «до 24 партии» неграмотно. Если на скачивание нужно меньше минуты — «первый раз меньше минуты».
- **Не найден** — как на компьютере: «Lichess: игрока с таким ником нет — проверьте написание», без галочки. Сайт не ответил — текст ошибки (§23.4) цветом `error` и «Попробовать ещё раз».
- **Переключатель** «Объединить оба сайта в одну базу» — строка 64 dp целиком переключает (`toggleable`, роль Switch); по умолчанию включён.
- **Куда:** «В новую базу «…»» или «В базу «…» (там уже 1 234; добавятся только новые)». Имя — как в списке баз (с учётом переименования), а не имя файла.
- **После «Скачать»** кнопка «Скачать» и галочки скрываются, пока человек не нажмёт «Найти» снова (новый ник или те же). Иначе в конце на экране две заполненные кнопки — «Скачать» и «Открыть базу», и повторное «Скачать» неочевидно, что делает.
- **Карточка скачивания:** имя базы (`titleMedium`), строка хода («Lichess: 1 200 из примерно 6 541 · осталось около 5 мин», «Chess.com: месяц 12 из 84 · 340 партий»; общее число — цифрами, без слова «партий»), полоса, под ней `online_leave` «Можно уйти с этого экрана: база уже в списке, скачивание продолжится» и «Остановить» (контурная).
- Полоса при двух сайтах в одной базе — общая: доля = (номер сайта + доля сайта) / число сайтов. Сейчас она доходит до конца на Lichess и снова начинается с нуля на Chess.com.
- **Итог:** первое скачивание — «Готово: 6 541 партия»; докачка — «+12, всего 1 246»; без новых — «Новых партий нет, в базе 1 234»; остановлено — «Остановлено, в базе 1 200». Затем «Открыть базу» (заполненная). Ошибка — текст §23.4 цветом `error`, и при этом, если в базе что-то есть, тоже «Открыть базу».
- **Поворот экрана** сохраняет найденное (`found`, отметки) — человек не должен искать заново.
### 23.3. Строка такой базы в списке
- Значок формата «PGN», подпись: «1 234 партии · обновлено 3 ч назад»; пока не закончено ни одно скачивание — «1 234 партии · не докачана». Меньше минуты назад — «обновлено только что» (не «1 минуту назад»).
- Во время скачивания: «Скачивается · 1 234» и полоса 2 dp по низу строки; ⋮ → «Остановить скачивание» (первым пунктом, на месте «Скачать новые партии»).
- Ошибка последнего скачивания — подпись цветом `error`, число партий остаётся: «1 234 партии · Lichess не отвечает». Сейчас счёт пропадает, и база выглядит пустой. ⋮ → «Скачать новые партии» пробует снова.
- Конец любого скачивания, пока виден экран «Базы» (в том числе начатого на экране §23.2, если человек ушёл с него), — снекбар 4 с: «Magnus: +12, всего 1 246» / «Magnus: новых партий нет» / «Magnus: Lichess не отвечает» (короткая форма). Действие снекбара — «Открыть», если в базе есть партии. Это единственная обратная связь докачки из списка (§23.1 п. 2).
- **Верхняя панель «Партий» такой базы:** рядом с поиском значок `download` (Material Symbols), описание «Скачать новые партии». Пока идёт скачивание — на его месте ✕ «Остановить скачивание», под панелью полоса 2 dp; по концу — тот же снекбар, и список перечитывается сам, оставаясь на месте прокрутки. Зачем: базу своих партий открывают каждый день, и «новые партии» ищут там, где партии, а не в ⋮ списка баз. Свайп «потянуть, чтобы обновить» не делаем: жест скрытый, а ребёнок его не найдёт (§0 п. 4).
### 23.4. Тексты ошибок
Как на компьютере: «{site} не отвечает. Проверьте подключение к интернету и попробуйте ещё раз.»; «{site} просит сделать паузу…»; «{site} ответил непонятно…»; «Не удалось записать базу: на телефоне не хватает места.»; «Эта база уже скачивается.» Короткие формы для строки базы и снекбара: «{site} не отвечает», «{site} просит паузу», «Скачивание прервалось».
### 23.5. Порядок партий (решение владельца, 2026-10-23)
- В скачанной базе партии идут **от последней сыгранной к первой**: по `UTCDate` + `UTCTime`, если их нет — по `Date`; партии двух сайтов перемешаны по времени. Остальные базы — в порядке файла, как раньше.
- ‹ › в партии и поиск идут в том же порядке; номер в строке партии — место в этом списке (№ 1 — самая свежая).
- После докачки новые партии оказываются наверху — поэтому список после «Скачать новые партии» возвращается к началу только если человек и так был в начале; иначе остаётся на месте.
- Вторая строка партии такой базы (предложение, nice): полная дата вместо года — «блиц · 12 мар. 2026 · C42». Год у всех партий за последний месяц одинаков и не помогает найти «вчерашнюю».
### 23.6. TalkBack
- Строка хода скачивания **не** живая область: она меняется 2–3 раза в секунду, и TalkBack читал бы её без остановки. Живая область (`Polite`) — только итог и ошибки; ход читается по фокусу.
- «Ищу на сайтах…» и найденные строки — живая область `Polite` один раз, после поиска.
- Найденная строка: «Lichess, Magnus, до 6 541 партии, первый раз около 6 минут, флажок, отмечен».
- Строка базы во время скачивания: «Magnus (Lichess + Chess.com), скачивается, 1 234».
- Значок в «Партиях»: «Скачать новые партии, кнопка» / «Остановить скачивание, кнопка».
## 24. Ревью «Партий с Lichess и Chess.com» (2026-10-23)
Ревью реализации (`OnlineScreen.kt`, `DatabasesScreen.kt`, `AddDatabase.kt`, `OnlineDownloads.kt`, строки `online_*` на шести языках) и снимков с эмулятора. Что изменено в спецификации:
- §0 п. 7 — сеть нужна и для партий с сайтов, только по нажатию; §15.2 п. 6 — сделано.
- §23.1 — докачка как механизм обновления (решение владельца); второй вход «Скачать новые партии» — значок в «Партиях» этой базы; итог докачки — снекбар; база без партий исчезает; отдельной кнопки на «Базах» нет, о сайтах говорит пустой экран.
- §23.2 — поля 16 dp; вводный текст 14sp и без повтора подписи листа; правило ника не краснеет от первой буквы; «Найти» прячет клавиатуру; «Скачать» скрывается после запуска (две заполненные кнопки в конце); общая полоса для двух сайтов; подсказка «можно уйти с экрана»; «Готово: N партий» вместо «+N, всего N» при первом скачивании; имя базы — как в списке; найденное переживает поворот.
- §23.3 — ошибка не прячет число партий; «обновлено только что»; снекбар по концу скачивания; значок в верхней панели «Партий».
- §23.5 — порядок партий от последней (решение владельца), ‹ › и поиск в том же порядке.
- §23.6 — TalkBack: ход скачивания не живая область.
- §14.8 — таблица строк; падеж после «до» и «из примерно» (`games_up_to`, голое число), разряды в `online_added`.
- По итогам тестирования (2026-10-23): найденное на экране §23.2 живёт вместе с экраном (у каждого экрана навигации своё хранилище состояния и ViewModel) — повторный вход начинается с чистого экрана, поворот найденное сохраняет; число партий и время обновления скачанной базы при запуске и после «Вернуть» берутся из файла состояния скачивания (докачка, оборванная закрытием приложения, сразу видна в строке); снекбар «База удалена · Вернуть» держится 10 с, а не бесконечно. Известно: при шрифте 130 % подпись строки базы обрезается многоточием.