diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 04e4232..9e5da22 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -308,6 +308,8 @@ pub struct App { brilliant_summary: Option, /// A pass asked for while Stockfish 19 is fetched or checked: it starts after. brilliant_waiting: Option, + /// The plies of the games the pass under way analyses, for its time left. + brilliant_plies: std::collections::HashMap, applied_dark: Option, debug: DebugStartup, } @@ -583,6 +585,7 @@ impl App { brilliant_pass: None, brilliant_summary: None, brilliant_waiting: None, + brilliant_plies: std::collections::HashMap::new(), applied_dark: None, debug: DebugStartup::from_env(), } @@ -1998,6 +2001,7 @@ impl App { path: PathBuf, records: Vec, filter: chess_import::chessbase::base::Filter, + about: String, ) { if self.library.pass.is_some() { return; @@ -2010,13 +2014,10 @@ impl App { else { return; }; - let about = if filter == chess_import::chessbase::base::Filter::default() { - tr("all games").to_owned() - } else { - tr("matching the conditions").to_owned() - }; - let mut dialog = - crate::brilliant_ui::StartDialog::new(ctx, path, db, records, filter, about, cache); + let index = self.library.marks(&path); + let mut dialog = crate::brilliant_ui::StartDialog::new( + ctx, path, db, records, filter, about, cache, index, + ); // `CP_BRILLIANT_RUN=1`: no question. if std::env::var_os("CP_BRILLIANT_RUN").is_some() { let cancel = std::sync::atomic::AtomicBool::new(false); @@ -2024,11 +2025,13 @@ impl App { self.library.database(&dialog.source), crate::review::cache_dir(), ) { + let index = self.library.marks(&dialog.source); dialog.counted = Some(crate::brilliant_ui::count( &db, &dialog.records, &dialog.filter, &cache, + &index, &cancel, )); } @@ -2079,6 +2082,12 @@ impl App { // The list in the table's order: the analysed ones are taken first (at once). let mut list = counted.reviewed.clone(); list.extend(&counted.left); + self.brilliant_plies = counted + .left + .iter() + .copied() + .zip(counted.plies_left.iter().copied()) + .collect(); let order: std::collections::HashMap = dialog .records .iter() @@ -2139,8 +2148,24 @@ impl App { if let Some(p) = self.prep.as_mut() { p.engine_blocked = pass_busy; } - let estimate = |rest: &[u32]| rest.len() as f64 * 60.0 / crate::review::processes() as f64; + let plies = &self.brilliant_plies; + let estimate = |rest: &[u32]| { + crate::brilliant::estimate_secs( + rest.iter().filter_map(|r| plies.get(r).copied()), + crate::review::processes(), + ) + }; self.library.show_pass(estimate); + // `CP_BRILLIANT_STOP_AFTER=`: «Stop» pressed that long after the start. + if let Some(ms) = std::env::var("CP_BRILLIANT_STOP_AFTER") + .ok() + .and_then(|ms| ms.parse::().ok()) + && let Some(job) = self.library.pass.as_mut() + && !job.stopping + && job.started.elapsed() >= std::time::Duration::from_millis(ms) + { + job.stop(); + } if let Some(job) = self.library.pass.as_ref() && let Some((end, sides)) = job.poll() { @@ -2221,6 +2246,7 @@ impl App { && let Some(action) = summary.show(ctx) { let source = summary.source.clone(); + let summary_about = summary.about.clone(); use crate::brilliant_ui::SummaryAction; match action { SummaryAction::Close => self.brilliant_summary = None, @@ -2230,7 +2256,8 @@ impl App { SummaryAction::Sort => self.library.sort_by_marks(&source), SummaryAction::Continue { records, filter } => { self.brilliant_summary = None; - self.ask_great_moves(ctx, source, records, *filter); + let about = summary_about.clone(); + self.ask_great_moves(ctx, source, records, *filter, about); } SummaryAction::Open { record, ply } => { self.brilliant_summary = None; @@ -2452,6 +2479,10 @@ impl App { /// 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) { + if let Some(why) = engine_game_refused(self.pass_busy()) { + self.toast(ctx, why); + return; + } let Some(aside) = self.put_aside.as_ref() else { return; }; @@ -2779,7 +2810,7 @@ impl App { fn start_play(&mut self, ctx: &egui::Context, start: crate::play::Start) { // No game against the engine while the search for great moves runs (the owner's // decision, task 27). - if let Some(why) = self.pass_busy() { + if let Some(why) = engine_game_refused(self.pass_busy()) { self.toast(ctx, why); return; } @@ -4773,7 +4804,8 @@ impl eframe::App for App { path, records, filter, - } => self.ask_great_moves(&ctx, path, records, filter), + about, + } => self.ask_great_moves(&ctx, path, records, filter, about), LibraryAction::EditGameData { path, index } => { self.open_game(&ctx, path, index, None); self.edit_game_data(); @@ -5097,6 +5129,18 @@ fn sanitize(s: &str) -> String { .collect::() } +/// Why a game against the engine (Maia, a rematch, the game put aside) may not start: +/// the search for great moves has the engine (`pass`: its message while it runs). +fn engine_game_refused(pass: Option) -> Option { + pass.map(|why| { + format!( + "{} {}", + tr("A game against the engine waits until the search for great moves ends."), + why + ) + }) +} + #[cfg(test)] mod waiting_tests { use super::{names_text, still_waiting}; @@ -5119,6 +5163,22 @@ mod waiting_tests { assert!(!still_waiting(&Pending::LiveAnalysis, Some(7), Some(3))); } + /// Every way to a game against the engine asks the same guard: refused while the + /// search for great moves runs, allowed otherwise. + #[test] + fn a_game_against_the_engine_waits_for_the_search() { + assert!(super::engine_game_refused(None).is_none()); + let why = super::engine_game_refused(Some("x".into())).unwrap(); + assert!(why.ends_with('x')); + let src = include_str!("app.rs"); + for f in ["fn resume_aside(", "fn start_play("] { + let body = &src[src.find(f).unwrap()..]; + let guard = body.find("engine_game_refused(self.pass_busy())").unwrap(); + let first_return = body.find("return").unwrap(); + assert!(guard < first_return + 40, "{f} checks the search first"); + } + } + #[test] fn names_in_messages_are_short() { let names: Vec = ["a.pgn", "b.pgn", "c.pgn", "d.pgn"] diff --git a/apps/desktop/src/brilliant.rs b/apps/desktop/src/brilliant.rs index 8c33633..23ad03a 100644 --- a/apps/desktop/src/brilliant.rs +++ b/apps/desktop/src/brilliant.rs @@ -174,6 +174,15 @@ impl Entry { } } +/// The entry of `record` if it still belongs to the game the database has there now (its +/// main line is the one analysed): a deleted or changed game never lends its marks to +/// the record that took its number. +pub fn current_entry(index: &Index, db: &Database, record: u32) -> Option { + let entry = index.get(record)?; + let game = db.load_game(record as usize)?.game; + (GameAnalysis::new(&game, None).cache_key() == entry.line).then(|| entry.clone()) +} + /// The record of an analysis of `game`: its marks per side and its moves of note. pub fn entry_of(analysis: &GameAnalysis, game: &Game) -> Entry { let report = &analysis.report; @@ -214,6 +223,18 @@ pub fn entry_of(analysis: &GameAnalysis, game: &Game) -> Entry { } } +/// The entry of a game that is not analysed, and why («—» in the column). +pub fn skipped_entry(line: String, skip: Skip) -> Entry { + Entry { + line, + white: SideMarks::default(), + black: SideMarks::default(), + found: Vec::new(), + stale: false, + skip: Some(skip), + } +} + /// Why `game` is not analysed, if it is not. pub fn skip_of(game: &Game, chess960: bool) -> Option { if chess960 { @@ -295,6 +316,11 @@ impl Index { } } + /// The records with an entry. + pub fn records(&self) -> impl Iterator + '_ { + self.records.keys().copied() + } + pub fn get(&self, record: u32) -> Option<&Entry> { self.records.get(&record) } @@ -306,8 +332,8 @@ impl Index { /// Where a record goes when the table is sorted by its marks: !! first, then !, /// analysed without them, not analysable, not analysed. - pub fn rank(&self, record: u32, sides: &Sides) -> u8 { - match self.records.get(&record) { + pub fn rank(&self, record: u32, sides: &Sides, current: &dyn Fn(u32) -> bool) -> u8 { + match self.records.get(&record).filter(|_| current(record)) { None => 4, Some(e) if e.skip.is_some() => 3, Some(e) => { @@ -495,7 +521,14 @@ pub fn run_pass( } if let Err(e) = result { end.outcome = Outcome::EngineFailed(match e { - JobFailure::Start(e) | JobFailure::Engine(e) => e, + JobFailure::Start(e) => { + eprintln!("great moves: {e}"); + crate::i18n::tr("the engine did not start").to_owned() + } + JobFailure::Engine(e) => { + eprintln!("great moves: {e}"); + crate::i18n::tr("the engine stopped answering").to_owned() + } JobFailure::Terminated(r) => crate::analysis::termination_message(&r), }); break; @@ -569,13 +602,14 @@ pub struct Totals { } /// Sums the index's entries of `records` over the sides that count (`sides`). -pub fn totals(index: &Index, records: &[u32], sides: &Sides) -> Totals { +pub fn totals(index: &Index, db: &Database, records: &[u32], sides: &Sides) -> Totals { let mut t = Totals::default(); let (mut acpl, mut acc) = (Vec::new(), Vec::new()); for &r in records { - let Some(e) = index.get(r).filter(|e| e.skip.is_none()) else { + let Some(e) = current_entry(index, db, r).filter(|e| e.skip.is_none()) else { continue; }; + let e = &e; let (white, black) = sides.of(r); if !white && !black { t.player_missing.push(r); @@ -751,11 +785,34 @@ impl Drop for PassJob { } } -/// Seconds an engine takes for games of these many plies: one search per position and a -/// second one for some, about 0.94 s per position in one process -/// (docs/decisions.md, «Analysis with fixed parameters»), over `processes`. +/// Seconds per position of one engine process, with the second search of !! and !: +/// measured, 3 games of 170 plies in 44 s in 8 processes (i7-13700KF, +/// docs/qa/task-27-functional-2026-11-27.md). +const SECS_PER_POSITION: f64 = 2.0; + +/// Seconds an engine takes for games of these many plies over `processes`: the same in +/// the question and in the progress until three games are done. pub fn estimate_secs(plies: impl Iterator, processes: usize) -> f64 { - plies.map(|p| (p + 1) as f64 * 0.94).sum::() / processes.max(1) as f64 + plies + .map(|p| (p + 1) as f64 * SECS_PER_POSITION) + .sum::() + / processes.max(1) as f64 +} + +/// «less than a minute», «about 14 min», «about 1 h 20 min». +pub fn format_estimate(secs: f64) -> String { + if secs < 60.0 { + return crate::i18n::tr("less than a minute").to_owned(); + } + let min = (secs / 60.0).round() as u64; + if min < 60 { + crate::i18n::trf("about {n} min", &[("n", &min)]) + } else { + crate::i18n::trf( + "about {h} h {m} min", + &[("h", &(min / 60)), ("m", &(min % 60))], + ) + } } #[cfg(test)] diff --git a/apps/desktop/src/brilliant_tests.rs b/apps/desktop/src/brilliant_tests.rs index 6b05489..61e8fce 100644 --- a/apps/desktop/src/brilliant_tests.rs +++ b/apps/desktop/src/brilliant_tests.rs @@ -222,6 +222,17 @@ fn a_broken_index_is_an_empty_one() { assert_eq!(Index::load(dir.0.join("none.json")).len(), 0); } +/// The entries of `index` made the database's own: their main lines are those of its +/// games (as a pass writes them). +fn fit(index: &mut Index, db: &Database) { + let records: Vec = index.records().collect(); + for r in records { + let mut e = index.get(r).unwrap().clone(); + e.line = GameAnalysis::new(&db.load_game(r as usize).unwrap().game, None).cache_key(); + index.set(r, e); + } +} + fn side(brilliant: u32, great: u32, blunders: u32, acpl: u32, accuracy: f64) -> SideMarks { SideMarks { counts: Counts { @@ -282,7 +293,10 @@ fn totals_count_only_the_filters_players_moves() { ..entry(SideMarks::default(), SideMarks::default(), Vec::new()) }, ); - let all = totals(&index, &[0, 1, 2], &Sides::default()); + let dir = Dir::new("totals"); + let (_, db) = source(&dir); + fit(&mut index, &db); + let all = totals(&index, &db, &[0, 1, 2], &Sides::default()); assert_eq!( (all.games, all.sides, all.with_brilliant, all.with_great), (2, 4, 2, 2) @@ -303,7 +317,7 @@ fn totals_count_only_the_filters_players_moves() { let player = Sides { player: Some((vec![0], vec![1])), }; - let t = totals(&index, &[0, 1, 2], &player); + let t = totals(&index, &db, &[0, 1, 2], &player); assert_eq!( (t.games, t.sides, t.with_brilliant, t.with_great), (2, 2, 2, 1) @@ -322,7 +336,10 @@ fn totals_count_only_the_filters_players_moves() { let nobody = Sides { player: Some((Vec::new(), Vec::new())), }; - assert_eq!(totals(&index, &[0, 1], &nobody).player_missing, vec![0, 1]); + assert_eq!( + totals(&index, &db, &[0, 1], &nobody).player_missing, + vec![0, 1] + ); } #[test] @@ -375,14 +392,15 @@ fn two_sided() -> Index { #[test] fn the_column_counts_only_the_filters_players_moves() { let index = two_sided(); + let any = |_| true; let both = Sides::default(); let black = Sides { player: Some((Vec::new(), vec![0])), }; - assert_eq!(index.rank(0, &both), 0); - assert_eq!(index.rank(0, &black), 1); + assert_eq!(index.rank(0, &both, &any), 0); + assert_eq!(index.rank(0, &black, &any), 1); // A game where the player is on neither side has nothing of his. - assert_eq!(index.rank(1, &black), 2); + assert_eq!(index.rank(1, &black, &any), 2); let e = index.get(0).unwrap().for_sides(false, true); assert_eq!(e.of_sides(true, true).brilliant, 0); assert_eq!(e.of_sides(true, true).great, 1); @@ -404,7 +422,8 @@ fn the_summary_keeps_the_player_for_continue() { ..Default::default() }; let sides = player_sides(&db, &filter, &AtomicBool::new(false)); - let index = two_sided(); + let mut index = two_sided(); + fit(&mut index, &db); // Record 0: Carlsen has White (its !!); record 1: Carlsen has Black (a !). let summary = crate::brilliant_ui::Summary::new( &path, @@ -427,3 +446,118 @@ fn the_summary_keeps_the_player_for_continue() { assert_eq!(summary.player, Some(("carlsen".to_owned(), 1, 1))); assert_eq!(summary.rows.len(), 1); } + +const FIVE: &str = "[White \"A\"]\n[Black \"B\"]\n[Result \"*\"]\n\n1. e4 e5 *\n\n\ +[White \"C\"]\n[Black \"D\"]\n[Result \"*\"]\n\n1. d4 d5 *\n\n\ +[White \"E\"]\n[Black \"F\"]\n[Result \"*\"]\n\n1. c4 e5 *\n\n\ +[White \"G\"]\n[Black \"H\"]\n[Result \"*\"]\n\n1. Nf3 d5 *\n\n\ +[White \"I\"]\n[Black \"J\"]\n[Result \"*\"]\n\n1. g3 g6 *\n"; + +/// A game deleted (the 2nd of 5): the records after it take other numbers, and none of +/// them lends another game's marks — not in the summary, not in the sort; asked again, +/// the entries are made anew from the cache. +#[test] +fn a_deleted_game_never_lends_its_marks() { + let dir = Dir::new("deleted"); + let path = dir.0.join("five.pgn"); + std::fs::write(&path, FIVE).unwrap(); + let open = |p: &Path| { + chess_import::open(p, &mut |_| {}, &AtomicBool::new(false)) + .unwrap() + .db + }; + let db = open(&path); + let file = dir.0.join("marks.json"); + let index = Mutex::new(Index::load(file.clone())); + pass(&db, &[0, 1, 2, 3, 4], &index, &dir, &engine_at(&fake())); + // Each game marked: a !! of its own, told apart by its number. + { + let mut i = index.lock().unwrap(); + for r in 0..5u32 { + let mut e = i.get(r).unwrap().clone(); + e.white.counts.brilliant = 1; + e.found = vec![found(0, true, r + 1, "x", true)]; + i.set(r, e); + } + i.save().unwrap(); + } + let without_second: String = FIVE + .split("\n\n[") + .enumerate() + .filter(|(i, _)| *i != 1) + .map(|(i, g)| { + if i == 0 { + g.to_owned() + } else { + format!("[{g}") + } + }) + .collect::>() + .join("\n\n"); + std::fs::write(&path, without_second).unwrap(); + let db = open(&path); + assert_eq!(db.len(), 4); + let i = index.lock().unwrap(); + let t = totals(&i, &db, &[0, 1, 2, 3], &Sides::default()); + assert_eq!(t.games, 1); + assert_eq!( + t.brilliant + .iter() + .map(|(_, f)| f.number) + .collect::>(), + [1] + ); + assert!(current_entry(&i, &db, 1).is_none()); + assert_eq!( + i.rank(1, &Sides::default(), &|r| current_entry(&i, &db, r) + .is_some()), + 4 + ); + drop(i); + // «Find» again: counted from the cache, the entries are the games' own again. + let cache = dir.cache(); + let c = crate::brilliant_ui::count( + &db, + &[0, 1, 2, 3], + &Default::default(), + &cache, + &index, + &AtomicBool::new(false), + ); + assert_eq!(c.reviewed, vec![0, 1, 2, 3]); + let i = index.lock().unwrap(); + assert_eq!(totals(&i, &db, &[0, 1, 2, 3], &Sides::default()).games, 4); +} + +/// Games that cannot be analysed get «—» with the reason in the index. +#[test] +fn games_not_analysable_get_their_reason() { + let dir = Dir::new("skips"); + let (_, db) = source(&dir); + let index = Mutex::new(Index::load(dir.0.join("marks.json"))); + let c = crate::brilliant_ui::count( + &db, + &[2, 3], + &Default::default(), + &dir.cache(), + &index, + &AtomicBool::new(false), + ); + assert_eq!(c.skipped, vec![(2, Skip::NullMove), (3, Skip::NoMoves)]); + let i = index.lock().unwrap(); + assert_eq!( + current_entry(&i, &db, 2).unwrap().skip, + Some(Skip::NullMove) + ); + assert_eq!(i.get(3).unwrap().skip, Some(Skip::NoMoves)); +} + +#[test] +fn estimates_are_said_plainly() { + assert_eq!(format_estimate(30.0), "less than a minute"); + assert_eq!(format_estimate(14.0 * 60.0), "about 14 min"); + assert_eq!(format_estimate(80.0 * 60.0), "about 1 h 20 min"); + // The tester's measure: 3 games of 170 plies in 8 processes, 44 s. + let secs = estimate_secs([56, 57, 57].into_iter(), 8); + assert!((40.0..48.0).contains(&secs), "{secs}"); +} diff --git a/apps/desktop/src/brilliant_ui.rs b/apps/desktop/src/brilliant_ui.rs index 884ddb8..0560931 100644 --- a/apps/desktop/src/brilliant_ui.rs +++ b/apps/desktop/src/brilliant_ui.rs @@ -26,11 +26,15 @@ pub struct Counted { } /// Counts what of `records` is analysed (the analysis cache in `cache`), on this thread. +/// The index follows: a game analysed whose entry is missing or belongs to another game +/// (one deleted or changed) gets its entry anew from the cache, a game that cannot be +/// analysed gets «—» with the reason. pub fn count( db: &Database, records: &[u32], filter: &Filter, cache: &Path, + index: &std::sync::Mutex, cancel: &AtomicBool, ) -> Counted { let store = crate::review::Cache(cache.to_path_buf()); @@ -45,18 +49,33 @@ pub fn count( if cancel.load(Ordering::Relaxed) { break; } + let set = |entry: crate::brilliant::Entry| { + if let Ok(mut i) = index.lock() + && i.get(r) != Some(&entry) + { + i.set(r, entry); + let _ = i.save(); + } + }; let Some(parsed) = db.load_game(r as usize) else { c.skipped.push((r, Skip::Unreadable)); + set(crate::brilliant::skipped_entry( + String::new(), + Skip::Unreadable, + )); continue; }; + let mut a = GameAnalysis::with_store(&parsed.game, Some(&store)); if let Some(skip) = crate::brilliant::skip_of(&parsed.game, db.row(r as usize).chess960) { c.skipped.push((r, skip)); + set(crate::brilliant::skipped_entry(a.cache_key(), skip)); continue; } - let a = GameAnalysis::with_store(&parsed.game, Some(&store)); let by_engine = a.has_data() && a.meta.as_ref().is_some_and(|m| m.nodes > 0); if by_engine && (a.stale() || a.missing() == 0) { c.reviewed.push(r); + a.refresh(&parsed.game); + set(crate::brilliant::entry_of(&a, &parsed.game)); } else { c.left.push(r); c.plies_left.push(parsed.game.mainline().len()); @@ -84,6 +103,7 @@ pub enum StartOutcome { } impl StartDialog { + #[allow(clippy::too_many_arguments)] pub fn new( ctx: &egui::Context, source: PathBuf, @@ -92,6 +112,7 @@ impl StartDialog { filter: Filter, about: String, cache: PathBuf, + index: Arc>, ) -> StartDialog { let (tx, rx) = channel(); let cancel = Arc::new(AtomicBool::new(false)); @@ -99,7 +120,7 @@ impl StartDialog { let _ = std::thread::Builder::new() .name("brilliant-count".into()) .spawn(move || { - let _ = tx.send(count(&db, &list, &f, &cache, &c)); + let _ = tx.send(count(&db, &list, &f, &cache, &index, &c)); ctx.request_repaint(); }); StartDialog { @@ -134,15 +155,13 @@ impl StartDialog { .default_width(520.0) .show(ctx, |ui| { ui.set_width(520.0); - ui.label( - RichText::new(format!( - "{name} · {} {}", - crate::i18n::games(self.records.len()), - self.about - )) - .weak() - .size(12.0), + let about = format!( + "{name} · {} {}", + crate::i18n::games(self.records.len()), + self.about ); + ui.add(egui::Label::new(RichText::new(&about).weak().size(12.0)).truncate()) + .on_hover_text(&about); ui.add_space(8.0); // Two lines kept for the counts: the window does not jump when they come. ui.allocate_ui(egui::vec2(520.0, 40.0), |ui| match &self.counted { @@ -158,17 +177,19 @@ impl StartDialog { crate::review::processes(), ); ui.label(trf( - "The engine will review {games}: about {time}.", + "The engine will review {games} — {time}.", &[ - ("games", &crate::i18n::games(c.left.len())), - ("time", &crate::review::format_duration(secs)), + ("games", &crate::i18n::games_object(c.left.len())), + ("time", &crate::brilliant::format_estimate(secs)), ], )); if !c.reviewed.is_empty() { - ui.label(trf( - "{k} are already reviewed: their marks come from the saved review.", - &[("k", &c.reviewed.len())], - )); + let key = if crate::i18n::is_one(c.reviewed.len()) { + "{games} is already reviewed: its marks come from the saved review." + } else { + "{games} are already reviewed: their marks come from the saved review." + }; + ui.label(trf(key, &[("games", &crate::i18n::games(c.reviewed.len()))])); } } }); @@ -270,11 +291,11 @@ impl Summary { stopped: Option<(usize, usize)>, skipped: Vec<(u32, Skip)>, ) -> Summary { - let totals = crate::brilliant::totals(index, records, sides); + let totals = crate::brilliant::totals(index, db, records, sides); let rest = records .iter() .copied() - .filter(|r| index.get(*r).is_none()) + .filter(|r| crate::brilliant::current_entry(index, db, *r).is_none()) .collect(); let player = sides.player.as_ref().map(|(w, b)| { let count = |v: &Vec| { @@ -322,9 +343,37 @@ impl Summary { pub fn show(&mut self, ctx: &egui::Context) -> Option { let mut out = None; + // `CP_SUMMARY_CONTINUE=1`, `CP_SUMMARY_OPEN=`: «Continue», or the i-th move of + // «Games with !!» opened, once (checks without a mouse). + static HOOK: std::sync::Once = std::sync::Once::new(); + let mut hook = None; + HOOK.call_once(|| { + if std::env::var_os("CP_SUMMARY_CONTINUE").is_some() && !self.rest.is_empty() { + hook = Some(SummaryAction::Continue { + records: self.rest.clone(), + filter: Box::new(self.filter.clone()), + }); + } else if let Some(row) = std::env::var("CP_SUMMARY_OPEN") + .ok() + .and_then(|i| i.parse::().ok()) + .and_then(|i| self.rows.get(i)) + { + hook = Some(SummaryAction::Open { + record: row.record, + ply: row.found.ply, + }); + } + }); + if hook.is_some() { + return hook; + } let mut open = true; let t = &self.totals; let title = match self.stopped { + Some((i, n)) if crate::i18n::is_one(i) => trf( + "Search stopped · reviewed: {i} of {n} game", + &[("i", &i), ("n", &n)], + ), Some((i, n)) => trf( "Search stopped · reviewed: {i} of {n}", &[("i", &i), ("n", &n)], diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index c900aa2..fee3b52 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -169,6 +169,29 @@ pub fn games(n: usize) -> String { } } +/// [`games`] as the object of a verb: «разберёт 1 партию» in Russian; the same as +/// [`games`] in the other languages. +pub fn games_object(n: usize) -> String { + match current() { + Lang::Ru if n % 10 == 1 && n % 100 != 11 => { + format!("{} партию", crate::large_db::grouped(n)) + } + _ => games(n), + } +} + +/// Whether `n` takes the singular in the current language (a verb or an adjective +/// after the number: «1 партия разобрана», «21 партия разобрана», «2 партии разобраны»). +pub fn is_one(n: usize) -> bool { + match current() { + Lang::Ru => n % 10 == 1 && n % 100 != 11, + Lang::Fr => n <= 1, + // The noun after a number stays singular, and so does what goes with it. + Lang::Uz | Lang::Kk => true, + _ => n == 1, + } +} + /// "1 text", "21 texts" (guiding texts of a database), with Russian plural forms /// ("1 текст", "3 текста", "5 текстов"). pub fn texts(n: usize) -> String { @@ -20656,6 +20679,127 @@ const ROWS: &[[&str; 9]] = &[ "Yuklab olish tugagach, ajoyib yurishlarni qidirish o‘zi boshlanadi.", "Жүктеу аяқталғанда тамаша жүрістерді іздеу өзі басталады.", ], + [ + "A game against the engine waits until the search for great moves ends.", + "Игра с движком подождёт, пока идёт поиск замечательных ходов.", + "Une partie contre le moteur attend la fin de la recherche de très bons coups.", + "Eine Partie gegen die Engine wartet, bis die Suche nach starken Zügen endet.", + "Una partida contra el motor espera a que termine la búsqueda de jugadas notables.", + "Una partita contro il motore attende la fine della ricerca di mosse notevoli.", + "Uma partida contra o motor espera pelo fim da pesquisa de lances notáveis.", + "Ajoyib yurishlar qidiruvi tugaguncha dvigatel bilan o‘yin kutadi.", + "Тамаша жүрістерді іздеу аяқталғанша қозғалтқышпен ойын күтеді.", + ], + [ + "matching: {list}", + "по условиям: {list}", + "selon : {list}", + "nach: {list}", + "según: {list}", + "secondo: {list}", + "segundo: {list}", + "shartlar: {list}", + "шарттар: {list}", + ], + [ + "less than a minute", + "меньше минуты", + "moins d’une minute", + "weniger als eine Minute", + "menos de un minuto", + "meno di un minuto", + "menos de um minuto", + "bir daqiqadan kam", + "бір минуттан аз", + ], + [ + "about {n} min", + "примерно {n} мин", + "environ {n} min", + "etwa {n} Min.", + "unos {n} min", + "circa {n} min", + "cerca de {n} min", + "taxminan {n} daq", + "шамамен {n} мин", + ], + [ + "about {h} h {m} min", + "примерно {h} ч {m} мин", + "environ {h} h {m} min", + "etwa {h} Std. {m} Min.", + "unas {h} h {m} min", + "circa {h} h {m} min", + "cerca de {h} h {m} min", + "taxminan {h} soat {m} daq", + "шамамен {h} сағ {m} мин", + ], + [ + "the engine did not start", + "движок не запустился", + "le moteur n’a pas démarré", + "die Engine ist nicht gestartet", + "el motor no arrancó", + "il motore non è partito", + "o motor não arrancou", + "dvigatel ishga tushmadi", + "қозғалтқыш іске қосылмады", + ], + [ + "the engine stopped answering", + "движок перестал отвечать", + "le moteur ne répond plus", + "die Engine antwortet nicht mehr", + "el motor dejó de responder", + "il motore ha smesso di rispondere", + "o motor deixou de responder", + "dvigatel javob bermay qo‘ydi", + "қозғалтқыш жауап бермей қалды", + ], + [ + "The engine will review {games} — {time}.", + "Движок разберёт {games} — {time}.", + "Le moteur analysera {games} : {time}.", + "Die Engine analysiert {games}: {time}.", + "El motor analizará {games}: {time}.", + "Il motore analizzerà {games}: {time}.", + "O motor vai analisar {games}: {time}.", + "Dvigatel {games}ni tahlil qiladi — {time}.", + "Қозғалтқыш {games} талдайды — {time}.", + ], + [ + "{games} is already reviewed: its marks come from the saved review.", + "{games} уже разобрана: её отметки возьмутся из сохранённого разбора.", + "{games} est déjà analysée : ses marques viennent de l’analyse enregistrée.", + "{games} ist bereits analysiert: ihre Markierungen kommen aus der gespeicherten Analyse.", + "{games} ya está analizada: sus marcas salen del análisis guardado.", + "{games} è già analizzata: i suoi segni vengono dall’analisi salvata.", + "{games} já está analisada: as suas marcas vêm da análise guardada.", + "{games} allaqachon tahlil qilingan: belgilari saqlangan tahlildan olinadi.", + "{games} талданып қойған: белгілері сақталған талдаудан алынады.", + ], + [ + "{games} are already reviewed: their marks come from the saved review.", + "{games} уже разобраны: их отметки возьмутся из сохранённого разбора.", + "{games} sont déjà analysées : leurs marques viennent de l’analyse enregistrée.", + "{games} sind bereits analysiert: ihre Markierungen kommen aus der gespeicherten Analyse.", + "{games} ya están analizadas: sus marcas salen del análisis guardado.", + "{games} sono già analizzate: i loro segni vengono dall’analisi salvata.", + "{games} já estão analisadas: as suas marcas vêm da análise guardada.", + "{games} allaqachon tahlil qilingan: belgilari saqlangan tahlildan olinadi.", + "{games} талданып қойған: белгілері сақталған талдаудан алынады.", + ], + [ + "Search stopped · reviewed: {i} of {n} game", + "Поиск остановлен · разобрана: {i} из {n}", + "Recherche arrêtée · analysée : {i} sur {n}", + "Suche angehalten · analysiert: {i} von {n}", + "Búsqueda detenida · analizada: {i} de {n}", + "Ricerca fermata · analizzata: {i} di {n}", + "Pesquisa parada · analisada: {i} de {n}", + "Qidiruv to‘xtatildi · tahlil qilindi: {n} dan {i}", + "Іздеу тоқтатылды · талданды: {n} ішінен {i}", + ], ]; #[cfg(test)] diff --git a/apps/desktop/src/large_db.rs b/apps/desktop/src/large_db.rs index d3da970..4f60f0b 100644 --- a/apps/desktop/src/large_db.rs +++ b/apps/desktop/src/large_db.rs @@ -359,6 +359,10 @@ pub struct LargeView { shown_marks: std::cell::RefCell<(u64, HashMap>)>, /// The table sorted by the «!!» column. marks_sort: bool, + /// The database the marks are checked against (set by `table`). + marks_db: Option>, + /// The texts of the conditions of the list (for the search's question). + last_conditions: Vec, /// Whose moves the «!!» column counts: the filter's player's (found in the background /// for that filter), else both sides'. marks_sides: (Option, crate::brilliant::Sides), @@ -503,6 +507,8 @@ impl LargeView { marks: None, shown_marks: std::cell::RefCell::new((u64::MAX, HashMap::new())), marks_sort: false, + marks_db: None, + last_conditions: Vec::new(), marks_sides: (None, Default::default()), sides_job: None, pass: None, @@ -720,6 +726,13 @@ impl LargeView { } } + /// The database the marks are checked against. + pub fn set_marks_db(&mut self, db: &Arc) { + if !self.marks_db.as_ref().is_some_and(|d| Arc::ptr_eq(d, db)) { + self.marks_db = Some(db.clone()); + } + } + /// The table sorted by its «!!» column (the summary's «Sort»). pub fn sort_marks_on(&mut self) { self.marks_sort = true; @@ -735,7 +748,17 @@ impl LargeView { return; }; let sides = &self.marks_sides.1; - self.view.sort_by_key(|&r| (index.rank(r, sides), r)); + // Only the entries of the games the database has there now (a deleted game's + // marks are not its successor's). + let current: std::collections::HashSet = match &self.marks_db { + Some(db) => index + .records() + .filter(|&r| crate::brilliant::current_entry(&index, db, r).is_some()) + .collect(), + None => std::collections::HashSet::new(), + }; + self.view + .sort_by_key(|&r| (index.rank(r, sides, &|r| current.contains(&r)), r)); self.view_gen += 1; } @@ -773,13 +796,38 @@ impl LargeView { /// «!! Find great moves» (the button, Shift+A): the library asks first. fn ask_search(&mut self, path: &Path, actions: &mut Vec) { + let about = if self.last_conditions.is_empty() { + tr("all games").to_owned() + } else { + trf( + "matching: {list}", + &[("list", &self.last_conditions.join(" · "))], + ) + }; actions.push(LibraryAction::FindGreatMoves { path: path.to_path_buf(), records: self.view.clone(), filter: self.form.filter(), + about, }); } + /// «!! Find great moves»: the button, or Shift+A outside a field (a disabled button + /// says why, also over an empty list). + fn handle_find(&mut self, ui: &mut Ui, path: &Path, actions: &mut Vec) { + let typing = ui.ctx().egui_wants_keyboard_input(); + let shift_a = !typing + && !crate::app::overlay_open_besides(ui.ctx(), &[egui::Id::new("filters_drawer")]) + && ui.input_mut(|i| i.consume_key(egui::Modifiers::SHIFT, egui::Key::A)); + if std::mem::take(&mut self.find_clicked) || shift_a { + match (self.pass.is_some(), self.search_blocked()) { + (false, None) => self.ask_search(path, actions), + (false, Some(why)) => actions.push(LibraryAction::Notice(why)), + (true, _) => {} + } + } + } + /// Why the search cannot start on the list shown, if it cannot. fn search_blocked(&self) -> Option { if let Some(why) = &self.engine_busy { @@ -1551,6 +1599,7 @@ impl LargeView { /// many games reached the position in the board's move order. fn chips(&mut self, ui: &mut Ui, settings: &Settings) { let conditions = self.conditions(settings); + self.last_conditions = conditions.iter().map(|c| c.text.clone()).collect(); let mut clear = None; let mut goto = None; let mut toggle_order = false; @@ -2668,19 +2717,7 @@ impl LargeView { return open_notes; } - // «!! Find great moves»: the button, or Shift+A outside a field (a disabled button - // says why). - let typing = ui.ctx().egui_wants_keyboard_input(); - let shift_a = !typing - && !crate::app::overlay_open_besides(ui.ctx(), &[egui::Id::new("filters_drawer")]) - && ui.input_mut(|i| i.consume_key(egui::Modifiers::SHIFT, egui::Key::A)); - if std::mem::take(&mut self.find_clicked) || shift_a { - match (self.pass.is_some(), self.search_blocked()) { - (false, None) => self.ask_search(path, actions), - (false, Some(why)) => actions.push(LibraryAction::Notice(why)), - (true, _) => {} - } - } + self.handle_find(ui, path, actions); self.update_marks_sides(db, ui.ctx()); // `CP_MARKS_DEMO=1`: made-up marks for the first rows (screenshots of the column). if std::env::var_os("CP_MARKS_DEMO").is_some() diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index f4312f2..998bd43 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -107,6 +107,8 @@ pub enum LibraryAction { path: PathBuf, records: Vec, filter: chess_import::chessbase::base::Filter, + /// The conditions in words, for the question and the summary. + about: String, }, EditGameData { path: PathBuf, @@ -1720,6 +1722,7 @@ impl Library { .entry(path.clone()) .or_insert_with(|| LargeView::for_database(&db, online)); let notes = self.info.get(&path).map_or(0, |i| i.notes.len()); + view.set_marks_db(&db); if view.marks.is_none() { let marks = self .marks