Desktop: a game against the computer can be put aside and continued
Some checks are pending
CI / macos-build (push) Waiting to run
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run

«⏸ Put aside» in the game, the main answer of «The game is on» and closing the
window put the game aside: its journal stays, with what it is played with and
the side to move's time. A card on the library's shelf (a strip in a folded
shelf) continues it with the clocks where they stopped; a crash leaves a game
put aside too (said once). A new game over it asks first; letting it go writes
it unfinished into the player's database, and a failed write keeps it.
A missing opponent is downloaded before it goes on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-26 23:57:45 +03:00
parent 115a7c33c8
commit 3dac4a185b
11 changed files with 2270 additions and 98 deletions

View file

@ -0,0 +1,347 @@
//! The card of a game put aside (docs/design/desktop-adjourned.md): on the library's
//! shelf, as a strip under a folded shelf, and in the question about a new game.
use chess_core::shakmaty::{Chess, Color, Position, Square};
use egui::{RichText, Sense, Ui, vec2};
use crate::i18n::{tr, trf};
use crate::player_games::PutAside;
use crate::settings::Settings;
/// What the card shows, read once from the game put aside.
pub struct Card {
pos: Chess,
last: Option<(Square, Square)>,
user: Color,
/// «Game against Maia 1550».
pub title: String,
/// «Alekhine · you play black · move 18».
pub line2: String,
/// «5+3 · you 4:12 · Maia 3:58», «no clock».
pub line3: String,
/// The lines of its tooltip under the board.
tip: Vec<String>,
/// Where × writes it (`None`: × deletes it).
pub db: Option<String>,
}
/// What was pressed on a card.
#[derive(PartialEq)]
pub enum Pressed {
Continue,
Discard,
}
impl Card {
pub fn new(aside: &PutAside) -> Self {
let game = crate::play::parse_game(aside.pgn()).unwrap_or_default();
let saved = aside.game();
let user = if saved.white {
Color::White
} else {
Color::Black
};
let end = game.line_end(chess_core::NodeId::ROOT);
let pos = game.position(end).cloned().unwrap_or_default();
let last = game.game_move(end).and_then(|m| match &m.kind {
chess_core::MoveKind::Normal(m) => Some((m.from()?, m.to())),
chess_core::MoveKind::Null => None,
});
let style = crate::play::style(&saved.style);
let (rival, short) = match saved.rival {
crate::play::Rival::Maia => (format!("Maia {}", saved.strength), "Maia".to_owned()),
crate::play::Rival::Rodent => {
let name = style.rodent.name();
(format!("{name} {}", saved.strength), name.to_owned())
}
};
let side = if saved.white {
tr("you play white")
} else {
tr("you play black")
};
let n = pos.fullmoves().get();
let mv = trf("move {n}", &[("n", &n)]);
let mut line2 = Vec::new();
if saved.rival == crate::play::Rival::Rodent && saved.style != crate::play::STYLES[0].id {
line2.push(tr(style.title()).to_owned());
}
line2.push(side.to_owned());
line2.push(mv);
let line3 = match saved.clock {
Some(tc) => {
let left = crate::play::times_left(&game, saved.floor, aside.to_move_left());
let base = std::time::Duration::from_secs(tc.base.into());
let text = |c: Color| {
crate::play::clock_text(
left[if c == Color::White { 0 } else { 1 }].unwrap_or(base),
)
};
format!(
"{} · {} · {short} {}",
tc.label(),
trf("you {t}", &[("t", &text(user))]),
text(!user)
)
}
None => tr("no clock").to_owned(),
};
let whose = if pos.turn() == user {
trf("move {n}, yours", &[("n", &n)])
} else {
trf("move {n}, {rival} to move", &[("n", &n), ("rival", &short)])
};
let when = chrono::DateTime::<chrono::Local>::from(aside.when())
.format("%d.%m, %H:%M")
.to_string();
let mut tip = vec![trf("Game against {rival}", &[("rival", &rival)])];
if line2.len() > 2 {
tip.push(format!("{} · {}", line2[0], side));
} else {
tip.push(side.to_owned());
}
tip.push(whose);
tip.push(trf("Put aside {when}", &[("when", &when)]));
Card {
pos,
last,
user,
title: trf("Game against {rival}", &[("rival", &rival)]),
line2: line2.join(" · "),
line3,
tip,
db: aside.target().map(crate::own_db::base_name),
}
}
/// The board of the position, `size` square, at `at`.
pub fn board(&self, ui: &mut Ui, rect: egui::Rect, settings: &Settings) {
let view = crate::board::BoardView {
pos: &self.pos,
orientation: self.user,
last_move: self.last,
arrows: &[],
circles: &[],
badge: None,
interactive: false,
show_coords: false,
theme: settings.board_theme.theme(),
pieces: settings.piece_set,
animation: 0.0,
premove: None,
auto_queen: false,
alert: None,
};
let mut state = crate::board::BoardState::default();
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
view.show(ui, &mut state);
});
}
/// The board and the lines under the pointer.
fn tooltip(&self, ui: &mut Ui, settings: &Settings) {
let (rect, _) = ui.allocate_exact_size(vec2(192.0, 192.0), Sense::hover());
self.board(ui, rect, settings);
ui.add_space(4.0);
ui.label(RichText::new(&self.tip[0]).strong());
for line in &self.tip[1..] {
ui.label(line);
}
ui.label(RichText::new(tr("Click, or Ctrl+G, Enter")).weak());
}
fn discard_hint(&self) -> String {
match &self.db {
Some(db) => trf(
"Don't finish it: the game is written to «{db}» unfinished",
&[("db", db)],
),
None => tr("Don't finish it: the game is deleted").to_owned(),
}
}
/// The width of the full card: its lines, its button, within 360…460.
pub fn width(&self, ui: &Ui) -> f32 {
let w = |s: &str, size: f32| {
ui.fonts_mut(|f| {
f.layout_no_wrap(
s.to_owned(),
egui::FontId::proportional(size),
egui::Color32::WHITE,
)
.size()
.x
})
};
let lines = w(&self.title, 14.0)
.max(w(&self.line2, 12.0))
.max(w(&self.line3, 12.0));
let button = w(tr("Continue"), 14.0) + 2.0 * ui.spacing().button_padding.x;
(64.0 + 12.0 + lines + 12.0 + button + 8.0 + 20.0 + 4.0).clamp(360.0, 460.0)
}
/// The card on the shelf: 64 high, `width` wide.
pub fn show(&self, ui: &mut Ui, width: f32, settings: &Settings) -> Option<Pressed> {
self.frame(ui, vec2(width, 64.0), settings, |ui, rect, card| {
let v = ui.visuals().clone();
let button = tr("Continue");
let bw = ui.fonts_mut(|f| {
f.layout_no_wrap(
button.to_owned(),
egui::FontId::proportional(14.0),
v.text_color(),
)
.size()
.x
}) + 2.0 * ui.spacing().button_padding.x;
let text_left = rect.left() + 64.0 + 12.0;
let text_w = rect.right() - 4.0 - 20.0 - 8.0 - bw - 12.0 - text_left;
let mut y = rect.top() + 7.0;
for (line, size, color) in [
(&card.title, 14.0, v.text_color()),
(&card.line2, 12.0, v.weak_text_color()),
(&card.line3, 12.0, v.weak_text_color()),
] {
let galley = cut(ui, line, size, color, text_w);
let h = galley.size().y;
ui.painter().galley(egui::pos2(text_left, y), galley, color);
y += h + 2.0;
}
let at = egui::Rect::from_min_size(
egui::pos2(rect.right() - 4.0 - 20.0 - 8.0 - bw, rect.center().y - 14.0),
vec2(bw, 28.0),
);
ui.put(at, primary_button(ui, button)).clicked()
})
}
/// The strip under a folded shelf: 40 high, one line.
pub fn strip(&self, ui: &mut Ui, settings: &Settings) -> Option<Pressed> {
let width = ui.available_width();
self.frame(ui, vec2(width, 40.0), settings, |ui, rect, card| {
let v = ui.visuals().clone();
let button = tr("Continue");
let bw = ui.fonts_mut(|f| {
f.layout_no_wrap(
button.to_owned(),
egui::FontId::proportional(14.0),
v.text_color(),
)
.size()
.x
}) + 2.0 * ui.spacing().button_padding.x;
let text_left = rect.left() + 40.0 + 10.0;
let text_w = rect.right() - 4.0 - 20.0 - 8.0 - bw - 10.0 - text_left;
let line = format!("{} · {} · {}", card.title, card.line2, card.line3);
let galley = cut(ui, &line, 13.0, v.text_color(), text_w);
let y = rect.center().y - galley.size().y / 2.0;
ui.painter()
.galley(egui::pos2(text_left, y), galley, v.text_color());
let at = egui::Rect::from_min_size(
egui::pos2(rect.right() - 4.0 - 20.0 - 8.0 - bw, rect.center().y - 14.0),
vec2(bw, 28.0),
);
ui.put(at, primary_button(ui, button)).clicked()
})
}
/// The card's frame, board, × and click; `inside` draws the rest and says whether its
/// button was pressed.
fn frame(
&self,
ui: &mut Ui,
size: egui::Vec2,
settings: &Settings,
inside: impl FnOnce(&mut Ui, egui::Rect, &Card) -> bool,
) -> Option<Pressed> {
let (rect, _) = ui.allocate_exact_size(size, Sense::hover());
let v = ui.visuals();
let fill = if ui.rect_contains_pointer(rect) {
v.widgets.hovered.weak_bg_fill
} else {
v.faint_bg_color
};
let stroke = egui::Stroke::new(1.5, v.selection.bg_fill);
ui.painter().rect_filled(rect, 6.0, fill);
// Inside the rounded frame, clear of its outline.
let side = rect.height() - 8.0;
let board = egui::Rect::from_min_size(rect.min + vec2(4.0, 4.0), vec2(side, side));
self.board(ui, board, settings);
ui.painter()
.rect_stroke(rect, 6.0, stroke, egui::StrokeKind::Inside);
// The whole card goes on with the game, its board too (over it: later); the
// button and × are their own.
let resp = ui
.interact(rect, ui.id().with("aside_card"), Sense::click())
.on_hover_ui(|ui| self.tooltip(ui, settings));
let mut pressed = None;
if inside(ui, rect, self) {
pressed = Some(Pressed::Continue);
}
let x = egui::Rect::from_min_size(rect.right_top() + vec2(-26.0, 4.0), vec2(22.0, 20.0));
if ui
.put(x, |ui: &mut Ui| crate::widgets::small_close_button(ui))
.on_hover_text(self.discard_hint())
.clicked()
{
pressed = Some(Pressed::Discard);
}
if pressed.is_none() && resp.clicked() {
pressed = Some(Pressed::Continue);
}
resp.widget_info(|| {
egui::WidgetInfo::labeled(
egui::WidgetType::Button,
true,
format!(
"{}: {} · {} · {}. {}",
tr("Game put aside"),
self.title,
self.line2,
self.line3,
tr("Continue")
),
)
});
pressed
}
/// The board and the three lines, for the question about a new game.
pub fn summary(&self, ui: &mut Ui, settings: &Settings) {
ui.horizontal_top(|ui| {
let (rect, _) = ui.allocate_exact_size(vec2(96.0, 96.0), Sense::hover());
self.board(ui, rect, settings);
ui.add_space(12.0 - ui.spacing().item_spacing.x);
ui.vertical(|ui| {
ui.label(RichText::new(&self.title).size(14.0).strong());
ui.label(RichText::new(&self.line2).weak());
ui.label(RichText::new(&self.line3).weak());
});
});
}
}
/// A line cut with «…» to `width`.
fn cut(
ui: &Ui,
text: &str,
size: f32,
color: egui::Color32,
width: f32,
) -> std::sync::Arc<egui::Galley> {
let mut job = egui::text::LayoutJob::simple(
text.to_owned(),
egui::FontId::proportional(size),
color,
width.max(10.0),
);
job.wrap.max_rows = 1;
job.wrap.break_anywhere = true;
job.wrap.overflow_character = Some('…');
ui.fonts_mut(|f| f.layout_job(job))
}
/// As `widgets::primary`, to be put at a place.
fn primary_button(ui: &Ui, label: &str) -> egui::Button<'static> {
egui::Button::new(RichText::new(label.to_owned()).strong()).fill(ui.visuals().selection.bg_fill)
}

View file

@ -195,6 +195,17 @@ pub struct App {
own: Own,
/// The play dialog («Play against the computer»).
play_dialog: Option<crate::play::Dialog>,
/// A game against the computer put aside (or left by a crash): it can go on
/// (docs/design/desktop-adjourned.md).
put_aside: Option<crate::player_games::PutAside>,
/// A new game was asked for while a game is put aside: «There is a game put aside»
/// asks first; what was asked for comes after «Start a new one».
aside_question: Option<PlayNext>,
/// × on the card of a game that goes into no database: «Delete it?».
aside_delete: bool,
/// The opponent of the game put aside is not on the disk: offered for download
/// (`Some(None)`: asked, not started), then the game goes on.
aside_fetch: Option<Option<crate::play::Fetch>>,
/// After the current game is closed: a new game against Maia (a rematch, or the
/// dialog for a new one).
play_next: Option<PlayNext>,
@ -365,6 +376,10 @@ impl App {
toast: None,
own: Own::default(),
play_dialog: None,
put_aside: None,
aside_question: None,
aside_delete: false,
aside_fetch: None,
play_next: None,
tx,
rx,
@ -399,8 +414,21 @@ impl App {
);
app.toast(ctx, msg);
}
// Games a crash left half played go into their databases now.
for r in crate::player_games::recover() {
// Journals no program plays now: a game that can go on is put aside; finished
// games kept from their database and older ones go into it now.
let (written, aside) = crate::player_games::recover();
let mut aside = aside;
let crashed = aside.as_ref().is_some_and(|a| a.crashed());
if let Some(a) = aside.as_mut().filter(|_| crashed) {
// Said once: from now on it is a game put aside.
a.crash_said();
}
app.set_aside(aside);
for r in written {
if r.put_aside {
app.written_unfinished(ctx, r);
continue;
}
let res = r.written.map_err(|e| {
let db = own_db::base_name(&r.target);
trf(
@ -410,6 +438,13 @@ impl App {
});
app.recorded(ctx, &r.player, res, true);
}
if crashed {
app.toast_for(
ctx,
tr("The program closed during a game: the game is put aside, you can go on with it"),
6.0,
);
}
app
}
@ -462,6 +497,22 @@ impl App {
}
fn debug_screenshot(&mut self, ctx: &egui::Context) {
// `CP_RESUME=1`: the game put aside goes on at once; `=ask`: a new game is asked
// for over it.
static RESUMED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
if let Ok(v) = std::env::var("CP_RESUME")
&& self.put_aside.is_some()
&& self.game.is_none()
&& self.aside_question.is_none()
&& ctx.input(|i| i.time) > 1.0
&& !RESUMED.swap(true, std::sync::atomic::Ordering::Relaxed)
{
if v == "ask" {
self.play_new(ctx, PlayNext::Dialog(None));
} else {
self.resume_aside(ctx);
}
}
if self.debug.open_settings && ctx.input(|i| i.time) > 1.5 {
self.debug.open_settings = false;
self.settings_ui.open = true;
@ -1363,6 +1414,11 @@ impl App {
/// What comes after a game against Maia was closed: a rematch, the dialog.
fn play_next_now(&mut self, ctx: &egui::Context) {
// A game put aside: asked about first.
if self.put_aside.is_some() && self.play_next.is_some() {
self.aside_question = self.play_next.take();
return;
}
match self.play_next.take() {
Some(PlayNext::Rematch(s)) => self.start_play(ctx, s),
Some(PlayNext::Dialog(None)) => {
@ -1375,6 +1431,274 @@ impl App {
}
}
/// A new game against the computer, or its dialog (asking first about a game put
/// aside).
fn play_new(&mut self, ctx: &egui::Context, next: PlayNext) {
self.play_next = Some(next);
self.play_next_now(ctx);
}
/// The game put aside, and its card on the shelf.
fn set_aside(&mut self, aside: Option<crate::player_games::PutAside>) {
self.library.aside = aside.as_ref().map(crate::adjourned::Card::new);
self.put_aside = aside;
}
/// The game being played is put aside (its card on the shelf). False: it could not
/// be (no folder for its journal): it goes on.
fn put_game_aside(&mut self, ctx: &egui::Context) -> bool {
let Some(aside) = self.game.as_mut().and_then(|g| g.put_aside()) else {
self.toast(
ctx,
tr("The game could not be put aside: its file could not be written"),
);
return false;
};
// One at a time: a game started over another asked about it first.
self.let_go_aside(ctx);
self.set_aside(Some(aside));
true
}
/// The game put aside is let go: written into its player's database unfinished, or
/// deleted when games are not written.
fn let_go_aside(&mut self, ctx: &egui::Context) {
let Some(aside) = self.put_aside.take() else {
return;
};
self.library.aside = None;
match aside.discard() {
Ok(Some(r)) => self.written_unfinished(ctx, r),
Ok(None) => {}
// Not written: it stays put aside (its card back), the reason said.
Err(b) => {
let (r, aside) = *b;
self.set_aside(Some(aside));
self.written_unfinished(ctx, r);
}
}
}
/// A game put aside went into its database unfinished (or could not): said.
fn written_unfinished(&mut self, ctx: &egui::Context, r: crate::player_games::Recovered) {
let db = own_db::base_name(&r.target);
match r.written {
Ok(w) => {
let n = w.index + 1;
self.recorded(ctx, &r.player, Ok(w), false);
self.toast_for(
ctx,
trf(
"Game written to «{db}» unfinished, No. {n}",
&[("db", &db), ("n", &n)],
),
6.0,
);
}
Err(e) => self.toast(
ctx,
trf(
"Could not write to «{db}»: {reason}",
&[("db", &db), ("reason", &e)],
),
),
}
}
/// Goes on with the game put aside: its record on the screen, the opponent started
/// again with its moves, the clocks where they stopped.
fn resume_aside(&mut self, ctx: &egui::Context) {
let Some(aside) = self.put_aside.as_ref() else {
return;
};
let saved = aside.game().clone();
let Some(game) = crate::play::parse_game(aside.pgn()) else {
self.toast(ctx, tr("The game put aside could not be read"));
return;
};
let Some(engine) = crate::play::engine_for(&saved.start(None)) else {
// Its opponent is no longer on the disk: downloaded first.
self.aside_fetch = Some(None);
return;
};
let judge = crate::engines::own_stockfish().or_else(|| {
self.settings
.active_engine()
.and_then(|e| e.executable())
.filter(|p| p.is_file())
});
let Some(aside) = self.put_aside.take() else {
return;
};
self.library.aside = None;
let to_move_left = aside.to_move_left();
self.open_over(game);
if let Some(g) = self.game.as_mut() {
g.resume_play(&saved, to_move_left, engine, judge, aside.resume(), ctx);
}
}
/// «There is a game put aside»: go on with it, or let it go for the new game.
fn aside_question(&mut self, ctx: &egui::Context) {
if self.aside_question.is_none() {
return;
}
let Some(card) = self.library.aside.as_ref() else {
// Let go meanwhile: what was asked for goes on.
self.play_next = self.aside_question.take();
self.play_next_now(ctx);
return;
};
let mut choice = None;
egui::Modal::new(egui::Id::new("aside_question")).show(ctx, |ui| {
ui.set_width(460.0);
ui.heading(tr("There is a game put aside"));
ui.add_space(4.0);
card.summary(ui, &self.settings);
ui.add_space(8.0);
ui.label(match &card.db {
Some(db) => trf(
"A new game replaces it; the one put aside is written to «{db}» unfinished.",
&[("db", db)],
),
None => tr("A new game replaces it: the one put aside is deleted.").to_owned(),
});
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let go_on = crate::widgets::primary(ui, tr("Continue it"));
// The main answer has the keyboard (its focus seen).
if ui.memory(|m| m.focused().is_none()) {
go_on.request_focus();
}
if go_on.clicked() {
choice = Some(true);
}
if ui.button(tr("Start a new one")).clicked() {
choice = Some(false);
}
});
});
if choice.is_none() && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Enter)) {
choice = Some(true);
}
if choice.is_none() && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape))
{
self.aside_question = None;
return;
}
match choice {
Some(true) => {
self.aside_question = None;
self.resume_aside(ctx);
}
Some(false) => {
self.let_go_aside(ctx);
self.play_next = self.aside_question.take();
self.play_next_now(ctx);
}
None => {}
}
}
/// The opponent of the game put aside is downloaded, then the game goes on; the card
/// stays meanwhile and after a failure.
fn aside_fetch_question(&mut self, ctx: &egui::Context) {
let Some(fetch) = self.aside_fetch.as_ref() else {
return;
};
let Some(saved) = self.put_aside.as_ref().map(|a| a.game().clone()) else {
self.aside_fetch = None;
return;
};
let mut start = false;
let mut close = false;
let mut done = false;
egui::Modal::new(egui::Id::new("aside_fetch")).show(ctx, |ui| {
ui.set_width(460.0);
ui.heading(tr("The opponent of this game is not installed"));
if let Some(card) = self.library.aside.as_ref() {
ui.add_space(4.0);
card.summary(ui, &self.settings);
}
ui.add_space(8.0);
let state = match fetch {
None => {
ui.label(RichText::new(crate::play::Fetch::note(&saved)).weak());
None
}
Some(f) => Some(f.show(ui)),
};
done = state == Some(crate::play::Fetched::Done);
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
match state {
None => start |= crate::widgets::primary(ui, tr("Download")).clicked(),
Some(crate::play::Fetched::Failed) => {
start |= crate::widgets::primary(ui, tr("Try again")).clicked()
}
_ => {}
}
close |= ui.button(tr("Cancel")).clicked();
});
});
if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) {
close = true;
}
if done {
self.aside_fetch = None;
self.resume_aside(ctx);
} else if close {
// Dropping the download stops it.
self.aside_fetch = None;
} else if start {
self.aside_fetch = Some(Some(crate::play::Fetch::start(&saved, ctx)));
}
}
/// × on the card of a game that goes into no database: deleting it is asked.
fn aside_delete_question(&mut self, ctx: &egui::Context) {
if !self.aside_delete {
return;
}
let mut choice = None;
egui::Modal::new(egui::Id::new("aside_delete")).show(ctx, |ui| {
ui.set_width(400.0);
ui.heading(tr("Delete the game put aside?"));
if let Some(card) = self.library.aside.as_ref() {
ui.add_space(4.0);
card.summary(ui, &self.settings);
ui.add_space(8.0);
}
ui.label(tr(
"Games are not written into a database: it is not kept anywhere.",
));
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button(tr("Cancel")).clicked() {
choice = Some(false);
}
let delete =
egui::Button::new(RichText::new(tr("Delete")).color(egui::Color32::WHITE))
.fill(ui.visuals().error_fg_color);
if ui.add(delete).clicked() {
choice = Some(true);
}
});
});
if choice.is_none() && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape))
{
choice = Some(false);
}
match choice {
Some(true) => {
self.aside_delete = false;
self.let_go_aside(ctx);
}
Some(false) => self.aside_delete = false,
None => {}
}
}
/// A game from a position of another game: its moves to that position, the game
/// it comes from waiting under it (as a game opened from the reference does).
fn game_from(&mut self, from: &crate::play::StartFrom) {
@ -1963,10 +2287,16 @@ impl App {
if let Some(g) = self.game.as_mut() {
g.commit_editor();
if g.playing_started() {
g.ask_leave(intent);
return;
// Quitting puts the game aside: nothing is lost, no question.
if intent != CloseIntent::QuitApp || !self.put_game_aside(ctx) {
if let Some(g) = self.game.as_mut() {
g.ask_leave(intent);
}
return;
}
} else {
g.resign_if_playing();
}
g.resign_if_playing();
}
if self.game.as_ref().is_some_and(|g| g.game.is_modified()) {
self.confirm_close = Some(intent);
@ -2017,6 +2347,9 @@ impl App {
// The settings first (the new process reads them), and none of the dev
// hooks of this one (they would start the update again).
let _ = self.settings.save();
// The game put aside is let go of (its files stay): the new process
// offers it.
self.set_aside(None);
let mut cmd = std::process::Command::new(exe);
for (k, _) in std::env::vars_os() {
if k.to_string_lossy().starts_with("CP_") {
@ -2290,8 +2623,13 @@ impl eframe::App for App {
{
g.commit_editor();
if g.playing_started() {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
g.ask_leave(CloseIntent::QuitApp);
// Put aside: the next start offers to go on with it.
if !self.put_game_aside(&ctx) {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
if let Some(g) = self.game.as_mut() {
g.ask_leave(CloseIntent::QuitApp);
}
}
} else {
g.resign_if_playing();
}
@ -2353,7 +2691,7 @@ impl eframe::App for App {
// In the library a game from the start; on a game's screen the game plays on
// from its position (the game view takes Ctrl+G there).
if self.game.is_none() && ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::G))) {
self.play_dialog = Some(crate::play::Dialog::new(&self.settings));
self.play_new(&ctx, PlayNext::Dialog(None));
}
if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::N))) && self.game.is_none() {
self.new_game();
@ -2498,9 +2836,22 @@ impl eframe::App for App {
self.request_close(&ctx, intent);
}
GameAction::Train(start) => self.open_training(*start),
GameAction::PlayFrom(from) => {
self.play_dialog =
Some(crate::play::Dialog::new_from(&self.settings, *from));
GameAction::PlayFrom(from) => self.play_new(&ctx, PlayNext::Dialog(Some(from))),
GameAction::PutAside(intent) => {
let intent = intent.unwrap_or(
if self.game.as_ref().is_some_and(|g| g.previous.is_some()) {
CloseIntent::ReturnToPrevious
} else {
CloseIntent::BackToLibrary
},
);
if self.put_game_aside(&ctx) {
// Over another game the shelf is not in view: said.
if intent == CloseIntent::ReturnToPrevious {
self.toast(&ctx, tr("Game put aside: go on from the library"));
}
self.request_close(&ctx, intent);
}
}
GameAction::AddToDatabase => {
if let Some(g) = self.game.as_mut() {
@ -2570,9 +2921,15 @@ impl eframe::App for App {
}
LibraryAction::OpenPgn(text) => self.open_pgn_text(&ctx, text, true),
LibraryAction::NewGame => self.new_game(),
LibraryAction::Play => {
self.play_dialog = Some(crate::play::Dialog::new(&self.settings))
LibraryAction::ResumeAside => self.resume_aside(&ctx),
LibraryAction::DiscardAside => {
if self.library.aside.as_ref().is_some_and(|c| c.db.is_some()) {
self.let_go_aside(&ctx);
} else {
self.aside_delete = true;
}
}
LibraryAction::Play => self.play_new(&ctx, PlayNext::Dialog(None)),
LibraryAction::NewGameIn(path) => {
self.new_game();
if let Some(g) = self.game.as_mut() {
@ -2762,6 +3119,9 @@ impl eframe::App for App {
None => {}
}
}
self.aside_question(&ctx);
self.aside_delete_question(&ctx);
self.aside_fetch_question(&ctx);
if let Some(d) = self.play_dialog.as_mut()
&& let Some(out) = d.show(&ctx, &mut self.settings)
{

View file

@ -184,7 +184,13 @@ impl BoardView<'_> {
/// Draws the board into the available square area. Returns a move the user made, if any.
pub fn show(self, ui: &mut egui::Ui, state: &mut BoardState) -> Option<Move> {
let avail = ui.available_size();
let side = avail.x.min(avail.y).max(64.0).floor();
// A board to play on stays usable; one only shown may be a thumbnail.
let least = if self.interactive || self.premove.is_some() {
64.0
} else {
16.0
};
let side = avail.x.min(avail.y).max(least).floor();
let (rect, response) = ui.allocate_exact_size(Vec2::splat(side), Sense::click_and_drag());
let sq_size = side / 8.0;
let geo = Geometry {

View file

@ -127,6 +127,9 @@ pub enum GameAction {
Rematch,
/// Leaving after «The game is on» was answered.
Leave(crate::app::CloseIntent),
/// The game in progress is put aside (GameView::put_aside), then leaving: where the
/// user was going (`None`: where «⬅» leads).
PutAside(Option<crate::app::CloseIntent>),
/// Saving into a database, then leaving.
SaveAndLeave(crate::app::CloseIntent),
/// After a game against Maia: the play dialog.
@ -2116,7 +2119,7 @@ impl GameView {
record: Option<std::path::PathBuf>,
ctx: &egui::Context,
) {
use crate::play::{Clock, Opponent, Session};
use crate::play::Clock;
// Dev hook `CP_PREMOVE=e7e5`: a premove set at the start (to see it without a mouse).
if let Some(pm) = std::env::var("CP_PREMOVE").ok().filter(|p| p.len() == 4)
&& let (Ok(from), Ok(to)) = (pm[..2].parse(), pm[2..].parse())
@ -2202,17 +2205,87 @@ impl GameView {
if floor != NodeId::ROOT {
self.goto(floor);
}
// Its journal keeps what it is played with: it can be put aside and go on.
let floor_plies = self.plies_to(floor);
let journal = Some(crate::player_games::Journal::new(
record,
&start.user_name,
start.saved(floor_plies),
));
let clock = start.clock.map(Clock::new);
self.begin_play(start, (engine, file), judge, journal, clock, floor, ctx);
}
/// Goes on with a game put aside (docs/design/desktop-adjourned.md): the game on the
/// screen is its record so far; the clocks have the time each side had left (the side
/// to move's when it was put aside, the other's at its last move, `[%clk]`); its own
/// journal goes on.
pub fn resume_play(
&mut self,
saved: &crate::play::Saved,
to_move_left: Option<std::time::Duration>,
engine: (crate::play::Engine, std::path::PathBuf),
judge: Option<std::path::PathBuf>,
journal: crate::player_games::Journal,
ctx: &egui::Context,
) {
use crate::play::Clock;
// Unfinished while it was aside: the game goes on.
self.game.remove_tag("Termination");
self.game.mark_saved();
let line = self.game.mainline();
let floor = if saved.floor == 0 {
NodeId::ROOT
} else {
line.get(saved.floor - 1).copied().unwrap_or(NodeId::ROOT)
};
let from = (floor != NodeId::ROOT)
.then(|| self.start_from(floor).ok())
.flatten();
let start = saved.start(from);
let end = self.play_end_node();
let to_move = self.game.position(end).map_or(Color::White, |p| p.turn());
let left = crate::play::times_left(&self.game, saved.floor, to_move_left);
let clock = start
.clock
.map(|tc| Clock::resumed(tc, left, to_move, std::time::Instant::now()));
self.goto(end);
self.begin_play(start, engine, judge, Some(journal), clock, floor, ctx);
}
/// Half-moves of the main line up to `node` (0 for the start).
fn plies_to(&self, node: NodeId) -> usize {
self.game
.mainline()
.iter()
.position(|&n| n == node)
.map_or(0, |k| k + 1)
}
/// The game against the computer runs: its opponent and judge start, its clocks.
#[allow(clippy::too_many_arguments)]
fn begin_play(
&mut self,
start: crate::play::Start,
(engine, file): (crate::play::Engine, std::path::PathBuf),
judge: Option<std::path::PathBuf>,
journal: Option<crate::player_games::Journal>,
clock: Option<crate::play::Clock>,
floor: NodeId,
ctx: &egui::Context,
) {
use crate::play::{Opponent, Session};
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)),
journal,
user: start.user,
strength: start.strength,
engine,
style: start.style.clone(),
user_elo: start.user_elo,
clock: start.clock.map(Clock::new),
clock,
opponent: match engine {
crate::play::Engine::Maia(_) => Opponent::start(file, ctx),
crate::play::Engine::Rodent(_) => {
@ -2623,8 +2696,14 @@ impl GameView {
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| {
let Some(target) = journal.target() else {
return;
};
let name = crate::own_db::base_name(target);
let Some(res) = journal.finish(&self.game.to_pgn()) else {
return;
};
let res = res.map_err(|e| {
trf(
"Could not write to «{db}»: {reason}",
&[("db", &name), ("reason", &e)],
@ -2646,6 +2725,45 @@ impl GameView {
self.record_news = Some(res);
}
/// Puts the game in progress aside (docs/design/desktop-adjourned.md): it stops here,
/// its journal stays and it can go on later. `None`: its journal could not be made
/// (no folder for it): the game is left as it is, still played.
pub fn put_aside(&mut self) -> Option<crate::player_games::PutAside> {
let journal = self.play.as_ref()?.journal.as_ref()?;
if !journal.can_put_aside() {
return None;
}
// «The game is on» was open (the window closed over it): the clocks waited.
if let Some((_, since)) = self.play_leave.take()
&& let Some(s) = self.play.as_mut()
&& s.resign_offer.is_none()
&& let Some(c) = s.clock.as_mut()
{
c.pause(since.elapsed());
}
self.close_resign_offer();
let mut s = self.play.take()?;
s.opponent.forget();
self.board.clear_premove();
let mut g = self.game.clone();
g.set_tag("Termination", "Unterminated");
// The side to move keeps the time it had now (not its last move's).
let to_move = self
.game
.position(self.play_end_node())
.map_or(Color::White, |p| p.turn());
let left = s
.clock
.as_ref()
.map(|c| c.left(to_move, std::time::Instant::now()));
let aside = s
.journal
.take()
.and_then(|j| j.put_aside(&g.to_pgn(), left));
self.game.mark_saved();
aside
}
/// The player's name of the game against the computer on the screen.
pub fn player_name(&self) -> String {
self.play_start
@ -2937,7 +3055,8 @@ impl GameView {
self.play.is_some() && self.play_started()
}
/// «The game is on»: resign and add, resign and leave, keep playing.
/// «The game is on»: resign (and add), keep playing, put aside (the main answer: it
/// costs nothing).
fn leave_question(&mut self, ctx: &egui::Context, actions: &mut Vec<GameAction>) {
let Some((intent, since)) = self.play_leave else {
return;
@ -2951,30 +3070,53 @@ impl GameView {
.play
.as_ref()
.and_then(|s| s.journal.as_ref())
.map(|j| crate::own_db::base_name(j.target()));
.and_then(|j| j.target())
.map(crate::own_db::base_name);
match &target {
Some(db) => ui.label(trf(
"If you leave, the game ends with your resignation and is written to «{db}».",
"Put the game aside: the clocks stop, and you can go on from its card in the library. If you resign, the game ends and is written to «{db}».",
&[("db", db)],
)),
None => ui.label(tr("If you leave, the game ends with your resignation.")),
None => ui.label(tr("Put the game aside: the clocks stop, and you can go on from its card in the library. If you resign, the game ends.")),
};
ui.add_space(8.0);
ui.horizontal_wrapped(|ui| {
if target.is_none() && ui.button(tr("Resign and add to a database…")).clicked() {
choice = Some(0);
// Resigning on the left, apart from the main answer; all of one height. With
// «add to a database» too they take a row of their own above.
let button = |text: &str| egui::Button::new(text).min_size(vec2(0.0, 30.0));
let resign = |ui: &mut Ui, choice: &mut Option<u8>| {
if target.is_none() && ui.add(button(tr("Resign and add to a database…"))).clicked() {
*choice = Some(0);
}
if ui.button(tr("Resign and leave")).clicked() {
choice = Some(1);
if ui.add(button(tr("Resign and leave"))).clicked() {
*choice = Some(1);
}
if crate::widgets::primary(ui, tr("Keep playing")).clicked() {
choice = Some(2);
};
let main = |ui: &mut Ui, choice: &mut Option<u8>| {
if crate::widgets::primary(ui, tr("Put aside")).clicked() {
*choice = Some(3);
}
});
if ui.add(button(tr("Keep playing"))).clicked() {
*choice = Some(2);
}
};
if target.is_none() {
ui.horizontal(|ui| resign(ui, &mut choice));
ui.add_space(4.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
main(ui, &mut choice)
});
} else {
let mut right = None;
egui::Sides::new().show(ui, |ui| resign(ui, &mut choice), |ui| main(ui, &mut right));
choice = choice.or(right);
}
});
if choice.is_none() && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) {
choice = Some(2);
}
if choice.is_none() && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)) {
choice = Some(3);
}
let Some(choice) = choice else { return };
self.play_leave = None;
// The clocks waited while the question was open.
@ -3000,6 +3142,7 @@ impl GameView {
self.game.mark_saved();
actions.push(GameAction::Leave(intent));
}
3 => actions.push(GameAction::PutAside(Some(intent))),
_ => {}
}
}
@ -3313,6 +3456,41 @@ impl GameView {
));
}
}
// Leaving without an end, apart from the game's endings. Short of room
// it is its icon (the words in its tooltip), on the next row with no
// separator left at the end of this one.
let hint = format!(
"{}\n{}",
tr("⏸ Put aside"),
tr("Put the game aside: the clocks stop; go on from its card in the library")
);
let w = |t: &str| {
ui.fonts_mut(|f| {
f.layout_no_wrap(t.to_owned(), egui::FontId::proportional(14.0), Color32::WHITE)
.size()
.x
}) + 2.0 * ui.spacing().button_padding.x
};
let separator = 2.0 * ui.spacing().item_spacing.x + 1.0;
// What is left of this row (a wrapping row offers its whole width).
let room = ui.max_rect().right() - ui.cursor().min.x;
let full = room >= separator + w(tr("⏸ Put aside"));
let fits = room >= separator + w("⏸");
if fits {
ui.separator();
}
let label = if full { tr("⏸ Put aside") } else { "⏸" };
if ui
.add(word(label))
.on_hover_text(if full {
tr("Put the game aside: the clocks stop; go on from its card in the library")
} else {
&hint
})
.clicked()
{
actions.push(GameAction::PutAside(None));
}
}
});
ui.add_space(4.0);

View file

@ -10244,17 +10244,6 @@ const ROWS: &[[&str; 9]] = &[
"Partiya davom etmoqda",
"Партия жүріп жатыр",
],
[
"If you leave, the game ends with your resignation.",
"Если выйти, партия закончится вашей сдачей.",
"Si vous quittez, la partie se termine par votre abandon.",
"Wenn Sie gehen, endet die Partie mit Ihrer Aufgabe.",
"Si sales, la partida terminará con tu abandono.",
"Se esci, la partita finisce con il tuo abbandono.",
"Se você sair, a partida termina com o seu abandono.",
"Chiqsangiz, partiya taslim bo‘lishingiz bilan tugaydi.",
"Шықсаңыз, партия сіздің берілуіңізбен аяқталады.",
],
[
"Resign and add to a database…",
"Сдаться и добавить в базу…",
@ -11598,17 +11587,6 @@ const ROWS: &[[&str; 9]] = &[
"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",
"Сюда записываются партии с компьютером",
@ -13367,6 +13345,347 @@ const ROWS: &[[&str; 9]] = &[
"O‘sha pozitsiya, yana qoralar bilan o‘ynaysiz",
"Сол позиция, сіз қайтадан қаралармен ойнайсыз",
],
[
"⏸ Put aside",
"⏸ Отложить",
"⏸ Ajourner",
"⏸ Vertagen",
"⏸ Aplazar",
"⏸ Rinvia",
"⏸ Adiar",
"⏸ Keyinga qoldirish",
"⏸ Кейінге қалдыру",
],
[
"Put aside",
"Отложить",
"Ajourner",
"Vertagen",
"Aplazar",
"Rinvia",
"Adiar",
"Keyinga qoldirish",
"Кейінге қалдыру",
],
[
"Put the game aside: the clocks stop; go on from its card in the library",
"Отложить партию: часы остановятся, продолжить можно с карточки в библиотеке",
"Ajourner la partie : les pendules s'arrêtent ; reprenez-la depuis sa carte dans la bibliothèque",
"Partie vertagen: Die Uhren halten an; weiter geht es über ihre Karte in der Bibliothek",
"Aplazar la partida: los relojes se detienen; continúa desde su tarjeta en la biblioteca",
"Rinvia la partita: gli orologi si fermano; riprendila dalla sua scheda nella biblioteca",
"Adiar a partida: os relógios param; continue pelo cartão dela na biblioteca",
"O‘yinni keyinga qoldirish: soatlar to‘xtaydi; kutubxonadagi kartasidan davom ettiring",
"Ойынды кейінге қалдыру: сағаттар тоқтайды; кітапханадағы карточкасынан жалғастырыңыз",
],
[
"Put the game aside: the clocks stop, and you can go on from its card in the library. If you resign, the game ends and is written to «{db}».",
"Отложите партию — часы остановятся, а продолжить её можно с карточки в библиотеке. Если сдаться, партия закончится и запишется в «{db}».",
"Ajournez la partie : les pendules s'arrêtent et vous pourrez la reprendre depuis sa carte dans la bibliothèque. Si vous abandonnez, la partie se termine et est enregistrée dans « {db} ».",
"Vertagen Sie die Partie: Die Uhren halten an, und Sie können über ihre Karte in der Bibliothek weiterspielen. Wenn Sie aufgeben, endet die Partie und wird in „{db}“ geschrieben.",
"Aplaza la partida: los relojes se detienen y podrás continuarla desde su tarjeta en la biblioteca. Si abandonas, la partida termina y se guarda en «{db}».",
"Rinvia la partita: gli orologi si fermano e potrai riprenderla dalla sua scheda nella biblioteca. Se abbandoni, la partita finisce e viene scritta in «{db}».",
"Adie a partida: os relógios param e você pode continuá-la pelo cartão dela na biblioteca. Se abandonar, a partida termina e é gravada em «{db}».",
"O‘yinni keyinga qoldiring: soatlar to‘xtaydi, uni kutubxonadagi kartasidan davom ettirish mumkin. Taslim bo‘lsangiz, o‘yin tugaydi va «{db}» ga yoziladi.",
"Ойынды кейінге қалдырыңыз: сағаттар тоқтайды, оны кітапханадағы карточкасынан жалғастыруға болады. Берілсеңіз, ойын аяқталып, «{db}» ішіне жазылады.",
],
[
"Put the game aside: the clocks stop, and you can go on from its card in the library. If you resign, the game ends.",
"Отложите партию — часы остановятся, а продолжить её можно с карточки в библиотеке. Если сдаться, партия закончится вашей сдачей.",
"Ajournez la partie : les pendules s'arrêtent et vous pourrez la reprendre depuis sa carte dans la bibliothèque. Si vous abandonnez, la partie se termine.",
"Vertagen Sie die Partie: Die Uhren halten an, und Sie können über ihre Karte in der Bibliothek weiterspielen. Wenn Sie aufgeben, endet die Partie.",
"Aplaza la partida: los relojes se detienen y podrás continuarla desde su tarjeta en la biblioteca. Si abandonas, la partida termina.",
"Rinvia la partita: gli orologi si fermano e potrai riprenderla dalla sua scheda nella biblioteca. Se abbandoni, la partita finisce.",
"Adie a partida: os relógios param e você pode continuá-la pelo cartão dela na biblioteca. Se abandonar, a partida termina.",
"O‘yinni keyinga qoldiring: soatlar to‘xtaydi, uni kutubxonadagi kartasidan davom ettirish mumkin. Taslim bo‘lsangiz, o‘yin tugaydi.",
"Ойынды кейінге қалдырыңыз: сағаттар тоқтайды, оны кітапханадағы карточкасынан жалғастыруға болады. Берілсеңіз, ойын аяқталады.",
],
[
"you play white",
"вы белыми",
"vous avez les Blancs",
"Sie spielen Weiß",
"juegas con blancas",
"giochi con il Bianco",
"você joga de brancas",
"siz oqlar bilan",
"сіз ақтармен",
],
[
"you play black",
"вы чёрными",
"vous avez les Noirs",
"Sie spielen Schwarz",
"juegas con negras",
"giochi con il Nero",
"você joga de pretas",
"siz qoralar bilan",
"сіз қаралармен",
],
[
"move {n}",
"{n}-й ход",
"coup {n}",
"Zug {n}",
"jugada {n}",
"mossa {n}",
"lance {n}",
"{n}-yurish",
"{n}-жүріс",
],
[
"you {t}",
"вы {t}",
"vous {t}",
"Sie {t}",
"tú {t}",
"tu {t}",
"você {t}",
"siz {t}",
"сіз {t}",
],
[
"no clock",
"без часов",
"sans pendule",
"ohne Uhr",
"sin reloj",
"senza orologio",
"sem relógio",
"soatsiz",
"сағатсыз",
],
[
"move {n}, yours",
"{n}-й ход, ваш",
"coup {n}, à vous",
"Zug {n}, Sie sind am Zug",
"jugada {n}, te toca",
"mossa {n}, tocca a te",
"lance {n}, sua vez",
"{n}-yurish, sizniki",
"{n}-жүріс, сіздікі",
],
[
"move {n}, {rival} to move",
"{n}-й ход, ход {rival}",
"coup {n}, au tour de {rival}",
"Zug {n}, {rival} ist am Zug",
"jugada {n}, le toca a {rival}",
"mossa {n}, tocca a {rival}",
"lance {n}, vez de {rival}",
"{n}-yurish, {rival} navbati",
"{n}-жүріс, {rival} кезегі",
],
[
"Game against {rival}",
"Партия с {rival}",
"Partie contre {rival}",
"Partie gegen {rival}",
"Partida contra {rival}",
"Partita contro {rival}",
"Partida contra {rival}",
"{rival} bilan o‘yin",
"{rival} қарсы ойын",
],
[
"Put aside {when}",
"Отложена {when}",
"Ajournée le {when}",
"Vertagt am {when}",
"Aplazada el {when}",
"Rinviata il {when}",
"Adiada em {when}",
"Qoldirilgan: {when}",
"Қалдырылған: {when}",
],
[
"Click, or Ctrl+G, Enter",
"Щелчок или Ctrl+G, Enter",
"Clic, ou Ctrl+G, Entrée",
"Klick, oder Strg+G, Enter",
"Clic, o Ctrl+G, Intro",
"Clic, oppure Ctrl+G, Invio",
"Clique, ou Ctrl+G, Enter",
"Bosish yoki Ctrl+G, Enter",
"Басу немесе Ctrl+G, Enter",
],
[
"Don't finish it: the game is written to «{db}» unfinished",
"Не доигрывать: партия запишется в «{db}» неоконченной",
"Ne pas la finir : la partie est enregistrée dans « {db} » inachevée",
"Nicht zu Ende spielen: Die Partie wird unbeendet in „{db}“ geschrieben",
"No terminarla: la partida se guarda en «{db}» sin terminar",
"Non finirla: la partita viene scritta in «{db}» non finita",
"Não terminar: a partida é gravada em «{db}» inacabada",
"Tugatmaslik: o‘yin «{db}» ga tugallanmagan holda yoziladi",
"Аяқтамау: ойын «{db}» ішіне аяқталмаған күйде жазылады",
],
[
"Don't finish it: the game is deleted",
"Не доигрывать: партия будет удалена",
"Ne pas la finir : la partie est supprimée",
"Nicht zu Ende spielen: Die Partie wird gelöscht",
"No terminarla: la partida se elimina",
"Non finirla: la partita viene eliminata",
"Não terminar: a partida é excluída",
"Tugatmaslik: o‘yin o‘chiriladi",
"Аяқтамау: ойын жойылады",
],
[
"The program closed during a game: the game is put aside, you can go on with it",
"Программа закрылась посреди партии — партия отложена, её можно продолжить",
"Le programme s'est fermé pendant une partie : elle est ajournée, vous pouvez la reprendre",
"Das Programm wurde während einer Partie beendet: Die Partie ist vertagt, Sie können weiterspielen",
"El programa se cerró durante una partida: la partida está aplazada, puedes continuarla",
"Il programma si è chiuso durante una partita: la partita è rinviata, puoi riprenderla",
"O programa fechou durante uma partida: a partida foi adiada, você pode continuá-la",
"Dastur o‘yin vaqtida yopildi: o‘yin keyinga qoldirildi, uni davom ettirish mumkin",
"Бағдарлама ойын кезінде жабылды: ойын кейінге қалдырылды, оны жалғастыруға болады",
],
[
"The game could not be put aside: its file could not be written",
"Партию не удалось отложить: не записался её файл",
"Impossible d'ajourner la partie : son fichier n'a pas pu être écrit",
"Die Partie konnte nicht vertagt werden: Ihre Datei ließ sich nicht schreiben",
"No se pudo aplazar la partida: no se pudo escribir su archivo",
"Impossibile rinviare la partita: non è stato possibile scrivere il suo file",
"Não foi possível adiar a partida: o arquivo dela não pôde ser gravado",
"O‘yinni keyinga qoldirib bo‘lmadi: uning fayli yozilmadi",
"Ойынды кейінге қалдыру мүмкін болмады: оның файлы жазылмады",
],
[
"Game written to «{db}» unfinished, No. {n}",
"Партия записана в «{db}» неоконченной, № {n}",
"Partie enregistrée dans « {db} » inachevée, n° {n}",
"Partie unbeendet in „{db}“ geschrieben, Nr. {n}",
"Partida guardada en «{db}» sin terminar, n.º {n}",
"Partita scritta in «{db}» non finita, n. {n}",
"Partida gravada em «{db}» inacabada, nº {n}",
"O‘yin «{db}» ga tugallanmagan holda yozildi, № {n}",
"Ойын «{db}» ішіне аяқталмаған күйде жазылды, № {n}",
],
[
"The game put aside could not be read",
"Отложенную партию не удалось прочитать",
"Impossible de lire la partie ajournée",
"Die vertagte Partie ließ sich nicht lesen",
"No se pudo leer la partida aplazada",
"Impossibile leggere la partita rinviata",
"Não foi possível ler a partida adiada",
"Qoldirilgan o‘yinni o‘qib bo‘lmadi",
"Қалдырылған ойынды оқу мүмкін болмады",
],
[
"There is a game put aside",
"Есть отложенная партия",
"Une partie est ajournée",
"Es gibt eine vertagte Partie",
"Hay una partida aplazada",
"C'è una partita rinviata",
"Há uma partida adiada",
"Keyinga qoldirilgan o‘yin bor",
"Кейінге қалдырылған ойын бар",
],
[
"A new game replaces it; the one put aside is written to «{db}» unfinished.",
"Новая партия заменит её; отложенная запишется в «{db}» неоконченной.",
"Une nouvelle partie la remplace ; la partie ajournée est enregistrée dans « {db} » inachevée.",
"Eine neue Partie ersetzt sie; die vertagte wird unbeendet in „{db}“ geschrieben.",
"Una partida nueva la sustituye; la aplazada se guarda en «{db}» sin terminar.",
"Una nuova partita la sostituisce; quella rinviata viene scritta in «{db}» non finita.",
"Uma nova partida a substitui; a adiada é gravada em «{db}» inacabada.",
"Yangi o‘yin uning o‘rnini oladi; qoldirilgani «{db}» ga tugallanmagan holda yoziladi.",
"Жаңа ойын оның орнын басады; қалдырылғаны «{db}» ішіне аяқталмаған күйде жазылады.",
],
[
"A new game replaces it: the one put aside is deleted.",
"Новая партия заменит её: отложенная будет удалена.",
"Une nouvelle partie la remplace : la partie ajournée est supprimée.",
"Eine neue Partie ersetzt sie: Die vertagte wird gelöscht.",
"Una partida nueva la sustituye: la aplazada se elimina.",
"Una nuova partita la sostituisce: quella rinviata viene eliminata.",
"Uma nova partida a substitui: a adiada é excluída.",
"Yangi o‘yin uning o‘rnini oladi: qoldirilgani o‘chiriladi.",
"Жаңа ойын оның орнын басады: қалдырылғаны жойылады.",
],
[
"Continue it",
"Продолжить её",
"La reprendre",
"Weiterspielen",
"Continuarla",
"Riprenderla",
"Continuá-la",
"Davom ettirish",
"Жалғастыру",
],
[
"Start a new one",
"Начать новую",
"En commencer une nouvelle",
"Neue beginnen",
"Empezar una nueva",
"Iniziarne una nuova",
"Começar uma nova",
"Yangisini boshlash",
"Жаңасын бастау",
],
[
"Delete the game put aside?",
"Удалить отложенную партию?",
"Supprimer la partie ajournée ?",
"Die vertagte Partie löschen?",
"¿Eliminar la partida aplazada?",
"Eliminare la partita rinviata?",
"Excluir a partida adiada?",
"Qoldirilgan o‘yin o‘chirilsinmi?",
"Қалдырылған ойын жойылсын ба?",
],
[
"Games are not written into a database: it is not kept anywhere.",
"Партии не записываются в базу: она нигде не сохранится.",
"Les parties ne sont pas enregistrées dans une base : elle n'est conservée nulle part.",
"Partien werden in keine Datenbank geschrieben: Sie wird nirgends aufbewahrt.",
"Las partidas no se guardan en una base: no se conservará en ningún sitio.",
"Le partite non vengono scritte in un database: non sarà conservata da nessuna parte.",
"As partidas não são gravadas em uma base: ela não fica guardada em lugar nenhum.",
"O‘yinlar bazaga yozilmaydi: u hech qayerda saqlanmaydi.",
"Ойындар базаға жазылмайды: ол ешқайда сақталмайды.",
],
[
"Game put aside: go on from the library",
"Партия отложена — продолжить можно в библиотеке",
"Partie ajournée : reprenez-la depuis la bibliothèque",
"Partie vertagt: weiter geht es in der Bibliothek",
"Partida aplazada: continúa desde la biblioteca",
"Partita rinviata: riprendila dalla biblioteca",
"Partida adiada: continue pela biblioteca",
"O‘yin keyinga qoldirildi: kutubxonadan davom ettiring",
"Ойын кейінге қалдырылды: кітапханадан жалғастырыңыз",
],
[
"The opponent of this game is not installed",
"Соперник этой партии не установлен",
"L'adversaire de cette partie n'est pas installé",
"Der Gegner dieser Partie ist nicht installiert",
"El rival de esta partida no está instalado",
"L'avversario di questa partita non è installato",
"O adversário desta partida não está instalado",
"Bu o‘yinning raqibi o‘rnatilmagan",
"Бұл ойынның қарсыласы орнатылмаған",
],
[
"Game put aside",
"Отложенная партия",
"Partie ajournée",
"Vertagte Partie",
"Partida aplazada",
"Partita rinviata",
"Partida adiada",
"Keyinga qoldirilgan o‘yin",
"Кейінге қалдырылған ойын",
],
];
#[cfg(test)]

View file

@ -40,6 +40,9 @@ pub enum LibraryAction {
NewGame,
/// A game against Maia: the play dialog.
Play,
/// The game put aside: go on with it, or let it go (adjourned.rs).
ResumeAside,
DiscardAside,
/// A new game meant for this database (the table's «+ Game»): Ctrl+S adds it there.
NewGameIn(PathBuf),
PastePgn,
@ -134,6 +137,15 @@ fn shelf_buttons_w(ui: &Ui, update: Option<&str>, icons: bool) -> f32 {
}
/// A shelf button's tooltip: with icons only, its name first.
/// What was pressed on the card of a game put aside, as the library's action.
fn push_pressed(p: Option<crate::adjourned::Pressed>, actions: &mut Vec<LibraryAction>) {
match p {
Some(crate::adjourned::Pressed::Continue) => actions.push(LibraryAction::ResumeAside),
Some(crate::adjourned::Pressed::Discard) => actions.push(LibraryAction::DiscardAside),
None => {}
}
}
fn shelf_hint(icons: bool, full: &str, hint: &str) -> String {
if icons {
format!(
@ -198,6 +210,8 @@ pub struct Library {
pub online_running: Option<usize>,
/// A newer version to offer (its number), next to Settings.
pub update: Option<String>,
/// The card of the game put aside, on the shelf.
pub aside: Option<crate::adjourned::Card>,
}
impl Library {
@ -216,6 +230,7 @@ impl Library {
online_busy: Vec::new(),
online_running: None,
update: None,
aside: None,
}
}
@ -489,12 +504,20 @@ impl Library {
.is_some_and(|p| self.large.get(p).is_some_and(|v| v.pane() == Pane::Board));
// The shelf's rows hold the databases only (their actions are in the title row).
let cards = databases.len();
// The card of a game put aside stands right of the databases (they wrap beside
// it), or above them when not even one fits beside it.
let cards_width = match &self.aside {
Some(card) if width - 16.0 - card.width(ui) - 24.0 >= 190.0 => {
width - card.width(ui) - 24.0
}
_ => width,
};
let card_rows = {
let mut rows = 1;
let mut x = 0.0;
for _ in 0..cards {
let w = 190.0;
if x > 0.0 && x + w > width - 16.0 {
if x > 0.0 && x + w > cards_width - 16.0 {
rows += 1;
x = 0.0;
}
@ -503,10 +526,12 @@ impl Library {
rows
};
if card_rows > 2 || height < 600.0 || (board_open && height < 760.0) {
egui::Panel::top("shelf_compact")
.show(ui, |ui| self.compact_shelf(ui, databases, &mut actions));
egui::Panel::top("shelf_compact").show(ui, |ui| {
self.compact_shelf(ui, databases, settings, &mut actions)
});
} else {
egui::Panel::top("shelf").show(ui, |ui| self.shelf(ui, databases, &mut actions));
egui::Panel::top("shelf")
.show(ui, |ui| self.shelf(ui, databases, settings, &mut actions));
}
// A database has its filter panel or its search board on the right, when the
// window leaves the table its least width beside them (narrow-windows.md §2.1);
@ -641,6 +666,7 @@ impl Library {
&mut self,
ui: &mut Ui,
databases: &[PathBuf],
settings: &Settings,
actions: &mut Vec<LibraryAction>,
) {
let name = |p: &Path| {
@ -686,6 +712,12 @@ impl Library {
self.app_buttons(ui, icons, actions);
});
});
// The game put aside: a strip under the line.
if let Some(card) = &self.aside {
ui.add_space(4.0);
push_pressed(card.strip(ui, settings), actions);
ui.add_space(4.0);
}
}
/// "⚙ Settings" and the newer version (right to left): the program's corner, the
@ -758,7 +790,13 @@ impl Library {
}
}
fn shelf(&mut self, ui: &mut Ui, databases: &[PathBuf], actions: &mut Vec<LibraryAction>) {
fn shelf(
&mut self,
ui: &mut Ui,
databases: &[PathBuf],
settings: &Settings,
actions: &mut Vec<LibraryAction>,
) {
ui.add_space(8.0);
// The title row (library-layout.md §1.4): «Databases», then what to put in — the
// game ones first (used daily), then, apart, the database actions; the program's
@ -791,15 +829,38 @@ impl Library {
self.app_buttons(ui, icons, actions);
});
});
if !databases.is_empty() {
let card = self.aside.take();
let card_w = card.as_ref().map_or(0.0, |c| c.width(ui));
let width = ui.available_width();
let beside = card.is_some() && width - card_w - 24.0 >= 190.0;
// Not even one database beside it: the card has a row of its own, above them.
if let Some(c) = card.as_ref().filter(|_| !beside) {
ui.add_space(4.0);
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(8.0, 8.0);
for path in databases {
self.db_card(ui, path, actions);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
push_pressed(c.show(ui, card_w, settings), actions);
});
}
if !databases.is_empty() || beside {
ui.add_space(4.0);
ui.horizontal_top(|ui| {
let dbs_w = if beside { width - card_w - 24.0 } else { width };
ui.allocate_ui(vec2(dbs_w, 0.0), |ui| {
ui.set_max_width(dbs_w);
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(8.0, 8.0);
for path in databases {
self.db_card(ui, path, actions);
}
});
});
if let Some(c) = card.as_ref().filter(|_| beside) {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
push_pressed(c.show(ui, card_w, settings), actions);
});
}
});
}
self.aside = card;
ui.add_space(8.0);
}

View file

@ -1,6 +1,7 @@
// No console window for release builds on Windows.
#![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")]
mod adjourned;
mod analysis;
mod app;
mod assets;

View file

@ -720,6 +720,25 @@ impl Clock {
}
}
/// A clock going on from a game put aside: the time each side had left, whether it
/// has moved (its first move is free), the side to move's clock running from `now`.
pub fn resumed(
control: TimeControl,
left: [Option<Duration>; 2],
to_move: Color,
now: Instant,
) -> Clock {
let mut c = Clock::new(control);
for side in [Color::White, Color::Black] {
if let Some(d) = left[idx(side)] {
c.left[idx(side)] = d;
c.moved[idx(side)] = true;
}
}
c.running = Some((to_move, now));
c
}
/// The time left of `c` at `now`.
pub fn left(&self, c: Color, now: Instant) -> Duration {
let base = self.left[idx(c)];
@ -802,6 +821,59 @@ pub fn clk_command(d: Duration) -> String {
format!("[%clk {}:{:02}:{:02}]", s / 3600, s / 60 % 60, s % 60)
}
/// The time each side had left in a game put aside (white, black; `None`: it has not
/// moved): the `[%clk]` of its last move among those played after `floor` half-moves;
/// the side to move's `to_move` when it is known (its time when the game was put aside).
pub fn times_left(
game: &chess_core::Game,
floor: usize,
to_move: Option<Duration>,
) -> [Option<Duration>; 2] {
let mut left = [None, None];
let line = game.mainline();
for &id in line.iter().skip(floor) {
let mover = game.position_before(id).map(|p| p.turn());
let clk = game
.node(id)
.and_then(|n| n.comments_after().iter().find_map(|c| clk_of(c)));
if let (Some(m), Some(t)) = (mover, clk) {
left[idx(m)] = Some(t);
}
}
let end = line.last().copied().unwrap_or(chess_core::NodeId::ROOT);
if let (Some(t), Some(p)) = (to_move, game.position(end)) {
left[idx(p.turn())] = Some(t);
}
left
}
/// The game of a PGN text (a journal's: one game, UTF-8).
pub fn parse_game(pgn: &str) -> Option<chess_core::Game> {
let never = std::sync::atomic::AtomicBool::new(false);
let db = chess_core::PgnDatabase::from_bytes(
pgn.as_bytes().to_vec(),
Some(chess_core::TextEncoding::Utf8),
&mut |_| {},
&never,
)
.ok()?;
db.load_game(0).map(|p| p.game)
}
/// The time a `[%clk h:mm:ss]` of a comment says.
pub fn clk_of(comment: &str) -> Option<Duration> {
// The PGN writer may break the line after «[%clk».
let rest = &comment[comment.find("[%clk")? + 5..];
let text = &rest[..rest.find(']')?];
let mut secs = 0u64;
for part in text.trim().split(':') {
// Seconds may have a fraction («0:03:12.4»): whole ones are enough.
let whole = part.split('.').next()?.parse::<u64>().ok()?;
secs = secs * 60 + whole;
}
Some(Duration::from_secs(secs))
}
// ----- Maia's moves -------------------------------------------------------------------
/// A request for a move: the positions up to now, the ratings, the pause.
@ -1039,6 +1111,62 @@ mod tests {
use super::*;
use chess_core::shakmaty::uci::UciMove;
#[test]
fn the_time_of_a_clk_comment() {
assert_eq!(clk_of("[%clk 0:03:12]"), Some(Duration::from_secs(192)));
assert_eq!(
clk_of("Good move [%clk 1:00:05.3] [%cal Ge2e4]"),
Some(Duration::from_secs(3605))
);
assert_eq!(
clk_of(&clk_command(Duration::from_secs(4321))),
Some(Duration::from_secs(4321))
);
assert_eq!(clk_of("[%clk\n0:04:11]"), Some(Duration::from_secs(251)));
assert_eq!(clk_of("no clock"), None);
}
#[test]
fn a_clock_goes_on_from_the_times_left() {
let now = Instant::now();
let tc = TimeControl {
base: 300,
increment: 3,
};
let c = Clock::resumed(
tc,
[Some(Duration::from_secs(250)), None],
Color::Black,
now,
);
assert_eq!(c.left(Color::White, now), Duration::from_secs(250));
// Black has not moved: its first move is free, its time the base.
assert_eq!(
c.left(Color::Black, now + Duration::from_secs(9)),
Duration::from_secs(300)
);
assert_eq!(c.running(), None);
// Both have moved: the side to move's clock runs from the moment it goes on.
let c = Clock::resumed(
tc,
[
Some(Duration::from_secs(250)),
Some(Duration::from_secs(200)),
],
Color::White,
now,
);
assert_eq!(c.running(), Some(Color::White));
assert_eq!(
c.left(Color::White, now + Duration::from_secs(10)),
Duration::from_secs(240)
);
assert_eq!(
c.left(Color::Black, now + Duration::from_secs(10)),
Duration::from_secs(200)
);
}
#[test]
fn speeds_as_lichess() {
let s = |base, increment| TimeControl { base, increment }.speed();
@ -1202,6 +1330,51 @@ pub struct Session {
pub floor: chess_core::NodeId,
}
/// What a game against the computer is played with, kept in its journal so that it can
/// go on later (a game put aside, docs/design/desktop-adjourned.md).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Saved {
pub white: bool,
pub strength: u32,
pub rival: Rival,
pub style: String,
pub user_elo: Option<u32>,
pub user_name: String,
pub clock: Option<TimeControl>,
/// Half-moves of the game it went on from (not played here: not taken back).
pub floor: usize,
/// That game and its move, as the note and a rematch name them.
pub from_game: Option<String>,
pub from_after: Option<String>,
pub from_after_shown: Option<String>,
}
impl Saved {
/// The start of the game again, with the position it went on from (rebuilt from the
/// game itself) for a rematch.
pub fn start(&self, from: Option<StartFrom>) -> Start {
Start {
user: if self.white {
Color::White
} else {
Color::Black
},
strength: self.strength,
rival: self.rival,
style: self.style.clone(),
user_elo: self.user_elo,
user_name: self.user_name.clone(),
clock: self.clock,
from: from.map(|mut f| {
f.game = self.from_game.clone();
f.after = self.from_after.clone();
f.after_shown = self.from_after_shown.clone();
Box::new(f)
}),
}
}
}
/// What the play dialog starts.
#[derive(Clone, Debug)]
pub struct Start {
@ -1218,6 +1391,23 @@ pub struct Start {
}
impl Start {
/// What the game is played with, for its journal; `floor`: half-moves it went on from.
pub fn saved(&self, floor: usize) -> Saved {
Saved {
white: self.user == Color::White,
strength: self.strength,
rival: self.rival,
style: self.style.clone(),
user_elo: self.user_elo,
user_name: self.user_name.clone(),
clock: self.clock,
floor,
from_game: self.from.as_ref().and_then(|f| f.game.clone()),
from_after: self.from.as_ref().and_then(|f| f.after.clone()),
from_after_shown: self.from.as_ref().and_then(|f| f.after_shown.clone()),
}
}
/// The opponent as the game names it: «Maia 1500», «Rodent V 2400 (Tal)».
pub fn rival_name(&self) -> String {
rival_name(self.rival, self.strength, &self.style)
@ -2145,6 +2335,108 @@ fn position_block(
});
}
/// The opponent of a game put aside, downloaded so that the game can go on (it was
/// removed meanwhile): the same files and words as in the play dialog.
pub enum Fetch {
Maia(crate::maia_download::Download),
Rodent(crate::engine_download::Download),
}
/// How a `Fetch` goes.
#[derive(PartialEq)]
pub enum Fetched {
Going,
Done,
Failed,
}
impl Fetch {
pub fn start(saved: &Saved, ctx: &egui::Context) -> Fetch {
match saved.rival {
Rival::Maia => Fetch::Maia(crate::maia_download::Download::start(
ctx,
model_for().err().unwrap_or(Model::Large),
)),
Rival::Rodent => Fetch::Rodent(style(&saved.style).rodent.start(ctx)),
}
}
/// What is downloaded, said before it is.
pub fn note(saved: &Saved) -> String {
match saved.rival {
Rival::Maia => download_note(model_for().err()),
Rival::Rodent => {
let which = style(&saved.style).rodent;
let mb = which.size_mb();
match which {
Gen::V => crate::i18n::trf(
"Rodent V is downloaded once ({mb} MB, from github.com, the authors' own file).",
&[("mb", &mb)],
),
Gen::IV => crate::i18n::trf(
"Rodent IV is downloaded once ({mb} MB): the engine built from its authors' sources, its characters and books from their repository.",
&[("mb", &mb)],
),
}
}
}
}
/// Its progress, or why it failed.
pub fn show(&self, ui: &mut egui::Ui) -> Fetched {
use crate::engine_download::Stage as R;
use crate::maia_download::Stage as M;
let failed = |ui: &mut egui::Ui, text: String| {
ui.label(egui::RichText::new(text).color(ui.visuals().error_fg_color));
Fetched::Failed
};
match self {
Fetch::Maia(d) => match d.stage() {
M::Downloading { done } => {
ui.add(
egui::ProgressBar::new(done as f32 / d.model.size() as f32)
.show_percentage(),
);
Fetched::Going
}
M::Checking => {
ui.horizontal(|ui| {
ui.add(egui::Spinner::new());
ui.label(tr("Checking…"));
});
Fetched::Going
}
M::Done(_) => Fetched::Done,
M::Failed(e) => failed(ui, e),
},
Fetch::Rodent(d) => match d.stage() {
R::Downloading { done, total } => {
ui.add(
egui::ProgressBar::new(done as f32 / total.max(1) as f32).show_percentage(),
);
Fetched::Going
}
R::Unpacking => {
ui.horizontal(|ui| {
ui.add(egui::Spinner::new());
ui.label(tr("Unpacking…"));
});
Fetched::Going
}
R::Done(_) => Fetched::Done,
R::Failed(f) => failed(
ui,
crate::i18n::trf(
"Could not download Rodent: {error}",
&[("error", &download_failure(&f))],
),
),
R::Cancelled => Fetched::Failed,
},
}
}
}
/// Why Rodent's download failed, in words.
fn download_failure(f: &crate::engine_download::Failure) -> String {
use crate::engine_download::Failure as F;

View file

@ -164,7 +164,9 @@ pub fn write(path: &Path, pgn: &str) -> Result<Written, String> {
/// What the journal keeps of a game being played.
#[derive(Serialize, Deserialize)]
struct Entry {
target: PathBuf,
/// The player's database (`None`: games are not written, the journal is only for
/// going on with it).
target: Option<PathBuf>,
/// Whose game it is: the player is linked to the database when it is written.
#[serde(default)]
player: String,
@ -172,6 +174,27 @@ struct Entry {
/// 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>,
/// What the game is played with (the opponent, the clock…): it can go on from here.
/// None in journals of older versions: their games are only written.
#[serde(default)]
game: Option<crate::play::Saved>,
/// Put aside on purpose (not left by a crash).
#[serde(default)]
aside: bool,
/// The side to move's time left when it was put aside, in milliseconds (its last
/// `[%clk]` does not count the time it thought since).
#[serde(default)]
to_move_left_ms: Option<u64>,
/// When the game was last played (seconds since 1970): the newest of several put
/// aside is the one offered. Older journals: the file's time.
#[serde(default)]
played_at: Option<u64>,
}
fn now_secs() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
/// The folder of the journals.
@ -180,22 +203,29 @@ fn journal_dir() -> Option<PathBuf> {
}
/// 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).
/// held while it is played (a journal whose lock is free is a game put aside, or one a
/// crash left).
pub struct Journal {
lock: Option<(File, PathBuf)>,
path: PathBuf,
target: PathBuf,
target: Option<PathBuf>,
player: String,
game: Option<crate::play::Saved>,
}
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)
pub fn new(target: Option<PathBuf>, player: &str, game: crate::play::Saved) -> Self {
Self::in_dir(journal_dir(), target, player, Some(game))
}
fn in_dir(dir: Option<PathBuf>, target: PathBuf, player: &str) -> Self {
fn in_dir(
dir: Option<PathBuf>,
target: Option<PathBuf>,
player: &str,
game: Option<crate::play::Saved>,
) -> Self {
let made = dir.and_then(|dir| {
std::fs::create_dir_all(&dir).ok()?;
let stamp = std::time::SystemTime::now()
@ -216,11 +246,13 @@ impl Journal {
path,
target,
player: tidy(player),
game,
}
}
pub fn target(&self) -> &Path {
&self.target
/// Where the game goes when it ends (`None`: it is not written).
pub fn target(&self) -> Option<&Path> {
self.target.as_deref()
}
fn put(&self, pgn: &str, before: Option<u64>) {
@ -232,6 +264,10 @@ impl Journal {
player: self.player.clone(),
pgn: pgn.to_owned(),
before,
game: self.game.clone(),
aside: false,
to_move_left_ms: None,
played_at: Some(now_secs()),
};
if let Ok(json) = serde_json::to_vec(&entry) {
let _ = crate::settings::write_atomic(&self.path, &json);
@ -245,10 +281,50 @@ impl Journal {
/// 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());
/// `None`: the game is not written (no database for it).
pub fn finish(&self, pgn: &str) -> Option<Result<Written, String>> {
let target = self.target.as_ref()?;
let before = std::fs::metadata(target).map_or(0, |m| m.len());
self.put(pgn, Some(before));
write(&self.target, pgn)
Some(write(target, pgn))
}
/// Whether the game can be put aside: its journal is kept on disk.
pub fn can_put_aside(&self) -> bool {
self.lock.is_some() && self.game.is_some()
}
/// The game is put aside as `pgn`: its journal stays (still ours; after the program
/// stops, the next start finds it as a crash leaves one). `None`: there was no
/// journal (its folder could not be made) or it is not a game that can go on.
/// `to_move_left`: the side to move's time left now (with a clock).
pub fn put_aside(
mut self,
pgn: &str,
to_move_left: Option<std::time::Duration>,
) -> Option<PutAside> {
let game = self.game.take()?;
let (lock, lock_path) = self.lock.take()?;
let entry = Entry {
target: self.target.take(),
player: std::mem::take(&mut self.player),
pgn: pgn.to_owned(),
before: None,
game: Some(game),
aside: true,
to_move_left_ms: to_move_left.map(|d| d.as_millis() as u64),
played_at: Some(now_secs()),
};
if let Ok(json) = serde_json::to_vec(&entry) {
let _ = crate::settings::write_atomic(&self.path, &json);
}
Some(PutAside {
lock,
lock_path,
path: std::mem::take(&mut self.path),
entry,
when: std::time::SystemTime::now(),
})
}
}
@ -267,19 +343,126 @@ pub struct Recovered {
pub player: String,
pub target: PathBuf,
pub written: Result<Written, String>,
/// A game put aside on purpose (not one a crash left).
pub put_aside: bool,
}
/// 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> {
/// A game put aside (or left by a crash) that can go on: its journal, locked by us now.
pub struct PutAside {
lock: File,
lock_path: PathBuf,
path: PathBuf,
entry: Entry,
/// When it was last written (the newest is the one offered).
when: std::time::SystemTime,
}
impl PutAside {
pub fn pgn(&self) -> &str {
&self.entry.pgn
}
pub fn game(&self) -> &crate::play::Saved {
self.entry
.game
.as_ref()
.expect("a game put aside has its settings")
}
/// Left by a crash, not put aside on purpose.
pub fn crashed(&self) -> bool {
!self.entry.aside
}
/// The side to move's time left when it was put aside.
pub fn to_move_left(&self) -> Option<std::time::Duration> {
self.entry
.to_move_left_ms
.map(std::time::Duration::from_millis)
}
/// Where it goes when it ends (`None`: not written).
pub fn target(&self) -> Option<&Path> {
self.entry.target.as_deref()
}
/// When it was put aside (its journal last written).
pub fn when(&self) -> std::time::SystemTime {
self.when
}
/// Goes on with the game: the same journal, kept on.
pub fn resume(self) -> Journal {
Journal {
lock: Some((self.lock, self.lock_path)),
path: self.path,
target: self.entry.target,
player: self.entry.player,
game: self.entry.game,
}
}
/// The crash that left it was said: from now on it is a game put aside.
pub fn crash_said(&mut self) {
self.entry.aside = true;
self.store();
}
/// Lets the game go: written into its player's database unfinished (it is a game
/// that was played), then the journal goes. `Ok(None)`: games are not written: it
/// is only deleted. `Err`: it could not be written: it stays put aside, as it was.
pub fn discard(mut self) -> Result<Option<Recovered>, Box<(Recovered, PutAside)>> {
let Some(target) = self.entry.target.clone() else {
self.remove();
return Ok(None);
};
// The database's size first: a crash right after the write does not write it
// again (the next start sees the file grown).
self.entry.before = Some(std::fs::metadata(&target).map_or(0, |m| m.len()));
self.store();
let r = Recovered {
written: write(&target, &self.entry.pgn),
player: self.entry.player.clone(),
target,
put_aside: self.entry.aside,
};
if r.written.is_ok() {
self.remove();
Ok(Some(r))
} else {
self.entry.before = None;
self.store();
Err(Box::new((r, self)))
}
}
fn store(&self) {
if let Ok(json) = serde_json::to_vec(&self.entry) {
let _ = crate::settings::write_atomic(&self.path, &json);
}
}
/// Its journal goes.
fn remove(self) {
let _ = std::fs::remove_file(&self.path);
drop(self.lock);
let _ = std::fs::remove_file(&self.lock_path);
}
}
/// The journals no program plays now (their lock is free): the newest game that can go
/// on is put aside; finished games a crash kept from their database, games of older
/// versions and other games left are written into their databases now.
pub fn recover() -> (Vec<Recovered>, Option<PutAside>) {
journal_dir().map(|d| recover_in(&d)).unwrap_or_default()
}
fn recover_in(dir: &Path) -> Vec<Recovered> {
fn recover_in(dir: &Path) -> (Vec<Recovered>, Option<PutAside>) {
let Ok(read) = std::fs::read_dir(dir) else {
return Vec::new();
return (Vec::new(), None);
};
let mut out = Vec::new();
let mut written = Vec::new();
let mut aside: Vec<PutAside> = Vec::new();
for lock_path in read.flatten().map(|e| e.path()) {
if lock_path.extension().is_none_or(|e| e != "lock") {
continue;
@ -291,27 +474,75 @@ fn recover_in(dir: &Path) -> Vec<Recovered> {
continue; // a program running now plays it
}
let path = lock_path.with_extension("json");
if let Some(entry) = std::fs::read(&path)
let read = 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,
});
.and_then(|b| serde_json::from_slice::<Entry>(&b).ok());
let file_time = || {
std::fs::metadata(&path)
.and_then(|m| m.modified())
.unwrap_or(std::time::UNIX_EPOCH)
};
let when = match read.as_ref().and_then(|e| e.played_at) {
Some(t) => std::time::UNIX_EPOCH + std::time::Duration::from_secs(t),
None => file_time(),
};
match read {
// Over, or of an older version: it goes into its database (once).
Some(entry) if entry.before.is_some() || entry.game.is_none() => {
if let Some(target) = entry.target {
// The write had been made (the file grew since): not again.
let done = entry
.before
.is_some_and(|b| std::fs::metadata(&target).is_ok_and(|m| m.len() > b));
if !done {
let r = Recovered {
written: write(&target, &entry.pgn),
player: entry.player,
target,
put_aside: false,
};
let failed = r.written.is_err();
written.push(r);
// Not written: its journal stays for the next start.
if failed {
continue;
}
}
}
}
Some(entry) => {
aside.push(PutAside {
lock,
lock_path,
path,
entry,
when,
});
continue;
}
// A journal that cannot be read is kept aside, said in the log.
None if path.exists() => {
eprintln!("play journal unreadable, kept as .bad: {}", path.display());
let _ = std::fs::rename(&path, path.with_extension("json.bad"));
}
None => {}
}
let _ = std::fs::remove_file(&path);
drop(lock);
let _ = std::fs::remove_file(&lock_path);
}
out
// One game put aside at a time: the newest; any other is written unfinished.
aside.sort_by_key(|a| std::cmp::Reverse(a.when));
let mut rest = aside.into_iter();
let kept = rest.next();
for a in rest {
match a.discard() {
Ok(r) => written.extend(r),
// Not written: it stays for the next start (its lock let go).
Err(b) => written.push(b.0),
}
}
(written, kept)
}
#[cfg(test)]
@ -375,6 +606,7 @@ mod tests {
/// starting a process holds a copy of a lock for a moment (the child gets the parent's
/// files until it runs its program); recovery then leaves that journal for later.
fn recover_until(dir: &Path, live: usize) -> Vec<Recovered> {
let recover_in = |d: &Path| recover_in(d).0;
let locks = || {
std::fs::read_dir(dir)
.map(|r| {
@ -395,6 +627,80 @@ mod tests {
out
}
#[test]
fn a_game_put_aside_goes_on_or_is_written_unfinished() {
let dir = std::env::temp_dir().join(format!("cp-aside-{}", 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. e4 e5 *\n";
let saved = crate::play::Saved {
white: true,
strength: 1500,
rival: crate::play::Rival::Maia,
style: String::new(),
user_elo: None,
user_name: "Роман".into(),
clock: Some(crate::play::TimeControl {
base: 300,
increment: 3,
}),
floor: 0,
from_game: None,
from_after: None,
from_after_shown: None,
};
let j = Journal::in_dir(
Some(journals.clone()),
Some(db.clone()),
"Роман",
Some(saved.clone()),
);
let aside = j.put_aside(game, None).unwrap();
assert_eq!(aside.game(), &saved);
assert!(!aside.crashed());
// The program stops: the next start finds it put aside, not written.
drop(aside);
let (written, found) = recover_in(&journals);
assert!(written.is_empty());
let found = found.unwrap();
assert_eq!(found.pgn(), game);
// It goes on with the same journal; put aside again and let go: written.
let j = found.resume();
let aside = j
.put_aside(game, Some(std::time::Duration::from_secs(61)))
.unwrap();
assert_eq!(
aside.to_move_left(),
Some(std::time::Duration::from_secs(61))
);
let r = aside.discard().ok().flatten().unwrap();
assert_eq!(r.written.map(|w| w.index), Ok(0));
assert_eq!(std::fs::read_dir(&journals).unwrap().count(), 0);
// A database that cannot be written (a folder of its name): the game is not
// lost, it stays put aside, at the next start too.
let bad = dir.join("bad.pgn");
std::fs::create_dir_all(&bad).unwrap();
let j = Journal::in_dir(
Some(journals.clone()),
Some(bad.clone()),
"Роман",
Some(saved.clone()),
);
let aside = j.put_aside(game, None).unwrap();
let Err(b) = aside.discard() else {
panic!("written into a folder")
};
let (r, aside) = *b;
assert!(r.written.is_err());
assert_eq!(aside.pgn(), game);
drop(aside);
let (written, found) = recover_in(&journals);
assert!(written.is_empty());
assert_eq!(found.map(|a| a.pgn().to_owned()), Some(game.to_owned()));
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()));
@ -403,21 +709,21 @@ mod tests {
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(), "Роман");
let j = Journal::in_dir(Some(journals.clone()), Some(db.clone()), "Роман", None);
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"), "");
let live = Journal::in_dir(Some(journals.clone()), Some(dir.join("live.pgn")), "", None);
live.save(game);
let got = recover_until(&journals, 1);
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());
assert!(recover_in(&journals).0.is_empty());
// Crashed right after the write: not written again.
let j = Journal::in_dir(Some(journals.clone()), db.clone(), "Роман");
let j = Journal::in_dir(Some(journals.clone()), Some(db.clone()), "Роман", None);
let before = std::fs::metadata(&db).unwrap().len();
j.put(game, Some(before));
write(&db, game).unwrap();