Play: games against the computer go by themselves into the player's database
docs/research/player-games-db.md, docs/design/player-games.md, decisions «Партии игрока записываются сами» (desktop; Android next): - «Roman — games against the computer» (without a name, «Games against the computer»), made at the first game in the folder of new databases; only new records are appended. - During a game a journal after every move (a lock held while the program runs); a crash leaves it to the next start, which writes the game once, unfinished. A failed write keeps the journal until the game is saved elsewhere or left. - The play dialog says where the games go (wraps under the name), a ▾ list of the computer's players with their ratings (↓/↑ in the field); a toast when the database is made; the result strip «Written to the database, No. n · Open» instead of «Save to a database…»; the leave question names it. - ♞ on the player's card and in the folded shelf; a checkbox in Settings → Interface → Your databases (on). Checked by the tester (crash, failed write, two instances, names, files of the same name) and the designer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
e1292bff3f
commit
300430f2a8
14 changed files with 1381 additions and 19 deletions
|
|
@ -397,6 +397,17 @@ impl App {
|
|||
);
|
||||
app.toast(ctx, msg);
|
||||
}
|
||||
// Games a crash left half played go into their databases now.
|
||||
for r in crate::player_games::recover() {
|
||||
let res = r.written.map_err(|e| {
|
||||
let db = own_db::base_name(&r.target);
|
||||
trf(
|
||||
"Could not write to «{db}»: {reason}",
|
||||
&[("db", &db), ("reason", &e)],
|
||||
)
|
||||
});
|
||||
app.recorded(ctx, &r.player, res, true);
|
||||
}
|
||||
app
|
||||
}
|
||||
|
||||
|
|
@ -649,9 +660,14 @@ impl App {
|
|||
}
|
||||
|
||||
fn toast(&mut self, ctx: &egui::Context, msg: impl Into<String>) {
|
||||
self.toast_for(ctx, msg, 3.5);
|
||||
}
|
||||
|
||||
/// A message said once and seldom (a database made for the player): longer in view.
|
||||
fn toast_for(&mut self, ctx: &egui::Context, msg: impl Into<String>, secs: f64) {
|
||||
self.toast = Some(Toast {
|
||||
text: msg.into(),
|
||||
until: ctx.input(|i| i.time) + 3.5,
|
||||
until: ctx.input(|i| i.time) + secs,
|
||||
undo: false,
|
||||
});
|
||||
}
|
||||
|
|
@ -873,6 +889,7 @@ impl App {
|
|||
});
|
||||
g.target = None;
|
||||
g.game.mark_saved();
|
||||
g.unwritten = None;
|
||||
}
|
||||
self.settings.last_target = Some(target.clone());
|
||||
self.settings_dirty = true;
|
||||
|
|
@ -909,6 +926,7 @@ impl App {
|
|||
block: None,
|
||||
});
|
||||
g.game.mark_saved();
|
||||
g.unwritten = None;
|
||||
}
|
||||
self.settings.last_target = Some(target.clone());
|
||||
self.settings_dirty = true;
|
||||
|
|
@ -1425,8 +1443,63 @@ impl App {
|
|||
Some(from) => self.game_from(from),
|
||||
None => self.new_game(),
|
||||
}
|
||||
// Where the game goes by itself (player-games.md): the player's database.
|
||||
let record = self
|
||||
.settings
|
||||
.record_games
|
||||
.then(|| self.player_target(&start.user_name));
|
||||
if let Some(g) = self.game.as_mut() {
|
||||
g.start_play(start, maia, judge, ctx);
|
||||
g.start_play(start, maia, judge, record, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
/// The database of the player of this name: theirs, else a new one in the folder of
|
||||
/// new databases.
|
||||
fn player_target(&self, name: &str) -> PathBuf {
|
||||
let dir = own_db::default_base_dir(self.settings.new_database_dir.as_deref());
|
||||
crate::player_games::target(&self.settings.players, name, &dir)
|
||||
}
|
||||
|
||||
/// A game went into the player's database (or a game a crash left, at the start):
|
||||
/// the player is linked to it, it is first on the shelf and read anew; a new one is
|
||||
/// said once.
|
||||
fn recorded(
|
||||
&mut self,
|
||||
ctx: &egui::Context,
|
||||
name: &str,
|
||||
res: Result<crate::player_games::Written, String>,
|
||||
crashed: bool,
|
||||
) {
|
||||
match res {
|
||||
Ok(w) => {
|
||||
crate::player_games::link(&mut self.settings.players, name, &w.path);
|
||||
self.settings.touch_database(&w.path);
|
||||
self.settings_dirty = true;
|
||||
self.library.reload(&w.path, ctx);
|
||||
let db = own_db::base_name(&w.path);
|
||||
if crashed {
|
||||
self.toast_for(
|
||||
ctx,
|
||||
trf(
|
||||
"An unfinished game (the program closed) is written to «{db}», No. {n}",
|
||||
&[("db", &db), ("n", &(w.index + 1))],
|
||||
),
|
||||
6.0,
|
||||
);
|
||||
} else if w.created {
|
||||
self.toast_for(
|
||||
ctx,
|
||||
trf(
|
||||
"Database «{db}» created: your games will be written there",
|
||||
&[("db", &db)],
|
||||
),
|
||||
6.0,
|
||||
);
|
||||
}
|
||||
}
|
||||
// The result strip says so (with «Add to database…»); after a crash, a toast.
|
||||
Err(e) if crashed => self.toast(ctx, e),
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -2323,9 +2396,20 @@ impl eframe::App for App {
|
|||
// The analysis options (its dialog) are kept.
|
||||
self.settings_dirty |= self.settings.review != review;
|
||||
self.reference_tab = game.reference_tab();
|
||||
// Before the actions: leaving may take the game away.
|
||||
if let Some(res) = game.record_news.take() {
|
||||
let name = game.player_name();
|
||||
self.recorded(&ctx, &name, res, false);
|
||||
}
|
||||
for a in actions {
|
||||
match a {
|
||||
GameAction::Back => self.request_close(&ctx, CloseIntent::BackToLibrary),
|
||||
// The game's database in the library, the game's row shown (its row is
|
||||
// revealed as the game closes).
|
||||
GameAction::OpenDatabase(path) => {
|
||||
self.library.select_db(&path, &ctx);
|
||||
self.request_close(&ctx, CloseIntent::BackToLibrary);
|
||||
}
|
||||
GameAction::FindPosition(db) => self.find_position(&ctx, db),
|
||||
GameAction::ReferenceChoose(p) => {
|
||||
self.settings.reference_db = Some(p);
|
||||
|
|
@ -2654,6 +2738,22 @@ impl eframe::App for App {
|
|||
|
||||
self.confirm_dialog(&ctx);
|
||||
self.own_dialogs(&ctx);
|
||||
// The number of games of the database the dialog names (read once, if needed).
|
||||
if let Some(d) = self.play_dialog.as_mut()
|
||||
&& let Some(path) = d.record_target().map(std::path::Path::to_path_buf)
|
||||
&& path.exists()
|
||||
&& !d.counts.contains_key(&path)
|
||||
{
|
||||
match self.library.database(&path) {
|
||||
Some(db) => {
|
||||
d.counts.insert(path, db.len());
|
||||
}
|
||||
None if !self.library.loading(&path) && self.library.failure(&path).is_none() => {
|
||||
self.library.load(&path, &ctx)
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
if let Some(d) = self.play_dialog.as_mut()
|
||||
&& let Some(out) = d.show(&ctx, &mut self.settings)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -66,6 +66,14 @@ pub struct GameView {
|
|||
pub play: Option<crate::play::Session>,
|
||||
/// The game just played: the result strip.
|
||||
pub play_end: Option<crate::play::End>,
|
||||
/// Where the game just played went by itself (player-games.md), or why it did not:
|
||||
/// said on the result strip.
|
||||
pub recorded: Option<Result<crate::player_games::Written, String>>,
|
||||
/// The same, once, for the program: the shelf, the player's link, a toast.
|
||||
pub record_news: Option<Result<crate::player_games::Written, String>>,
|
||||
/// The journal of a game its database did not take: kept (a crash still leaves the
|
||||
/// game to the next start) until the game is saved elsewhere or left.
|
||||
pub unwritten: Option<crate::player_games::Journal>,
|
||||
/// What the play started with (for the end, a rematch).
|
||||
play_start: Option<crate::play::Start>,
|
||||
/// «The game is on» asked (leaving during a game); the clocks wait meanwhile.
|
||||
|
|
@ -105,6 +113,8 @@ enum SideTab {
|
|||
|
||||
pub enum GameAction {
|
||||
Back,
|
||||
/// Back to the library with this database chosen (the game's own).
|
||||
OpenDatabase(PathBuf),
|
||||
/// «Play on from here»: the play dialog for this position.
|
||||
PlayFrom(Box<crate::play::StartFrom>),
|
||||
/// «Learn the opening up to this move»: the training over this game.
|
||||
|
|
@ -169,6 +179,9 @@ impl GameView {
|
|||
editor: None,
|
||||
play: None,
|
||||
play_end: None,
|
||||
recorded: None,
|
||||
record_news: None,
|
||||
unwritten: None,
|
||||
play_start: None,
|
||||
play_leave: None,
|
||||
paste_pending: None,
|
||||
|
|
@ -2100,6 +2113,7 @@ impl GameView {
|
|||
start: crate::play::Start,
|
||||
(engine, file): (crate::play::Engine, std::path::PathBuf),
|
||||
judge: Option<std::path::PathBuf>,
|
||||
record: Option<std::path::PathBuf>,
|
||||
ctx: &egui::Context,
|
||||
) {
|
||||
use crate::play::{Clock, Opponent, Session};
|
||||
|
|
@ -2191,7 +2205,9 @@ impl GameView {
|
|||
}
|
||||
self.flipped = start.user == Color::Black;
|
||||
self.play_end = None;
|
||||
self.recorded = None;
|
||||
self.play = Some(Session {
|
||||
journal: record.map(|t| crate::player_games::Journal::new(t, &start.user_name)),
|
||||
user: start.user,
|
||||
strength: start.strength,
|
||||
engine,
|
||||
|
|
@ -2463,6 +2479,7 @@ impl GameView {
|
|||
if let Some(e) = crate::play::ending(&self.mainline_positions()) {
|
||||
self.finish_play(e, actions);
|
||||
} else {
|
||||
self.keep_journal();
|
||||
self.ask_maia();
|
||||
}
|
||||
}
|
||||
|
|
@ -2523,7 +2540,10 @@ impl GameView {
|
|||
}
|
||||
};
|
||||
actions.push(GameAction::Toast(trf(text, &[("e", &err)])));
|
||||
self.play = None;
|
||||
// What was played is kept, unfinished.
|
||||
let journal = self.play.take().and_then(|mut s| s.journal.take());
|
||||
self.game.set_tag("Termination", "Unterminated");
|
||||
self.record(journal);
|
||||
self.game.mark_saved();
|
||||
actions.push(GameAction::Back);
|
||||
return;
|
||||
|
|
@ -2575,6 +2595,7 @@ impl GameView {
|
|||
self.game.set_result(ending.result());
|
||||
self.game.set_tag("Termination", ending.termination());
|
||||
self.game.forget_history();
|
||||
self.record(s.journal.take());
|
||||
let end = self.play_end_node();
|
||||
self.goto(end);
|
||||
if matches!(ending, crate::play::Ending::Checkmate { .. }) {
|
||||
|
|
@ -2590,6 +2611,56 @@ impl GameView {
|
|||
}
|
||||
}
|
||||
|
||||
/// The game as a crash would leave it, kept after each move (once both have moved).
|
||||
fn keep_journal(&self) {
|
||||
if !self.play_started() {
|
||||
return;
|
||||
}
|
||||
if let Some(j) = self.play.as_ref().and_then(|s| s.journal.as_ref()) {
|
||||
let mut g = self.game.clone();
|
||||
g.set_tag("Termination", "Unterminated");
|
||||
j.save(&g.to_pgn());
|
||||
}
|
||||
}
|
||||
|
||||
/// The game ended (or stopped): it goes into the player's database, once a move of
|
||||
/// it was made; it becomes that database's record.
|
||||
fn record(&mut self, journal: Option<crate::player_games::Journal>) {
|
||||
let Some(journal) = journal else { return };
|
||||
if self.played().is_empty() {
|
||||
return;
|
||||
}
|
||||
let name = crate::own_db::base_name(journal.target());
|
||||
let res = journal.finish(&self.game.to_pgn()).map_err(|e| {
|
||||
trf(
|
||||
"Could not write to «{db}»: {reason}",
|
||||
&[("db", &name), ("reason", &e)],
|
||||
)
|
||||
});
|
||||
if let Ok(w) = &res {
|
||||
self.source = Some(GameSource {
|
||||
path: w.path.clone(),
|
||||
index: w.index,
|
||||
block: None,
|
||||
});
|
||||
self.target = None;
|
||||
self.game.mark_saved();
|
||||
}
|
||||
if res.is_err() {
|
||||
self.unwritten = Some(journal);
|
||||
}
|
||||
self.recorded = Some(res.clone());
|
||||
self.record_news = Some(res);
|
||||
}
|
||||
|
||||
/// The player's name of the game against the computer on the screen.
|
||||
pub fn player_name(&self) -> String {
|
||||
self.play_start
|
||||
.as_ref()
|
||||
.map(|s| s.user_name.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Before both sides have moved there is nothing to lose: the game is dropped.
|
||||
fn play_started(&self) -> bool {
|
||||
self.played().len() >= 2
|
||||
|
|
@ -2765,6 +2836,7 @@ impl GameView {
|
|||
c.take_back(user, moved, std::time::Instant::now());
|
||||
}
|
||||
}
|
||||
self.keep_journal();
|
||||
self.ask_maia();
|
||||
}
|
||||
|
||||
|
|
@ -2881,10 +2953,22 @@ impl GameView {
|
|||
egui::Modal::new(egui::Id::new("play_leave")).show(ctx, |ui| {
|
||||
ui.set_width(460.0);
|
||||
ui.heading(tr("The game is on"));
|
||||
ui.label(tr("If you leave, the game ends with your resignation."));
|
||||
// A game written by itself needs no «add»: where it goes is said instead.
|
||||
let target = self
|
||||
.play
|
||||
.as_ref()
|
||||
.and_then(|s| s.journal.as_ref())
|
||||
.map(|j| crate::own_db::base_name(j.target()));
|
||||
match &target {
|
||||
Some(db) => ui.label(trf(
|
||||
"If you leave, the game ends with your resignation and is written to «{db}».",
|
||||
&[("db", db)],
|
||||
)),
|
||||
None => ui.label(tr("If you leave, the game ends with your resignation.")),
|
||||
};
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui.button(tr("Resign and add to a database…")).clicked() {
|
||||
if target.is_none() && ui.button(tr("Resign and add to a database…")).clicked() {
|
||||
choice = Some(0);
|
||||
}
|
||||
if ui.button(tr("Resign and leave")).clicked() {
|
||||
|
|
@ -2916,7 +3000,8 @@ impl GameView {
|
|||
self.resign_if_playing();
|
||||
actions.push(GameAction::SaveAndLeave(intent));
|
||||
}
|
||||
// Leaving was the answer: no second question about saving.
|
||||
// Leaving was the answer: no second question about saving (a game written
|
||||
// by itself is in its database already).
|
||||
1 => {
|
||||
self.resign_if_playing();
|
||||
self.game.mark_saved();
|
||||
|
|
@ -3293,15 +3378,51 @@ impl GameView {
|
|||
.weak(),
|
||||
);
|
||||
}
|
||||
// Where the game went by itself (player-games.md §4); a write that failed
|
||||
// is said, and «Save to a database…» stays for it.
|
||||
match &self.recorded {
|
||||
Some(Ok(w)) => {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 4.0;
|
||||
// The database's name is under the title already: here only
|
||||
// the number, the name on hover.
|
||||
let db = crate::own_db::base_name(&w.path);
|
||||
ui.label(
|
||||
RichText::new(trf(
|
||||
"✔ Written to the database, No. {n}",
|
||||
&[("n", &(w.index + 1))],
|
||||
))
|
||||
.weak(),
|
||||
)
|
||||
.on_hover_text(&db);
|
||||
if ui
|
||||
.link(tr("Open"))
|
||||
.on_hover_text(tr(
|
||||
"The database in the library, this game selected",
|
||||
))
|
||||
.clicked()
|
||||
{
|
||||
actions.push(GameAction::OpenDatabase(w.path.clone()));
|
||||
}
|
||||
});
|
||||
}
|
||||
Some(Err(e)) => {
|
||||
ui.label(RichText::new(e).color(ui.visuals().error_fg_color));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
// All four in a row when they fit; else Analyse, then Rematch and New
|
||||
// game side by side, then Save — each as wide as the strip.
|
||||
// All in a row when they fit; else Analyse, then Rematch and New game side
|
||||
// by side, then Save (when the game is not in a database) — each as wide
|
||||
// as the strip.
|
||||
let saved = matches!(self.recorded, Some(Ok(_)));
|
||||
let labels = [
|
||||
tr("📈 Analyse"),
|
||||
tr("↻ Rematch"),
|
||||
tr("♞ New game"),
|
||||
tr("💾 Save to a database…"),
|
||||
];
|
||||
let labels = &labels[..if saved { 3 } else { 4 }];
|
||||
let font = egui::FontId::proportional(14.0);
|
||||
let pad = 2.0 * ui.spacing().button_padding.x + ui.spacing().item_spacing.x;
|
||||
let one_row: f32 = labels
|
||||
|
|
@ -3340,7 +3461,7 @@ impl GameView {
|
|||
};
|
||||
if fits {
|
||||
ui.horizontal(|ui| {
|
||||
for k in 0..4 {
|
||||
for k in 0..labels.len() {
|
||||
button(ui, k, 0.0);
|
||||
}
|
||||
});
|
||||
|
|
@ -3352,7 +3473,9 @@ impl GameView {
|
|||
button(ui, 1, half);
|
||||
button(ui, 2, half);
|
||||
});
|
||||
button(ui, 3, full);
|
||||
if !saved {
|
||||
button(ui, 3, full);
|
||||
}
|
||||
}
|
||||
if clicked[0] {
|
||||
self.review_asked = true;
|
||||
|
|
|
|||
|
|
@ -11565,6 +11565,193 @@ const ROWS: &[[&str; 9]] = &[
|
|||
"Bu uslubda Rodent V {min} dan {max} gacha o‘ynaydi: kuch {elo}.",
|
||||
"Бұл стильде Rodent V {min} бастап {max} дейін ойнайды: күш {elo}.",
|
||||
],
|
||||
[
|
||||
"Games against the computer",
|
||||
"Партии с компьютером",
|
||||
"Parties contre l’ordinateur",
|
||||
"Partien gegen den Computer",
|
||||
"Partidas contra el ordenador",
|
||||
"Partite contro il computer",
|
||||
"Partidas contra o computador",
|
||||
"Kompyuter bilan o‘yinlar",
|
||||
"Компьютермен ойындар",
|
||||
],
|
||||
[
|
||||
"{name} — games against the computer",
|
||||
"{name} — партии с компьютером",
|
||||
"{name} — parties contre l’ordinateur",
|
||||
"{name} — Partien gegen den Computer",
|
||||
"{name} — partidas contra el ordenador",
|
||||
"{name} — partite contro il computer",
|
||||
"{name} — partidas contra o computador",
|
||||
"{name} — kompyuter bilan o‘yinlar",
|
||||
"{name} — компьютермен ойындар",
|
||||
],
|
||||
[
|
||||
"Could not write to «{db}»: {reason}",
|
||||
"Не удалось записать в «{db}»: {reason}",
|
||||
"Impossible d’écrire dans « {db} » : {reason}",
|
||||
"Konnte nicht in „{db}“ schreiben: {reason}",
|
||||
"No se pudo escribir en «{db}»: {reason}",
|
||||
"Impossibile scrivere in «{db}»: {reason}",
|
||||
"Não foi possível gravar em «{db}»: {reason}",
|
||||
"«{db}» ga yozib bo‘lmadi: {reason}",
|
||||
"«{db}» базасына жазу мүмкін болмады: {reason}",
|
||||
],
|
||||
[
|
||||
"Database «{db}» created: your games will be written there",
|
||||
"Создана база «{db}» — сюда будут записываться ваши партии",
|
||||
"Base « {db} » créée : vos parties y seront enregistrées",
|
||||
"Datenbank „{db}“ angelegt: Ihre Partien werden dort gespeichert",
|
||||
"Se creó la base «{db}»: tus partidas se guardarán allí",
|
||||
"Creato il database «{db}»: le tue partite saranno salvate lì",
|
||||
"Base «{db}» criada: as suas partidas serão gravadas nela",
|
||||
"«{db}» bazasi yaratildi: o‘yinlaringiz shu yerga yoziladi",
|
||||
"«{db}» базасы құрылды: ойындарыңыз осында жазылады",
|
||||
],
|
||||
[
|
||||
"The database in the library, this game selected",
|
||||
"База в библиотеке, эта партия выделена",
|
||||
"La base dans la bibliothèque, cette partie sélectionnée",
|
||||
"Die Datenbank in der Bibliothek, diese Partie ausgewählt",
|
||||
"La base en la biblioteca, con esta partida seleccionada",
|
||||
"Il database nella libreria, con questa partita selezionata",
|
||||
"A base na biblioteca, com esta partida selecionada",
|
||||
"Kutubxonadagi baza, bu o‘yin belgilangan",
|
||||
"Кітапханадағы база, бұл ойын белгіленген",
|
||||
],
|
||||
[
|
||||
"If you leave, the game ends with your resignation and is written to «{db}».",
|
||||
"Если выйти, партия закончится вашей сдачей и запишется в «{db}».",
|
||||
"Si vous partez, la partie se termine par votre abandon et est enregistrée dans « {db} ».",
|
||||
"Wenn Sie gehen, endet die Partie mit Ihrer Aufgabe und wird in „{db}“ gespeichert.",
|
||||
"Si sales, la partida termina con tu rendición y se guarda en «{db}».",
|
||||
"Se esci, la partita finisce con il tuo abbandono e viene salvata in «{db}».",
|
||||
"Se sair, a partida termina com a sua desistência e é gravada em «{db}».",
|
||||
"Chiqsangiz, o‘yin taslim bo‘lishingiz bilan tugaydi va «{db}» ga yoziladi.",
|
||||
"Шықсаңыз, ойын сіздің берілуіңізбен аяқталып, «{db}» базасына жазылады.",
|
||||
],
|
||||
[
|
||||
"Games against the computer are written here",
|
||||
"Сюда записываются партии с компьютером",
|
||||
"Les parties contre l’ordinateur sont enregistrées ici",
|
||||
"Partien gegen den Computer werden hier gespeichert",
|
||||
"Aquí se guardan las partidas contra el ordenador",
|
||||
"Qui vengono salvate le partite contro il computer",
|
||||
"Aqui são gravadas as partidas contra o computador",
|
||||
"Kompyuter bilan o‘yinlar shu yerga yoziladi",
|
||||
"Компьютермен ойындар осында жазылады",
|
||||
],
|
||||
[
|
||||
"{name}'s games against the computer are written here",
|
||||
"Сюда записываются партии игрока {name} с компьютером",
|
||||
"Les parties de {name} contre l’ordinateur sont enregistrées ici",
|
||||
"Die Partien von {name} gegen den Computer werden hier gespeichert",
|
||||
"Aquí se guardan las partidas de {name} contra el ordenador",
|
||||
"Qui vengono salvate le partite di {name} contro il computer",
|
||||
"Aqui são gravadas as partidas de {name} contra o computador",
|
||||
"{name} ning kompyuter bilan o‘yinlari shu yerga yoziladi",
|
||||
"{name} ойыншысының компьютермен ойындары осында жазылады",
|
||||
],
|
||||
[
|
||||
"Write games against the computer to the player's database",
|
||||
"Записывать партии с компьютером в базу игрока",
|
||||
"Enregistrer les parties contre l’ordinateur dans la base du joueur",
|
||||
"Partien gegen den Computer in die Datenbank des Spielers schreiben",
|
||||
"Guardar las partidas contra el ordenador en la base del jugador",
|
||||
"Salvare le partite contro il computer nel database del giocatore",
|
||||
"Gravar as partidas contra o computador na base do jogador",
|
||||
"Kompyuter bilan o‘yinlarni o‘yinchi bazasiga yozish",
|
||||
"Компьютермен ойындарды ойыншы базасына жазу",
|
||||
],
|
||||
[
|
||||
"Games are not written by themselves (Settings → Interface → Your databases).",
|
||||
"Партии сами не записываются (Настройки → Интерфейс → Свои базы).",
|
||||
"Les parties ne sont pas enregistrées d’elles-mêmes (Réglages → Interface → Vos bases).",
|
||||
"Partien werden nicht von selbst gespeichert (Einstellungen → Oberfläche → Eigene Datenbanken).",
|
||||
"Las partidas no se guardan solas (Ajustes → Interfaz → Tus bases).",
|
||||
"Le partite non vengono salvate da sole (Impostazioni → Interfaccia → I tuoi database).",
|
||||
"As partidas não são gravadas sozinhas (Definições → Interface → As suas bases).",
|
||||
"O‘yinlar o‘zi yozilmaydi (Sozlamalar → Interfeys → Sizning bazalaringiz).",
|
||||
"Ойындар өзі жазылмайды (Баптаулар → Интерфейс → Өз базаларыңыз).",
|
||||
],
|
||||
[
|
||||
"Without a name games go to «{db}». Enter a name to have a database of your own.",
|
||||
"Без имени партии идут в «{db}». Впишите имя — заведём вашу базу.",
|
||||
"Sans nom, les parties vont dans « {db} ». Saisissez un nom pour avoir votre propre base.",
|
||||
"Ohne Namen gehen die Partien in „{db}“. Geben Sie einen Namen ein, um eine eigene Datenbank zu bekommen.",
|
||||
"Sin nombre, las partidas van a «{db}». Escribe un nombre para tener tu propia base.",
|
||||
"Senza nome le partite vanno in «{db}». Inserisci un nome per avere un database tuo.",
|
||||
"Sem nome, as partidas vão para «{db}». Escreva um nome para ter a sua própria base.",
|
||||
"Ismsiz o‘yinlar «{db}» ga tushadi. O‘z bazangiz bo‘lishi uchun ismingizni yozing.",
|
||||
"Атсыз ойындар «{db}» базасына түседі. Өз базаңыз болуы үшін атыңызды жазыңыз.",
|
||||
],
|
||||
[
|
||||
"Games will be written to a new database «{db}».",
|
||||
"Партии будут записываться в новую базу «{db}».",
|
||||
"Les parties seront enregistrées dans une nouvelle base « {db} ».",
|
||||
"Die Partien werden in eine neue Datenbank „{db}“ gespeichert.",
|
||||
"Las partidas se guardarán en una base nueva «{db}».",
|
||||
"Le partite saranno salvate in un nuovo database «{db}».",
|
||||
"As partidas serão gravadas numa nova base «{db}».",
|
||||
"O‘yinlar yangi «{db}» bazasiga yoziladi.",
|
||||
"Ойындар жаңа «{db}» базасына жазылады.",
|
||||
],
|
||||
[
|
||||
"Games are written to «{db}» · {n}",
|
||||
"Партии записываются в «{db}» · {n}",
|
||||
"Les parties sont enregistrées dans « {db} » · {n}",
|
||||
"Partien werden in „{db}“ gespeichert · {n}",
|
||||
"Las partidas se guardan en «{db}» · {n}",
|
||||
"Le partite vengono salvate in «{db}» · {n}",
|
||||
"As partidas são gravadas em «{db}» · {n}",
|
||||
"O‘yinlar «{db}» ga yoziladi · {n}",
|
||||
"Ойындар «{db}» базасына жазылады · {n}",
|
||||
],
|
||||
[
|
||||
"Games are written to «{db}»",
|
||||
"Партии записываются в «{db}»",
|
||||
"Les parties sont enregistrées dans « {db} »",
|
||||
"Partien werden in „{db}“ gespeichert",
|
||||
"Las partidas se guardan en «{db}»",
|
||||
"Le partite vengono salvate in «{db}»",
|
||||
"As partidas são gravadas em «{db}»",
|
||||
"O‘yinlar «{db}» ga yoziladi",
|
||||
"Ойындар «{db}» базасына жазылады",
|
||||
],
|
||||
[
|
||||
"✔ Written to the database, No. {n}",
|
||||
"✔ Записано в базу, № {n}",
|
||||
"✔ Enregistrée dans la base, n° {n}",
|
||||
"✔ In der Datenbank gespeichert, Nr. {n}",
|
||||
"✔ Guardada en la base, n.º {n}",
|
||||
"✔ Salvata nel database, n. {n}",
|
||||
"✔ Gravada na base, n.º {n}",
|
||||
"✔ Bazaga yozildi, № {n}",
|
||||
"✔ Базаға жазылды, № {n}",
|
||||
],
|
||||
[
|
||||
"Players of this computer (↓ in the name field)",
|
||||
"Игроки на этом компьютере (↓ в поле имени)",
|
||||
"Joueurs de cet ordinateur (↓ dans le champ du nom)",
|
||||
"Spieler an diesem Computer (↓ im Namensfeld)",
|
||||
"Jugadores de este ordenador (↓ en el campo del nombre)",
|
||||
"Giocatori di questo computer (↓ nel campo del nome)",
|
||||
"Jogadores deste computador (↓ no campo do nome)",
|
||||
"Bu kompyuterdagi o‘yinchilar (ism maydonida ↓)",
|
||||
"Осы компьютердегі ойыншылар (аты өрісінде ↓)",
|
||||
],
|
||||
[
|
||||
"An unfinished game (the program closed) is written to «{db}», No. {n}",
|
||||
"Недоигранная партия (программа закрылась) записана в «{db}», № {n}",
|
||||
"Une partie inachevée (le programme s’est fermé) est enregistrée dans « {db} », n° {n}",
|
||||
"Eine unvollendete Partie (das Programm wurde beendet) ist in „{db}“ gespeichert, Nr. {n}",
|
||||
"Una partida sin terminar (el programa se cerró) se guardó en «{db}», n.º {n}",
|
||||
"Una partita non finita (il programma si è chiuso) è salvata in «{db}», n. {n}",
|
||||
"Uma partida inacabada (o programa fechou) foi gravada em «{db}», n.º {n}",
|
||||
"Tugallanmagan o‘yin (dastur yopildi) «{db}» ga yozildi, № {n}",
|
||||
"Аяқталмаған ойын (бағдарлама жабылды) «{db}» базасына жазылды, № {n}",
|
||||
],
|
||||
[
|
||||
"Maia resigned",
|
||||
"Maia сдалась",
|
||||
|
|
|
|||
|
|
@ -175,6 +175,8 @@ const SEARCH_BOARD_MIN: f32 = 340.0;
|
|||
|
||||
pub struct Library {
|
||||
slots: HashMap<PathBuf, Slot>,
|
||||
/// The players' databases (player_games.rs) and whose: a knight on their cards.
|
||||
player_dbs: Vec<(PathBuf, String)>,
|
||||
/// Games the user has opened (by content).
|
||||
viewed: Viewed,
|
||||
/// Filters, quick search, position and game list of each database (for the session).
|
||||
|
|
@ -201,6 +203,7 @@ impl Library {
|
|||
pub fn new() -> Self {
|
||||
Self {
|
||||
slots: HashMap::new(),
|
||||
player_dbs: Vec::new(),
|
||||
viewed: Viewed::load(),
|
||||
large: HashMap::new(),
|
||||
pending_position: None,
|
||||
|
|
@ -470,6 +473,11 @@ impl Library {
|
|||
settings: &Settings,
|
||||
) -> Vec<LibraryAction> {
|
||||
self.poll();
|
||||
self.player_dbs = settings
|
||||
.players
|
||||
.iter()
|
||||
.filter_map(|p| Some((p.path.clone()?, p.name.clone())))
|
||||
.collect();
|
||||
let mut actions = Vec::new();
|
||||
// A field had the keyboard when this frame began: its Escape is its own.
|
||||
let typing = ui.ctx().egui_wants_keyboard_input();
|
||||
|
|
@ -654,8 +662,12 @@ impl Library {
|
|||
ui.horizontal(|ui| {
|
||||
let current = self.selected_db.as_deref().map(name).unwrap_or_default();
|
||||
let mut pick = None;
|
||||
let icon = match self.selected_db.as_deref() {
|
||||
Some(p) if self.player_dbs.iter().any(|(q, _)| q == p) => "♞",
|
||||
_ => "🗄",
|
||||
};
|
||||
egui::ComboBox::from_id_salt("shelf_db")
|
||||
.selected_text(format!("🗄 {current}"))
|
||||
.selected_text(format!("{icon} {current}"))
|
||||
.width(list)
|
||||
.truncate()
|
||||
.show_ui(ui, |ui| {
|
||||
|
|
@ -950,6 +962,11 @@ impl Library {
|
|||
}
|
||||
|
||||
fn db_card(&mut self, ui: &mut Ui, path: &Path, actions: &mut Vec<LibraryAction>) {
|
||||
let player = self
|
||||
.player_dbs
|
||||
.iter()
|
||||
.find(|(p, _)| p == path)
|
||||
.map(|(_, n)| n.clone());
|
||||
let selected = self.selected_db.as_deref() == Some(path);
|
||||
let name = path
|
||||
.file_stem()
|
||||
|
|
@ -998,6 +1015,8 @@ impl Library {
|
|||
egui::Align2::LEFT_TOP,
|
||||
if crate::online::is_online(path) {
|
||||
"🌐"
|
||||
} else if player.is_some() {
|
||||
"♞"
|
||||
} else {
|
||||
"🗄"
|
||||
},
|
||||
|
|
@ -1024,7 +1043,20 @@ impl Library {
|
|||
egui::FontId::proportional(12.0),
|
||||
v.weak_text_color(),
|
||||
);
|
||||
let resp = resp.on_hover_text(path.display().to_string());
|
||||
let resp = match &player {
|
||||
Some(name) => {
|
||||
let whose = if name.is_empty() {
|
||||
tr("Games against the computer are written here").to_owned()
|
||||
} else {
|
||||
trf(
|
||||
"{name}'s games against the computer are written here",
|
||||
&[("name", name)],
|
||||
)
|
||||
};
|
||||
resp.on_hover_text(format!("{whose}\n{}", path.display()))
|
||||
}
|
||||
None => resp.on_hover_text(path.display().to_string()),
|
||||
};
|
||||
if resp.clicked() {
|
||||
self.select_db(path, ui.ctx());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ mod online;
|
|||
mod online_ui;
|
||||
mod own_db;
|
||||
mod play;
|
||||
mod player_games;
|
||||
mod reference;
|
||||
mod review;
|
||||
mod rodent_download;
|
||||
|
|
|
|||
|
|
@ -69,7 +69,7 @@ pub fn base_name(path: &Path) -> String {
|
|||
}
|
||||
|
||||
/// Characters a file name cannot have (on any of the three systems).
|
||||
const FORBIDDEN: &[char] = &['/', '\\', ':', '*', '?', '"', '<', '>', '|'];
|
||||
pub const FORBIDDEN: &[char] = &['/', '\\', ':', '*', '?', '"', '<', '>', '|'];
|
||||
|
||||
// --- New database ------------------------------------------------------------------------
|
||||
|
||||
|
|
|
|||
|
|
@ -822,6 +822,8 @@ mod tests {
|
|||
|
||||
/// A game against Maia in progress (lives in the game screen while it is played).
|
||||
pub struct Session {
|
||||
/// The game kept for the player's database (none: not written by itself).
|
||||
pub journal: Option<crate::player_games::Journal>,
|
||||
pub user: Color,
|
||||
/// The opponent's strength (Lichess blitz scale), what plays it and in which style.
|
||||
pub strength: u32,
|
||||
|
|
@ -1073,6 +1075,10 @@ pub struct Dialog {
|
|||
/// rematch).
|
||||
keep_color: bool,
|
||||
focus: bool,
|
||||
/// The number of games of the players' databases read so far (the app fills it).
|
||||
pub counts: std::collections::HashMap<std::path::PathBuf, usize>,
|
||||
/// Where the games of the name typed go: for that name (found once per name).
|
||||
target: Option<(String, std::path::PathBuf)>,
|
||||
}
|
||||
|
||||
pub enum DialogOutcome {
|
||||
|
|
@ -1116,6 +1122,8 @@ impl Dialog {
|
|||
focus: true,
|
||||
from: None,
|
||||
keep_color: false,
|
||||
counts: Default::default(),
|
||||
target: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1151,6 +1159,49 @@ impl Dialog {
|
|||
d
|
||||
}
|
||||
|
||||
/// Where the games of the name typed go (player-games.md §3): said before the game.
|
||||
fn record_line(&mut self, settings: &crate::settings::Settings) -> String {
|
||||
use crate::i18n::trf;
|
||||
if !settings.record_games {
|
||||
return tr(
|
||||
"Games are not written by themselves (Settings → Interface → Your databases).",
|
||||
)
|
||||
.to_owned();
|
||||
}
|
||||
let name = crate::player_games::tidy(&self.name);
|
||||
if self.target.as_ref().is_none_or(|(n, _)| *n != name) {
|
||||
let dir = crate::own_db::default_base_dir(settings.new_database_dir.as_deref());
|
||||
let path = crate::player_games::target(&settings.players, &name, &dir);
|
||||
self.target = Some((name.clone(), path));
|
||||
}
|
||||
let path = &self.target.as_ref().expect("target").1;
|
||||
let db = crate::own_db::base_name(path);
|
||||
if name.is_empty() {
|
||||
return trf(
|
||||
"Without a name games go to «{db}». Enter a name to have a database of your own.",
|
||||
&[("db", &db)],
|
||||
);
|
||||
}
|
||||
if !path.exists() {
|
||||
return trf(
|
||||
"Games will be written to a new database «{db}».",
|
||||
&[("db", &db)],
|
||||
);
|
||||
}
|
||||
match self.counts.get(path) {
|
||||
Some(&n) => trf(
|
||||
"Games are written to «{db}» · {n}",
|
||||
&[("db", &db), ("n", &crate::i18n::games(n))],
|
||||
),
|
||||
None => trf("Games are written to «{db}»", &[("db", &db)]),
|
||||
}
|
||||
}
|
||||
|
||||
/// The database the games of the name typed go to.
|
||||
pub fn record_target(&self) -> Option<&std::path::Path> {
|
||||
self.target.as_ref().map(|(_, p)| p.as_path())
|
||||
}
|
||||
|
||||
fn rating(&self) -> Option<u32> {
|
||||
self.rating
|
||||
.trim()
|
||||
|
|
@ -1213,12 +1264,80 @@ impl Dialog {
|
|||
.spacing(egui::vec2(8.0, GAP))
|
||||
.show(ui, |ui| {
|
||||
ui.label(tr("Name:"));
|
||||
let r = ui.add(
|
||||
egui::TextEdit::singleline(&mut self.name).desired_width(f32::INFINITY),
|
||||
);
|
||||
if std::mem::take(&mut self.focus) && self.name.is_empty() {
|
||||
r.request_focus();
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
// The players of this computer, for a family (each their database
|
||||
// and rating).
|
||||
let known: Vec<_> = settings
|
||||
.players
|
||||
.iter()
|
||||
.filter(|p| !p.name.is_empty())
|
||||
.cloned()
|
||||
.collect();
|
||||
let menu_w = if known.is_empty() { 0.0 } else { 34.0 };
|
||||
let r = ui.add(
|
||||
egui::TextEdit::singleline(&mut self.name)
|
||||
.desired_width(ui.available_width() - menu_w),
|
||||
);
|
||||
if std::mem::take(&mut self.focus) && self.name.is_empty() {
|
||||
r.request_focus();
|
||||
}
|
||||
let mut pick = None;
|
||||
// ↓ / ↑ in the field go through the players.
|
||||
if r.has_focus() && !known.is_empty() {
|
||||
let step = ui.input_mut(|i| {
|
||||
if i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown) {
|
||||
1
|
||||
} else if i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp) {
|
||||
-1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
});
|
||||
if step != 0 {
|
||||
let n = known.len() as i32;
|
||||
let now = crate::player_games::tidy(&self.name).to_lowercase();
|
||||
let at = known
|
||||
.iter()
|
||||
.position(|p| p.name.to_lowercase() == now)
|
||||
.map_or(if step > 0 { -1 } else { n }, |k| k as i32);
|
||||
pick = Some(known[(at + step).rem_euclid(n) as usize].clone());
|
||||
}
|
||||
}
|
||||
if !known.is_empty() {
|
||||
let size = egui::vec2(menu_w - ui.spacing().item_spacing.x, r.rect.height());
|
||||
let (resp, _) = egui::containers::menu::MenuButton::from_button(
|
||||
egui::Button::new("▾").min_size(size),
|
||||
)
|
||||
.ui(ui, |ui| {
|
||||
for p in &known {
|
||||
let mut label = p.name.clone();
|
||||
if let Some(r) = p.rating {
|
||||
label += &format!(" · {r}");
|
||||
}
|
||||
if let Some(n) = p.path.as_ref().and_then(|q| self.counts.get(q)) {
|
||||
label += &format!(" · {}", crate::i18n::games(*n));
|
||||
}
|
||||
if ui.button(label).clicked() {
|
||||
pick = Some(p.clone());
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
resp.on_hover_text(tr("Players of this computer (↓ in the name field)"));
|
||||
}
|
||||
if let Some(p) = pick {
|
||||
self.name = p.name.clone();
|
||||
self.rating = p.rating.map(|r| r.to_string()).unwrap_or_default();
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label("");
|
||||
// As wide as the field: the line wraps, the dialog keeps its width.
|
||||
let line = self.record_line(settings);
|
||||
ui.scope(|ui| {
|
||||
ui.set_max_width(W - 80.0);
|
||||
ui.add(egui::Label::new(RichText::new(line).weak().size(12.5)).wrap());
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tr("Rating:"));
|
||||
ui.horizontal(|ui| {
|
||||
|
|
@ -1687,6 +1806,9 @@ impl Dialog {
|
|||
};
|
||||
settings.your_name = self.name.trim().to_owned();
|
||||
settings.rating = rating;
|
||||
if !self.name.trim().is_empty() {
|
||||
crate::player_games::remember(&mut settings.players, &self.name, rating);
|
||||
}
|
||||
// From a position the colour is the side to move's, not a habit.
|
||||
let color = settings.play.color;
|
||||
settings.play = self.prefs.clone();
|
||||
|
|
|
|||
412
apps/desktop/src/player_games.rs
Normal file
412
apps/desktop/src/player_games.rs
Normal file
|
|
@ -0,0 +1,412 @@
|
|||
//! The player's games (docs/design/player-games.md, decisions «Партии игрока
|
||||
//! записываются сами»): every game against the computer goes by itself into a database
|
||||
//! of its player — «Roman — games against the computer», made by the program in the
|
||||
//! folder of new databases at its first game. Only new records are appended; replacing
|
||||
//! and deleting stay explicit. While a game is played it is kept in a journal after
|
||||
//! every move, so that a crash loses nothing: the next start writes it (result `*`).
|
||||
|
||||
use std::fs::File;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::i18n::{tr, trf};
|
||||
|
||||
/// A player of this computer: the name as entered, the rating, the database.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Player {
|
||||
pub name: String,
|
||||
pub rating: Option<u32>,
|
||||
/// Their database, once a game was written (renaming it in the program keeps the
|
||||
/// link).
|
||||
pub path: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// The name as it is kept: trimmed, inner spaces single.
|
||||
pub fn tidy(name: &str) -> String {
|
||||
name.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// Names that are the same player: «Иван» and «иван ».
|
||||
fn same(a: &str, b: &str) -> bool {
|
||||
tidy(a).to_lowercase() == tidy(b).to_lowercase()
|
||||
}
|
||||
|
||||
/// The player of this name, if they played before.
|
||||
pub fn player<'a>(players: &'a [Player], name: &str) -> Option<&'a Player> {
|
||||
players.iter().find(|p| same(&p.name, name))
|
||||
}
|
||||
|
||||
/// Remembers the player who starts a game (first in the list) and their rating.
|
||||
pub fn remember(players: &mut Vec<Player>, name: &str, rating: Option<u32>) {
|
||||
let mut p = match players.iter().position(|p| same(&p.name, name)) {
|
||||
Some(i) => players.remove(i),
|
||||
None => Player::default(),
|
||||
};
|
||||
p.name = tidy(name);
|
||||
p.rating = rating;
|
||||
players.insert(0, p);
|
||||
}
|
||||
|
||||
/// Links the player to the database their game was written to.
|
||||
pub fn link(players: &mut Vec<Player>, name: &str, path: &Path) {
|
||||
match players.iter_mut().find(|p| same(&p.name, name)) {
|
||||
Some(p) => p.path = Some(path.to_owned()),
|
||||
None => players.push(Player {
|
||||
name: tidy(name),
|
||||
rating: None,
|
||||
path: Some(path.to_owned()),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The database's name: «Roman — games against the computer»; without a name, one for
|
||||
/// everybody. The name is not declined (in Russian it could not be done safely).
|
||||
pub fn db_name(name: &str) -> String {
|
||||
let name = tidy(name);
|
||||
if name.is_empty() {
|
||||
tr("Games against the computer").to_owned()
|
||||
} else {
|
||||
trf("{name} — games against the computer", &[("name", &name)])
|
||||
}
|
||||
}
|
||||
|
||||
/// The longest player's name a file name takes, in characters.
|
||||
const NAME_CHARS: usize = 40;
|
||||
|
||||
/// The longest file name, in bytes, with room for « 2.pgn» (file systems take 255).
|
||||
const STEM_BYTES: usize = 114;
|
||||
|
||||
/// The file name for a database name: what a file name cannot have becomes «_», the
|
||||
/// player's part is cut to [`NAME_CHARS`] (and to [`STEM_BYTES`] for the whole), no dot,
|
||||
/// space or hyphen left at the cut, none of the first two at the end (Windows).
|
||||
fn file_stem(player: &str, db: &str) -> String {
|
||||
let player = tidy(player);
|
||||
let mut chars: Vec<char> = player.chars().take(NAME_CHARS).collect();
|
||||
let rest = db.len() - player.len();
|
||||
while !chars.is_empty() && rest + chars.iter().map(|c| c.len_utf8()).sum::<usize>() > STEM_BYTES
|
||||
{
|
||||
chars.pop();
|
||||
}
|
||||
let mut cut: String = chars.into_iter().collect();
|
||||
if cut.len() < player.len() {
|
||||
cut = cut.trim_end_matches(['.', ' ', '-']).to_owned();
|
||||
}
|
||||
let db = if cut.len() < player.len() {
|
||||
db.replacen(&player, &cut, 1)
|
||||
} else {
|
||||
db.to_owned()
|
||||
};
|
||||
let clean: String = db
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if crate::own_db::FORBIDDEN.contains(&c) || c.is_control() {
|
||||
'_'
|
||||
} else {
|
||||
c
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
clean.trim_end_matches(['.', ' ']).to_owned()
|
||||
}
|
||||
|
||||
/// Where the player's games go: their database, else a new one in `dir`. A file of
|
||||
/// that name made otherwise is taken when it is a PGN in UTF-8 (appending keeps its
|
||||
/// bytes: a database brought from another computer goes on), else «… 2».
|
||||
pub fn target(players: &[Player], name: &str, dir: &Path) -> PathBuf {
|
||||
if let Some(path) = player(players, name).and_then(|p| p.path.clone()) {
|
||||
return path;
|
||||
}
|
||||
let stem = file_stem(name, &db_name(name));
|
||||
let taken =
|
||||
|p: &Path| p.exists() && !std::fs::read(p).is_ok_and(|b| std::str::from_utf8(&b).is_ok());
|
||||
let mut path = dir.join(format!("{stem}.pgn"));
|
||||
let mut n = 2;
|
||||
while taken(&path) {
|
||||
path = dir.join(format!("{stem} {n}.pgn"));
|
||||
n += 1;
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
/// A game written: its record and whether the database was made for it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Written {
|
||||
pub path: PathBuf,
|
||||
pub index: usize,
|
||||
pub created: bool,
|
||||
}
|
||||
|
||||
/// Appends `pgn` to the database at `path`, making it (and its folder) when absent.
|
||||
pub fn write(path: &Path, pgn: &str) -> Result<Written, String> {
|
||||
let created = !path.exists();
|
||||
if created {
|
||||
path.parent()
|
||||
.map(std::fs::create_dir_all)
|
||||
.unwrap_or(Ok(()))
|
||||
.and_then(|()| File::create_new(path))
|
||||
.and_then(|f| f.sync_all())
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
let db = chess_core::PgnDatabase::open(path, &mut |_| {}, &AtomicBool::new(false))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let index = db.len();
|
||||
chess_core::pgn::store::append(&db, pgn).map_err(|e| e.to_string())?;
|
||||
Ok(Written {
|
||||
path: path.to_owned(),
|
||||
index,
|
||||
created,
|
||||
})
|
||||
}
|
||||
|
||||
/// What the journal keeps of a game being played.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Entry {
|
||||
target: PathBuf,
|
||||
/// Whose game it is: the player is linked to the database when it is written.
|
||||
#[serde(default)]
|
||||
player: String,
|
||||
pgn: String,
|
||||
/// The database's size before the game was appended: set just before the write, so
|
||||
/// that a crash right after it does not write the game twice.
|
||||
before: Option<u64>,
|
||||
}
|
||||
|
||||
/// The folder of the journals.
|
||||
fn journal_dir() -> Option<PathBuf> {
|
||||
directories::ProjectDirs::from("", "", "chesspenguin").map(|d| d.data_local_dir().join("play"))
|
||||
}
|
||||
|
||||
/// The journal of the game being played: a file rewritten after each move, and a lock
|
||||
/// held while the program runs (a journal whose lock is free is one a crash left).
|
||||
pub struct Journal {
|
||||
lock: Option<(File, PathBuf)>,
|
||||
path: PathBuf,
|
||||
target: PathBuf,
|
||||
player: String,
|
||||
}
|
||||
|
||||
impl Journal {
|
||||
/// A journal for a game going to `target` (none when the folder cannot be made: the
|
||||
/// game is still written at its end).
|
||||
pub fn new(target: PathBuf, player: &str) -> Self {
|
||||
Self::in_dir(journal_dir(), target, player)
|
||||
}
|
||||
|
||||
fn in_dir(dir: Option<PathBuf>, target: PathBuf, player: &str) -> Self {
|
||||
let made = dir.and_then(|dir| {
|
||||
std::fs::create_dir_all(&dir).ok()?;
|
||||
let stamp = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_nanos());
|
||||
let stem = format!("game-{}-{stamp}", std::process::id());
|
||||
let lock_path = dir.join(format!("{stem}.lock"));
|
||||
let lock = File::create(&lock_path).ok()?;
|
||||
lock.try_lock().ok()?;
|
||||
Some(((lock, lock_path), dir.join(format!("{stem}.json"))))
|
||||
});
|
||||
let (lock, path) = match made {
|
||||
Some((lock, path)) => (Some(lock), path),
|
||||
None => (None, PathBuf::new()),
|
||||
};
|
||||
Self {
|
||||
lock,
|
||||
path,
|
||||
target,
|
||||
player: tidy(player),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn target(&self) -> &Path {
|
||||
&self.target
|
||||
}
|
||||
|
||||
fn put(&self, pgn: &str, before: Option<u64>) {
|
||||
if self.lock.is_none() {
|
||||
return;
|
||||
}
|
||||
let entry = Entry {
|
||||
target: self.target.clone(),
|
||||
player: self.player.clone(),
|
||||
pgn: pgn.to_owned(),
|
||||
before,
|
||||
};
|
||||
if let Ok(json) = serde_json::to_vec(&entry) {
|
||||
let _ = crate::settings::write_atomic(&self.path, &json);
|
||||
}
|
||||
}
|
||||
|
||||
/// The game as it is now (written as it would be if the program stopped here).
|
||||
pub fn save(&self, pgn: &str) {
|
||||
self.put(pgn, None);
|
||||
}
|
||||
|
||||
/// The game is over: written into its database. The journal stays until it is
|
||||
/// dropped: after a failed write a crash still leaves the game to the next start.
|
||||
pub fn finish(&self, pgn: &str) -> Result<Written, String> {
|
||||
let before = std::fs::metadata(&self.target).map_or(0, |m| m.len());
|
||||
self.put(pgn, Some(before));
|
||||
write(&self.target, pgn)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Journal {
|
||||
fn drop(&mut self) {
|
||||
if let Some((lock, lock_path)) = self.lock.take() {
|
||||
let _ = std::fs::remove_file(&self.path);
|
||||
drop(lock);
|
||||
let _ = std::fs::remove_file(lock_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A game a crash left: whose, where to, and what came of writing it.
|
||||
pub struct Recovered {
|
||||
pub player: String,
|
||||
pub target: PathBuf,
|
||||
pub written: Result<Written, String>,
|
||||
}
|
||||
|
||||
/// Games a crash left in journals (their program is gone: the lock is free) are written
|
||||
/// into their databases now.
|
||||
pub fn recover() -> Vec<Recovered> {
|
||||
journal_dir().map(|d| recover_in(&d)).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn recover_in(dir: &Path) -> Vec<Recovered> {
|
||||
let Ok(read) = std::fs::read_dir(dir) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for lock_path in read.flatten().map(|e| e.path()) {
|
||||
if lock_path.extension().is_none_or(|e| e != "lock") {
|
||||
continue;
|
||||
}
|
||||
let Ok(lock) = File::open(&lock_path) else {
|
||||
continue;
|
||||
};
|
||||
if lock.try_lock().is_err() {
|
||||
continue; // a program running now plays it
|
||||
}
|
||||
let path = lock_path.with_extension("json");
|
||||
if let Some(entry) = std::fs::read(&path)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<Entry>(&b).ok())
|
||||
{
|
||||
// The write had been made (the file grew since): not again.
|
||||
let done = entry
|
||||
.before
|
||||
.is_some_and(|b| std::fs::metadata(&entry.target).is_ok_and(|m| m.len() > b));
|
||||
if !done {
|
||||
out.push(Recovered {
|
||||
written: write(&entry.target, &entry.pgn),
|
||||
player: entry.player,
|
||||
target: entry.target,
|
||||
});
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
drop(lock);
|
||||
let _ = std::fs::remove_file(&lock_path);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn players_are_the_same_whatever_the_case_and_spaces() {
|
||||
let mut ps = Vec::new();
|
||||
remember(&mut ps, " Иван Петров ", Some(1500));
|
||||
remember(&mut ps, "Роман", None);
|
||||
remember(&mut ps, "иван петров", Some(1600));
|
||||
assert_eq!(ps.len(), 2);
|
||||
assert_eq!(ps[0].name, "иван петров");
|
||||
assert_eq!(ps[0].rating, Some(1600));
|
||||
link(&mut ps, "Роман", Path::new("/x/r.pgn"));
|
||||
assert_eq!(
|
||||
player(&ps, " роман").and_then(|p| p.path.clone()),
|
||||
Some(PathBuf::from("/x/r.pgn"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_names_have_no_forbidden_characters() {
|
||||
let stem = file_stem("A/B: C?", "A/B: C? — games");
|
||||
assert_eq!(stem, "A_B_ C_ — games");
|
||||
let long = "Я".repeat(60);
|
||||
let stem = file_stem(&long, &format!("{long} — games"));
|
||||
assert_eq!(stem, format!("{} — games", "Я".repeat(NAME_CHARS)));
|
||||
assert_eq!(file_stem("Dot.", "Dot."), "Dot");
|
||||
// Cut at a hyphen: none left at the cut; long letters: within the bytes.
|
||||
let name = format!("{}-Сидорова", "Ж".repeat(NAME_CHARS - 1));
|
||||
let stem = file_stem(&name, &format!("{name} — партии с компьютером"));
|
||||
assert!(!stem.contains("- —"), "{stem}");
|
||||
assert!(stem.len() <= STEM_BYTES, "{}", stem.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_database_takes_the_game_and_the_next_is_appended() {
|
||||
let dir = std::env::temp_dir().join(format!("cp-player-games-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let path = target(&[], "Тест", &dir.join("sub"));
|
||||
let game = "[Event \"?\"]\n[White \"Тест\"]\n[Black \"Maia 1500\"]\n[Result \"1-0\"]\n\n1. e4 e5 1-0\n";
|
||||
let w = write(&path, game).unwrap();
|
||||
assert!(w.created);
|
||||
assert_eq!(w.index, 0);
|
||||
let w = write(&path, game).unwrap();
|
||||
assert!(!w.created);
|
||||
assert_eq!(w.index, 1);
|
||||
// A file of the same name in another encoding is not written into.
|
||||
let bad = target(&[], "Bad", &dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(&bad, [0xff, 0xfe, 0x00]).unwrap();
|
||||
let other = target(&[], "Bad", &dir);
|
||||
assert_ne!(other, bad);
|
||||
assert!(other.to_string_lossy().ends_with(" 2.pgn"), "{other:?}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_game_left_by_a_crash_is_written_once() {
|
||||
let dir = std::env::temp_dir().join(format!("cp-journal-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let journals = dir.join("play");
|
||||
let db = dir.join("db.pgn");
|
||||
let game = "[Event \"?\"]\n[Result \"*\"]\n\n1. d4 d5 *\n";
|
||||
// Played, then the program stopped: the lock goes, the files stay.
|
||||
let j = Journal::in_dir(Some(journals.clone()), db.clone(), "Роман");
|
||||
j.save(game);
|
||||
let mut j = j;
|
||||
drop(j.lock.take());
|
||||
drop(j);
|
||||
// A game being played now (its lock held) is left alone.
|
||||
let live = Journal::in_dir(Some(journals.clone()), dir.join("live.pgn"), "");
|
||||
live.save(game);
|
||||
let got = recover_in(&journals);
|
||||
assert_eq!(got.len(), 1);
|
||||
assert_eq!(got[0].player, "Роман");
|
||||
assert_eq!(got[0].written.as_ref().map(|w| w.index), Ok(0));
|
||||
assert!(recover_in(&journals).is_empty());
|
||||
// Crashed right after the write: not written again.
|
||||
let j = Journal::in_dir(Some(journals.clone()), db.clone(), "Роман");
|
||||
let before = std::fs::metadata(&db).unwrap().len();
|
||||
j.put(game, Some(before));
|
||||
write(&db, game).unwrap();
|
||||
let mut j = j;
|
||||
drop(j.lock.take());
|
||||
drop(j);
|
||||
assert!(recover_in(&journals).is_empty());
|
||||
let n = chess_core::PgnDatabase::open(&db, &mut |_| {}, &AtomicBool::new(false))
|
||||
.unwrap()
|
||||
.len();
|
||||
assert_eq!(n, 2);
|
||||
drop(live);
|
||||
assert_eq!(std::fs::read_dir(&journals).unwrap().count(), 0);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
|
@ -145,6 +145,10 @@ pub struct Settings {
|
|||
pub rating: Option<u32>,
|
||||
/// The last choices of the play dialog.
|
||||
pub play: crate::play::PlayPrefs,
|
||||
/// Games against the computer go by themselves into the player's database.
|
||||
pub record_games: bool,
|
||||
/// Who played on this computer, the last first (`player_games.rs`).
|
||||
pub players: Vec<crate::player_games::Player>,
|
||||
}
|
||||
|
||||
/// Options of the whole-game analysis (the engine is the active one).
|
||||
|
|
@ -225,6 +229,8 @@ impl Default for Settings {
|
|||
your_name: String::new(),
|
||||
new_database_dir: None,
|
||||
last_target: None,
|
||||
record_games: true,
|
||||
players: Vec::new(),
|
||||
rating: None,
|
||||
play: Default::default(),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -189,6 +189,12 @@ impl SettingsWindow {
|
|||
actions.push(SettingsAction::PickBaseFolder);
|
||||
}
|
||||
});
|
||||
changed |= ui
|
||||
.checkbox(
|
||||
&mut s.record_games,
|
||||
tr("Write games against the computer to the player's database"),
|
||||
)
|
||||
.changed();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue