Samples: the built-in databases are brought up to the program's version
At every start a sample's file that is not the text built into the program (an older version, damaged or edited outside) is replaced atomically, under its name in any language; a sample taken off the shelf stays off. Android reads the samples from the app's assets: the number of games on a row is taken again when the sample's SHA-256 is not the one it was counted from. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
1524affd1a
commit
a328f429c5
7 changed files with 194 additions and 54 deletions
|
|
@ -73,7 +73,8 @@ data class DbEntry(
|
|||
val format: String? = null,
|
||||
/// A sample shows the name of the current language until it is renamed (displayName).
|
||||
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. A sample's: of
|
||||
/// the text its number of games was taken from (a new app may bring a new text).
|
||||
val sha256: String? = null,
|
||||
/// A downloaded database: when its last download finished (Unix seconds).
|
||||
val updated: Long? = null,
|
||||
|
|
@ -204,6 +205,18 @@ class Library(private val context: Context) {
|
|||
return names.map { (f, name) -> DbEntry(id = "sample-$f", name = name, source = Source.Sample, location = "examples/$f", fileName = f) }
|
||||
}
|
||||
|
||||
/// Counts the samples on the list not counted yet, or counted in a text other than
|
||||
/// the one in this app: an update of the app brings a sample's new version (more
|
||||
/// games), read from the app itself as ever, and its row shows it at once.
|
||||
suspend fun countSamples() {
|
||||
for (e in _entries.value.filter { it.source == Source.Sample }) {
|
||||
if (e.games != null && e.sha256 == withContext(Dispatchers.IO) { sha256(sampleBytes(e)) }) continue
|
||||
database(e.id)
|
||||
}
|
||||
}
|
||||
|
||||
private fun sampleBytes(e: DbEntry): ByteArray = context.assets.open(e.location).use { it.readBytes() }
|
||||
|
||||
/// Puts the sample games back on the list (those not on it), at its end.
|
||||
fun addSamples() = update { list -> list + samples().filter { s -> list.none { it.id == s.id } } }
|
||||
|
||||
|
|
@ -579,10 +592,14 @@ class Library(private val context: Context) {
|
|||
suspend fun database(id: String): Result<Database> = lock.withLock {
|
||||
open[id]?.let { return@withLock Result.success(it) }
|
||||
val e = entry(id) ?: return@withLock Result.failure(IllegalArgumentException("no database $id"))
|
||||
var text: String? = e.sha256
|
||||
val result = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
when (e.source) {
|
||||
Source.Sample -> openBytes(e.fileName, context.assets.open(e.location).use { it.readBytes() })
|
||||
Source.Sample -> sampleBytes(e).let { bytes ->
|
||||
text = sha256(bytes)
|
||||
openBytes(e.fileName, bytes)
|
||||
}
|
||||
Source.File -> openFile(e.fileName, openDocument(Uri.parse(e.location)).detachFd())
|
||||
Source.ChessBase -> openChessBase(e)
|
||||
Source.Copy -> openFile(
|
||||
|
|
@ -601,10 +618,14 @@ class Library(private val context: Context) {
|
|||
open[id] = db
|
||||
val games = db.len().toInt()
|
||||
val format = db.format()
|
||||
if (e.games != games || e.format != format) {
|
||||
update { list -> list.map { if (it.id == id) it.copy(games = games, format = format) else it } }
|
||||
val sum = text
|
||||
if (e.games != games || e.format != format || e.sha256 != sum) {
|
||||
update { list -> list.map { if (it.id == id) it.copy(games = games, format = format, sha256 = sum) else it } }
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
private fun sha256(bytes: ByteArray): String =
|
||||
java.security.MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }
|
||||
|
|
|
|||
|
|
@ -224,9 +224,7 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett
|
|||
}
|
||||
val scroll = TopAppBarDefaults.pinnedScrollBehavior()
|
||||
// The samples are small: read them at once, so their rows show the number of games.
|
||||
LaunchedEffect(Unit) {
|
||||
library.entries.value.filter { it.source == Source.Sample && it.games == null }.forEach { library.database(it.id) }
|
||||
}
|
||||
LaunchedEffect(Unit) { library.countSamples() }
|
||||
|
||||
Scaffold(
|
||||
modifier = Modifier.nestedScroll(scroll.nestedScrollConnection),
|
||||
|
|
|
|||
|
|
@ -360,7 +360,7 @@ impl App {
|
|||
let _ = settings.save();
|
||||
}
|
||||
let engines_found = crate::engines::first_run_setup(&mut settings);
|
||||
if crate::examples::first_run_setup(&mut settings) || engines_found {
|
||||
if crate::examples::setup(&mut settings) || engines_found {
|
||||
let _ = settings.save();
|
||||
}
|
||||
// PGN files passed on the command line (e.g. "Open with…") join the library, first one selected.
|
||||
|
|
|
|||
|
|
@ -1,25 +1,27 @@
|
|||
//! Sample databases for the first start, so the library is not empty: classic games
|
||||
//! with short introductions, and Alekhine's games (moves only). They are written once,
|
||||
//! named in the interface language, to `<local data dir>/examples/` and put on the
|
||||
//! library shelf; a sample removed from the shelf does not come back.
|
||||
//! Sample databases of the program, so the library is not empty: classic games with
|
||||
//! short introductions, and Alekhine's games (moves only). At the first start they are
|
||||
//! written, named in the interface language, to `<local data dir>/examples/` and put on
|
||||
//! the library shelf; a sample removed from the shelf does not come back.
|
||||
//!
|
||||
//! The samples are read only, so their files are the program's: at every start a file
|
||||
//! that is not the text built into this version (an older version of the sample, a file
|
||||
//! damaged or edited outside) is replaced by it, whether on the shelf or not. Nothing
|
||||
//! keeps a sample by its place in the file: the counts of the cards are of the file's
|
||||
//! size and time, the marks of viewed games of the games' text.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::i18n::tr;
|
||||
use crate::i18n::{all_languages, tr};
|
||||
use crate::settings::Settings;
|
||||
|
||||
fn files() -> [(&'static str, &'static str); 2] {
|
||||
[
|
||||
(
|
||||
tr("Classic games"),
|
||||
include_str!("../../../examples/classics.pgn"),
|
||||
),
|
||||
(
|
||||
tr("Alekhine"),
|
||||
include_str!("../../../examples/alekhine.pgn"),
|
||||
),
|
||||
]
|
||||
}
|
||||
/// The samples: the English name (a key of the translations) and the text.
|
||||
const SAMPLES: [(&str, &str); 2] = [
|
||||
(
|
||||
"Classic games",
|
||||
include_str!("../../../examples/classics.pgn"),
|
||||
),
|
||||
("Alekhine", include_str!("../../../examples/alekhine.pgn")),
|
||||
];
|
||||
|
||||
fn dir() -> Option<PathBuf> {
|
||||
directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin")
|
||||
|
|
@ -32,44 +34,67 @@ pub fn is_example(path: &std::path::Path) -> bool {
|
|||
dir().is_some_and(|d| path.starts_with(d))
|
||||
}
|
||||
|
||||
/// Adds the samples once; `true` when the settings changed. A new library starts with
|
||||
/// them (the classics open); an existing one gets them after its own databases.
|
||||
pub fn first_run_setup(settings: &mut Settings) -> bool {
|
||||
if settings.examples_added {
|
||||
return false;
|
||||
/// Adds the samples at the first start and brings their files up to this version;
|
||||
/// `true` when the settings changed. A new library starts with them (the classics
|
||||
/// open); an existing one gets them after its own databases.
|
||||
pub fn setup(settings: &mut Settings) -> bool {
|
||||
match dir() {
|
||||
Some(dir) => setup_in(&dir, settings),
|
||||
None => !std::mem::replace(&mut settings.examples_added, true),
|
||||
}
|
||||
settings.examples_added = true;
|
||||
let Some(dir) = dir() else {
|
||||
return true;
|
||||
};
|
||||
if let Err(e) = std::fs::create_dir_all(&dir) {
|
||||
eprintln!("examples: cannot create {}: {e}", dir.display());
|
||||
return true;
|
||||
}
|
||||
for (name, text) in files() {
|
||||
let path = dir.join(format!("{name}.pgn"));
|
||||
if !path.exists()
|
||||
&& let Err(e) = std::fs::write(&path, text)
|
||||
{
|
||||
eprintln!("examples: cannot write {}: {e}", path.display());
|
||||
continue;
|
||||
}
|
||||
|
||||
fn setup_in(dir: &Path, settings: &mut Settings) -> bool {
|
||||
let first = !std::mem::replace(&mut settings.examples_added, true);
|
||||
for (key, text) in SAMPLES {
|
||||
let named = dir.join(format!("{}.pgn", tr(key)));
|
||||
// The file is named in the language of the first start: the sample's file under
|
||||
// any language's name is it.
|
||||
for name in all_languages(key) {
|
||||
let path = dir.join(format!("{name}.pgn"));
|
||||
let kept = path.exists() || settings.databases.contains(&path);
|
||||
if (kept || (first && path == named))
|
||||
&& let Err(e) = bring_up_to_date(&path, text)
|
||||
{
|
||||
eprintln!("examples: cannot write {}: {e}", path.display());
|
||||
}
|
||||
}
|
||||
if !settings.databases.contains(&path) {
|
||||
settings.databases.push(path);
|
||||
if first && named.exists() && !settings.databases.contains(&named) {
|
||||
settings.databases.push(named);
|
||||
}
|
||||
}
|
||||
true
|
||||
first
|
||||
}
|
||||
|
||||
/// Writes `text` to `path` unless the file holds it already. The new file takes the old
|
||||
/// one's place at once (a program started meanwhile reads one or the other whole).
|
||||
fn bring_up_to_date(path: &Path, text: &str) -> std::io::Result<()> {
|
||||
if std::fs::read(path).is_ok_and(|on_disk| on_disk == text.as_bytes()) {
|
||||
return Ok(());
|
||||
}
|
||||
chess_core::pgn::store::write_atomic(path, text.as_bytes())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A folder of its own for each test, empty.
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("cp-examples-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
fn classics(dir: &Path) -> PathBuf {
|
||||
dir.join(format!("{}.pgn", tr("Classic games")))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn samples_are_valid_pgn() {
|
||||
for (name, text) in files() {
|
||||
let dir = std::env::temp_dir().join(format!("cp-examples-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let dir = folder("valid");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for (name, text) in SAMPLES {
|
||||
let path = dir.join(format!("{name}.pgn"));
|
||||
std::fs::write(&path, text).unwrap();
|
||||
let db = chess_core::PgnDatabase::open(
|
||||
|
|
@ -88,7 +113,83 @@ mod tests {
|
|||
parsed.diagnostics
|
||||
);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_start_writes_the_samples_and_shelves_them() {
|
||||
let dir = folder("first");
|
||||
let mut settings = Settings::default();
|
||||
assert!(setup_in(&dir, &mut settings));
|
||||
assert!(settings.examples_added);
|
||||
assert_eq!(settings.databases.len(), SAMPLES.len());
|
||||
assert_eq!(settings.databases[0], classics(&dir));
|
||||
for (path, (_, text)) in settings.databases.iter().zip(SAMPLES) {
|
||||
assert_eq!(std::fs::read_to_string(path).unwrap(), text);
|
||||
}
|
||||
// The next start changes nothing.
|
||||
let before = settings.databases.clone();
|
||||
assert!(!setup_in(&dir, &mut settings));
|
||||
assert_eq!(settings.databases, before);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_or_damaged_sample_is_replaced() {
|
||||
let dir = folder("older");
|
||||
let mut settings = Settings::default();
|
||||
setup_in(&dir, &mut settings);
|
||||
let path = classics(&dir);
|
||||
let old: String = SAMPLES[0].1.chars().take(SAMPLES[0].1.len() / 3).collect();
|
||||
std::fs::write(&path, old).unwrap();
|
||||
assert!(!setup_in(&dir, &mut settings));
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), SAMPLES[0].1);
|
||||
// Edited outside: the same.
|
||||
let mut edited = SAMPLES[0].1.to_owned();
|
||||
edited.push_str("\n[Event \"mine\"]\n\n1. e4 *\n");
|
||||
std::fs::write(&path, edited).unwrap();
|
||||
setup_in(&dir, &mut settings);
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), SAMPLES[0].1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A program that started in another language named the file in it.
|
||||
#[test]
|
||||
fn a_sample_named_in_another_language_is_replaced() {
|
||||
let dir = folder("language");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let russian = dir.join("Классические партии.pgn");
|
||||
std::fs::write(&russian, "[Event \"old\"]\n\n1. e4 *\n").unwrap();
|
||||
let mut settings = Settings {
|
||||
examples_added: true,
|
||||
databases: vec![russian.clone()],
|
||||
..Settings::default()
|
||||
};
|
||||
assert!(!setup_in(&dir, &mut settings));
|
||||
assert_eq!(std::fs::read_to_string(&russian).unwrap(), SAMPLES[0].1);
|
||||
// The samples of the other names are not made.
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
|
||||
assert_eq!(settings.databases, vec![russian]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sample_taken_off_the_shelf_stays_off() {
|
||||
let dir = folder("off");
|
||||
let mut settings = Settings::default();
|
||||
setup_in(&dir, &mut settings);
|
||||
let path = classics(&dir);
|
||||
settings.databases.retain(|p| *p != path);
|
||||
std::fs::write(&path, "[Event \"old\"]\n\n1. e4 *\n").unwrap();
|
||||
assert!(!setup_in(&dir, &mut settings));
|
||||
assert!(!settings.databases.contains(&path));
|
||||
// Its file is the new one, should the user open it again.
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), SAMPLES[0].1);
|
||||
// Deleted as well: not made again.
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
setup_in(&dir, &mut settings);
|
||||
assert!(!path.exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -120,6 +120,17 @@ pub fn tr(key: &'static str) -> &'static str {
|
|||
.unwrap_or(key)
|
||||
}
|
||||
|
||||
/// `key` in every language (English first; the same text once).
|
||||
pub fn all_languages(key: &'static str) -> Vec<&'static str> {
|
||||
let mut out = vec![key];
|
||||
for t in table().get(key).into_iter().flat_map(|row| row.iter()) {
|
||||
if !out.contains(t) {
|
||||
out.push(t);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// "1 game", "5 games" in the interface language, with Russian plural forms
|
||||
/// ("1 партия", "3 партии", "5 партий").
|
||||
pub fn games(n: usize) -> String {
|
||||
|
|
|
|||
|
|
@ -120,7 +120,7 @@ pub struct Settings {
|
|||
pub databases: Vec<PathBuf>,
|
||||
/// The first-start engine discovery has run (see `engines::first_run_setup`).
|
||||
pub engines_discovered: bool,
|
||||
/// The sample databases were put on the shelf (see `examples::first_run_setup`).
|
||||
/// The sample databases were put on the shelf (see `examples::setup`).
|
||||
pub examples_added: bool,
|
||||
/// Ask GitHub for a newer release at start (Settings → About).
|
||||
pub check_updates: bool,
|
||||
|
|
|
|||
|
|
@ -199,3 +199,12 @@
|
|||
- Настройки `review.{quality,threads,hash_mb,chosen}` и `prep.quality` удалены; старые файлы настроек читаются (лишние поля пропускаются).
|
||||
- Оценка времени — по скорости одного процесса из последнего разбора (или живого движка на поток; до замера — 700k узл/с на компьютере, 250k на телефоне) × число процессов.
|
||||
- Сверка с chess.com (`chesscom_check`) идёт в том же режиме; `CP_REVIEW_NODES` — только для подбора узлов в этом примере, кэш в отдельной папке. Первый прогон на 1M (правила — на коммите 968ab22, 10 партий): !! — 17 из 18 chess.com (94 %), наших 18, из них 94 % совпали; ! — 24 из 29 (83 %), наших 30, совпали 80 %; совпадений 41, расхождений 12.
|
||||
|
||||
## Встроенные базы-примеры обновляются с программой (2026-10-28)
|
||||
|
||||
Владелец: база классики растёт (до 120–150 партий) и должна быть сразу доступна, в том числе у тех, у кого уже лежит старая версия.
|
||||
|
||||
- **Компьютер** (`apps/desktop/src/examples.rs`). Текст примеров вшит в программу (`include_str!`). При первом запуске файлы пишутся в `<data>/examples/` под именем на языке интерфейса и ставятся на полку (`settings.examples_added`). При **каждом** запуске файл примера сравнивается с вшитым текстом побайтно; отличается (старая версия, повреждён, изменён снаружи) — заменяется атомарно (`chess_core::pgn::store::write_atomic`). Отдельной версии нет: версия — сам текст. Файл ищется под именем примера на любом языке (имя дал язык первого запуска).
|
||||
- Пример, убранный с полки, **на полку не возвращается**; его файл, если он остался на диске, всё равно обновляется (это файл программы, только для чтения; открыть его снова — получить новую версию). Удалённый с диска и не стоящий на полке файл заново не создаётся; стоящий на полке — создаётся.
|
||||
- Кэши не мешают: число партий на карточке (`db_counts`) привязано к размеру и времени файла — пересчитывается; отметки просмотренных партий (`viewed`) — к тексту партии, у неизменных партий сохраняются; поиск позиций по PGN и справочник держат данные в памяти, а замена идёт при запуске, до открытия баз.
|
||||
- **Android** (`data/Library.kt`). Примеры не копируются: читаются прямо из assets приложения, поэтому с обновлением приложения новая версия открывается сама. Запомненное число партий в строке списка сверяется с SHA-256 текста, из которого оно взято (`DbEntry.sha256`); не совпало — пример перечитывается при показе списка баз (`countSamples`).
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue