diff --git a/CHANGELOG.md b/CHANGELOG.md index 350fa8d..0861fc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https ## [Unreleased] +- Desktop: the database cards show how many games each holds instead of «not loaded»: + the databases are counted in the background, one after another, and the counts are + remembered for the next start (a changed file is counted again). +- Desktop, the play dialog: the strength rides above the slider's handle, where the eye + is while it moves. +- Desktop, a game against the computer: the buttons under the clocks are of one height; + the moves and the board flip on one row, the game's own actions on the next. + ## [1.9.3] — 2026-10-27 - Android: «About» no longer calls the app an alpha, says what it does now (chess diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 76ec020..a7a7026 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -358,7 +358,7 @@ impl App { let _ = settings.save(); } let (tx, rx) = channel(); - let mut library = Library::new(); + let mut library = Library::new(ctx); // Read in the background: a missing file says so there (a lost network drive // does not hold the start). if let Some(first) = settings.databases.first() { diff --git a/apps/desktop/src/db_counts.rs b/apps/desktop/src/db_counts.rs new file mode 100644 index 0000000..3209a42 --- /dev/null +++ b/apps/desktop/src/db_counts.rs @@ -0,0 +1,212 @@ +//! How many games each database on the shelf holds before it is opened: «not loaded» +//! on a card told the user nothing. A thread of its own counts the databases one after +//! another (reading a large one takes seconds; the screen never waits) and remembers the +//! counts with the file's size and time, so the next start shows them at once. A card +//! whose database is not counted yet says nothing. + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; +use std::sync::mpsc::{Sender, channel}; +use std::sync::{Arc, Mutex}; +use std::time::UNIX_EPOCH; + +use chess_import::Database; +use serde::{Deserialize, Serialize}; + +/// What a card says of a database: its games and whether it is a ChessBase one read in +/// place (a lock: it cannot take games). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Count { + pub games: usize, + pub locked: bool, +} + +impl Count { + pub fn of(db: &Database) -> Count { + match db.as_chessbase() { + Some(b) => Count { + games: b.games() + b.texts(), + locked: true, + }, + None => Count { + games: db.len(), + locked: false, + }, + } + } +} + +/// A count and the file it was taken from. +#[derive(Clone, Copy, Serialize, Deserialize)] +struct Entry { + size: u64, + modified: u64, + count: Count, +} + +enum Job { + /// Count the file, unless the count remembered is of the file as it is. + Count(PathBuf), + /// The database was opened: its count, nothing to read. + Known(PathBuf, Count), +} + +#[derive(Default)] +struct Shared { + known: HashMap, +} + +pub struct Counts { + shared: Arc>, + asked: HashSet, + jobs: Option>, +} + +impl Counts { + pub fn new(ctx: &egui::Context) -> Self { + let file = crate::settings::Settings::cache_dir().map(|d| d.join("database-counts.json")); + Self::kept_in(file, ctx) + } + + /// Counts remembered in `file` (`None`: for this run only). + fn kept_in(file: Option, ctx: &egui::Context) -> Self { + let known: HashMap = file + .as_ref() + .and_then(|f| std::fs::read(f).ok()) + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default(); + let shared = Arc::new(Mutex::new(Shared { known })); + let (tx, rx) = channel::(); + let (worker, ctx) = (shared.clone(), ctx.clone()); + let spawned = std::thread::Builder::new() + .name("db-counts".into()) + .spawn(move || { + let never = AtomicBool::new(false); + for job in rx { + let (path, known) = match job { + Job::Count(p) => (p, None), + Job::Known(p, c) => (p, Some(c)), + }; + let Some((size, modified)) = stamp(&path) else { + continue; + }; + let fresh = worker.lock().ok().and_then(|s| { + s.known + .get(&path) + .filter(|e| e.size == size && e.modified == modified) + .map(|e| e.count) + }); + let count = match known { + Some(c) if fresh == Some(c) => continue, + Some(c) => c, + None if fresh.is_some() => continue, + None => match chess_import::open(&path, &mut |_| {}, &never) { + Ok(o) => Count::of(&o.db), + // The card says why when the database is opened. + Err(_) => continue, + }, + }; + let json = match worker.lock() { + Ok(mut s) => { + s.known.insert( + path, + Entry { + size, + modified, + count, + }, + ); + serde_json::to_vec(&s.known).ok() + } + Err(_) => return, + }; + if let (Some(f), Some(json)) = (&file, json) { + if let Some(dir) = f.parent() { + let _ = std::fs::create_dir_all(dir); + } + let _ = crate::settings::write_atomic(f, &json); + } + ctx.request_repaint(); + } + }); + Self { + shared, + asked: HashSet::new(), + jobs: spawned.ok().map(|_| tx), + } + } + + /// The games of a database not opened yet (`None`: not counted yet); it is counted + /// from now on. + pub fn get(&mut self, path: &Path) -> Option { + if self.asked.insert(path.to_owned()) + && let Some(jobs) = &self.jobs + { + let _ = jobs.send(Job::Count(path.to_owned())); + } + self.shared.lock().ok()?.known.get(path).map(|e| e.count) + } + + /// A database was opened: its count is remembered for the next start. + pub fn opened(&mut self, path: &Path, db: &Database) { + self.asked.insert(path.to_owned()); + if let Some(jobs) = &self.jobs { + let _ = jobs.send(Job::Known(path.to_owned(), Count::of(db))); + } + } +} + +/// The file's size and time (seconds since the epoch); a changed file is counted again. +fn stamp(path: &Path) -> Option<(u64, u64)> { + let m = std::fs::metadata(path).ok()?; + let modified = m + .modified() + .ok()? + .duration_since(UNIX_EPOCH) + .ok()? + .as_secs(); + Some((m.len(), modified)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{Duration, Instant}; + + fn wait(counts: &mut Counts, path: &Path, want: usize) -> bool { + let deadline = Instant::now() + Duration::from_secs(5); + while Instant::now() < deadline { + if counts.get(path).map(|c| c.games) == Some(want) { + return true; + } + std::thread::sleep(Duration::from_millis(20)); + } + false + } + + #[test] + fn a_database_is_counted_away_from_the_screen_and_again_when_it_changes() { + let dir = std::env::temp_dir().join(format!("cp-db-counts-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let pgn = dir.join("a.pgn"); + std::fs::write( + &pgn, + "[White \"A\"]\n\n1. e4 *\n\n[White \"B\"]\n\n1. d4 *\n", + ) + .unwrap(); + let mut counts = Counts::kept_in(None, &egui::Context::default()); + // Asked: nothing known yet, nothing waited for. + assert_eq!(counts.get(&pgn), None); + assert!(wait(&mut counts, &pgn, 2)); + // An opened database tells its count; a changed file is counted anew. + std::fs::write(&pgn, "[White \"A\"]\n\n1. e4 *\n").unwrap(); + let db = chess_import::open(&pgn, &mut |_| {}, &AtomicBool::new(false)) + .unwrap() + .db; + counts.opened(&pgn, &db); + assert!(wait(&mut counts, &pgn, 1)); + assert!(!counts.get(&pgn).unwrap().locked); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 7a42cab..d24a3bd 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -3420,33 +3420,35 @@ impl GameView { /// moves). fn play_toolbar(&mut self, ui: &mut Ui, actions: &mut Vec) { ui.add_space(4.0); + // Every button of one height; the moves and the board on one row, the game's own + // actions on the next (a row wrapping in the middle of a group looks broken). + const H: f32 = 28.0; + let icon = |s: &str| egui::Button::new(RichText::new(s).size(18.0)).min_size(vec2(0.0, H)); + let word = |s: &str| egui::Button::new(RichText::new(s).size(14.0)).min_size(vec2(0.0, H)); ui.horizontal_wrapped(|ui| { - let big = |s: &str| RichText::new(s).size(18.0); - // The words as tall as the icon buttons beside them. - let word = - |s: &str| egui::Button::new(RichText::new(s).size(14.0)).min_size(vec2(0.0, 28.0)); - if ui.button(big("⏮")).clicked() { + if ui.add(icon("⏮")).clicked() { self.goto(NodeId::ROOT); } - if ui.button(big("◀")).clicked() { + if ui.add(icon("◀")).clicked() { self.step_back(); } - if ui.button(big("▶")).clicked() { + if ui.add(icon("▶")).clicked() { self.step_forward(actions); } - if ui.button(big("⏭")).clicked() { + if ui.add(icon("⏭")).clicked() { let end = self.play_end_node(); self.goto(end); } ui.separator(); if ui - .button(big("🔃")) + .add(icon("🔃")) .on_hover_text(tr("Flip board (F)")) .clicked() { self.flipped = !self.flipped; } - ui.separator(); + }); + ui.horizontal_wrapped(|ui| { let user = self.play.as_ref().map_or(Color::White, |s| s.user); let user_moved = self.user_moved(user); if self.take_back_offered() @@ -3534,8 +3536,7 @@ 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. + // it is its icon (the words in its tooltip). let hint = format!( "{}\n{}", tr("⏸ Put aside"), @@ -3548,14 +3549,9 @@ impl GameView { .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 full = room >= w(tr("⏸ Put aside")); let label = if full { tr("⏸ Put aside") } else { "⏸" }; if ui .add(word(label)) diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 4578170..48b3af1 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -7102,17 +7102,6 @@ const ROWS: &[[&str; 9]] = &[ "fayl topilmadi", "файл табылмады", ], - [ - "not loaded", - "не загружена", - "non chargée", - "nicht geladen", - "no cargada", - "non caricato", - "não carregada", - "yuklanmagan", - "жүктелмеген", - ], [ "Reload file", "Перечитать файл", diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index cf63389..ff7db1f 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -212,10 +212,12 @@ pub struct Library { pub update: Option, /// The card of the game put aside, on the shelf. pub aside: Option, + /// The games of the databases not opened, for their cards. + counts: crate::db_counts::Counts, } impl Library { - pub fn new() -> Self { + pub fn new(ctx: &egui::Context) -> Self { Self { slots: HashMap::new(), files: crate::file_state::FileStates::new(), @@ -231,6 +233,7 @@ impl Library { online_running: None, update: None, aside: None, + counts: crate::db_counts::Counts::new(ctx), } } @@ -436,6 +439,7 @@ impl Library { { b.set_booster_dir(&dir.join("boosters")); } + self.counts.opened(path, &o.db); Slot::Ready(Arc::new(o.db)) } Err(e) => Slot::Failed(import_error(&e)), @@ -1031,17 +1035,18 @@ impl Library { .file_stem() .map(|s| s.to_string_lossy().into_owned()) .unwrap_or_default(); - let detail = match self.slots.get(path) { - Some(Slot::Ready(db)) => match db.as_chessbase() { - Some(b) => format!( + let shown = |c: crate::db_counts::Count| { + if c.locked { + format!( "{} · 🔒", - trf( - "{n} games", - &[("n", &large_db::short_count(b.games() + b.texts()))], - ) - ), - None => crate::i18n::games(db.len()), - }, + trf("{n} games", &[("n", &large_db::short_count(c.games))]) + ) + } else { + crate::i18n::games(c.games) + } + }; + let detail = match self.slots.get(path) { + Some(Slot::Ready(db)) => shown(crate::db_counts::Count::of(db)), Some(Slot::Loading { progress, .. }) => { let p = progress.lock().map(|g| *g).unwrap_or(ScanProgress { bytes_done: 0, @@ -1052,7 +1057,8 @@ impl Library { } Some(Slot::Failed(_)) => tr("error").into(), None if !self.files.exists(path) => tr("file not found").into(), - None => tr("not loaded").into(), + // Not opened: its games once counted, nothing till then. + None => self.counts.get(path).map(shown).unwrap_or_default(), }; let (rect, resp) = ui.allocate_exact_size(vec2(190.0, 64.0), Sense::click()); let v = ui.visuals(); diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index 4ad7451..cb13429 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -8,6 +8,7 @@ mod assets; mod board; mod board_search; mod chatgpt; +mod db_counts; mod engine_download; mod engine_offer; mod engines; diff --git a/apps/desktop/src/play.rs b/apps/desktop/src/play.rs index 2091196..01749fc 100644 --- a/apps/desktop/src/play.rs +++ b/apps/desktop/src/play.rs @@ -1414,17 +1414,30 @@ impl Dialog { }); // Each engine on its own scale (its authors'): not a person's Elo, said under it. let (min, max) = range(self.prefs.rival, &self.prefs.style); + // Room for the rating that rides above the handle. + ui.add_space(16.0); ui.horizontal(|ui| { let end = |ui: &mut egui::Ui, v: u32| { ui.add_sized([34.0, 18.0], egui::Label::new(RichText::new(v.to_string()).weak())) }; end(ui, min); ui.spacing_mut().slider_width = W - 2.0 * 34.0 - 2.0 * GAP; - ui.add( + let r = ui.add( egui::Slider::new(&mut self.prefs.strength, min..=max) .step_by(50.0) .show_value(false), ); + // The eye is on the handle while it moves, not on the heading: the rating + // follows it (the handle's travel as egui's slider has it). + let travel = r.rect.x_range().shrink(r.rect.height() / 2.5); + let t = self.prefs.strength.saturating_sub(min) as f32 / (max - min).max(1) as f32; + ui.painter().text( + egui::pos2(travel.min + t * travel.span(), r.rect.top() - 2.0), + egui::Align2::CENTER_BOTTOM, + self.prefs.strength.to_string(), + egui::FontId::proportional(14.0), + ui.visuals().strong_text_color(), + ); end(ui, max); }); ui.add_space(4.0);