diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 5e67c20..d12e7f5 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -24,7 +24,12 @@ use crate::sound::SoundPlayer; /// Results of work done off the UI thread (file dialogs, engine checks). enum Async { + /// Databases chosen in a dialog (none: it was cancelled). DatabasesPicked(Vec), + /// Databases dropped on the window. + DatabasesDropped(Vec), + /// Files dropped on the window that are no longer there (their names). + Missing(Vec), /// Files not opened: too big for a browser (name, bytes). #[cfg(web)] TooBig(Vec<(String, u64)>), @@ -257,8 +262,9 @@ pub struct App { close_after_save: Option, /// The offer to download Stockfish when an action needs an engine. engine_offer: crate::engine_offer::EngineOffer, - /// What waits for an engine of the user's to be probed (`review_engine`). - review_wait: Option, + /// What waits for an engine of the user's to be probed (`review_engine`): at most + /// one game analysis and one search for opening errors. + review_wait: Vec, offer_hook_done: bool, /// What only the desktop program has: online games, updates. #[cfg(not(web))] @@ -508,7 +514,7 @@ impl App { prep_quit_ask: false, prep_quit_ok: false, engine_offer: crate::engine_offer::EngineOffer::new(), - review_wait: None, + review_wait: Vec::new(), offer_hook_done: false, #[cfg(not(web))] desktop, @@ -981,7 +987,10 @@ impl App { } PrepAction::EngineEnded => {} PrepAction::NeedEngine => { - self.need_review_engine(ctx, crate::engine_offer::Pending::OpeningErrors) + if let Some(prep) = self.prep.as_ref().map(|p| p.serial) { + let pending = crate::engine_offer::Pending::OpeningErrors { prep }; + self.need_review_engine(ctx, pending); + } } PrepAction::SettingsChanged => self.settings_dirty = true, PrepAction::Toast(m) => self.toast(ctx, m), @@ -2417,7 +2426,7 @@ impl App { fn pick_databases(&self, ctx: &egui::Context) { let (tx, ctx) = (self.tx.clone(), ctx.clone()); crate::platform::files::pick_databases(move |picked| { - send_picked(&tx, picked); + send_picked(&tx, picked, false); ctx.request_repaint(); }); } @@ -2487,10 +2496,7 @@ impl App { ); } Async::NotDatabases(names) => { - let mut files = names.iter().take(3).cloned().collect::>().join(", "); - if names.len() > 3 { - files.push_str(", …"); - } + let files = names_text(&names); self.toast( ctx, trf( @@ -2501,9 +2507,37 @@ impl App { } #[cfg(web)] Async::CopyKept(path, kept) => self.copy_kept(ctx, path, kept), + Async::Missing(names) => { + let files = names_text(&names); + self.toast(ctx, trf("Not found: {files}", &[("files", &files)])); + } + Async::DatabasesDropped(paths) => { + // As «Add database»; the game on the screen stays, so it is told. + for p in paths.iter().rev() { + self.settings.touch_database(p); + } + if let Some(first) = paths.first() { + self.library.select_db(first, ctx); + } + self.settings_dirty = true; + if self.game.is_some() { + let names: Vec = + paths.iter().map(|p| own_db::base_name(p)).collect(); + let files = names_text(&names); + self.toast( + ctx, + trf("Added to the shelf: {files}", &[("files", &files)]), + ); + } + } Async::DatabasesPicked(paths) => { - // The file chosen again takes the place of the one gone. - if let Some(old) = self.choosing_again.take() { + // The file chosen again takes the place of the one gone (a cancelled + // dialog ends «Choose again» too). + let old = self.choosing_again.take(); + if paths.is_empty() { + continue; + } + if let Some(old) = old { self.settings.databases.retain(|d| *d != old); self.library.forget(&old); crate::platform::files::forget(&old); @@ -2780,8 +2814,8 @@ impl App { let own_search = matches!( pending, Some( - crate::engine_offer::Pending::GameAnalysis - | crate::engine_offer::Pending::OpeningErrors + crate::engine_offer::Pending::GameAnalysis { .. } + | crate::engine_offer::Pending::OpeningErrors { .. } ) ); if !own_search || self.settings.active_engine().is_none() { @@ -2793,34 +2827,63 @@ impl App { /// The game analysis or the opening errors found no engine to search with: a /// Stockfish 19 of the user's that searches as ours is taken (probed first, in the - /// background: the action waits for it), else ours is offered for download, saying - /// what the user's engine is. + /// background: the action waits for it, on its own game or preparation), else ours + /// is offered for download, saying why the user's engine does not do. fn need_review_engine(&mut self, ctx: &egui::Context, pending: crate::engine_offer::Pending) { - use crate::review_engine::Lookup; crate::review_engine::set_candidates(&self.settings); + if self.review_wait.is_empty() { + self.toast( + ctx, + tr("Checking whether your engine can run the analysis…"), + ); + } + // One wait per kind: the newer request of a kind takes its place, the other + // kind keeps its own. + let same_kind = |p: &crate::engine_offer::Pending| { + std::mem::discriminant(p) == std::mem::discriminant(&pending) + }; + self.review_wait.retain(|p| !same_kind(p)); + self.review_wait.push(pending); + self.poll_review_wait(ctx); + } + + /// The actions waiting for an engine of the user's to be probed: dropped when their + /// game or preparation is no longer there; when the probe is done, started, or the + /// download of ours is offered for the latest of them. + fn poll_review_wait(&mut self, ctx: &egui::Context) { + use crate::review_engine::Lookup; + let (game, prep) = ( + self.game.as_ref().map(|g| g.serial), + self.prep.as_ref().map(|p| p.serial), + ); + self.review_wait.retain(|p| still_waiting(p, game, prep)); + if self.review_wait.is_empty() { + return; + } match crate::review_engine::lookup(ctx) { + Lookup::Checking => {} Lookup::Ready(_) => { - self.review_wait = None; - self.run_engine_pending(ctx, Some(pending)); - } - Lookup::Checking => { - if self.review_wait.is_none() { - self.toast(ctx, tr("Checking the Stockfish of the settings…")); + for p in std::mem::take(&mut self.review_wait) { + self.run_engine_pending(ctx, Some(p)); } - self.review_wait = Some(pending); } - Lookup::Other(name) => { - self.review_wait = None; - self.engine_offer.ask_instead_of(pending, name); + Lookup::Unfit(unfit) => { + let waiting = std::mem::take(&mut self.review_wait); + if let Some(p) = waiting.last() { + self.engine_offer.ask_instead_of(*p, unfit); + } } Lookup::None => { - self.review_wait = None; - self.engine_offer.ask(pending, &self.settings); + let waiting = std::mem::take(&mut self.review_wait); + if let Some(p) = waiting.last() { + self.engine_offer.ask(*p, &self.settings); + } } } } - /// Runs what the user was doing when an engine had to be found first. + /// Runs what the user was doing when an engine had to be found first: on the game + /// or the preparation it was asked on, if it is still there. fn run_engine_pending( &mut self, ctx: &egui::Context, @@ -2832,9 +2895,9 @@ impl App { self.toggle_engine(ctx); } } - Some(crate::engine_offer::Pending::GameAnalysis) => { - let actions = match self.game.as_mut() { - Some(g) => g.start_review_now(ctx), + Some(crate::engine_offer::Pending::GameAnalysis { game, full }) => { + let actions = match self.game.as_mut().filter(|g| g.serial == game) { + Some(g) => g.start_review_now(ctx, full), None => Vec::new(), }; for a in actions { @@ -2848,8 +2911,8 @@ impl App { } } } - Some(crate::engine_offer::Pending::OpeningErrors) => { - let actions = match self.prep.as_mut() { + Some(crate::engine_offer::Pending::OpeningErrors { prep }) => { + let actions = match self.prep.as_mut().filter(|p| p.serial == prep) { Some(p) => p.start_after_engine(ctx), None => Vec::new(), }; @@ -2946,7 +3009,7 @@ impl App { fn dropped_files(&mut self, ctx: &egui::Context) { let (tx, waker) = (self.tx.clone(), ctx.clone()); crate::platform::files::take_dropped(ctx, move |picked| { - send_picked(&tx, picked); + send_picked(&tx, picked, true); waker.request_repaint(); }); if crate::platform::files::dragging(ctx) { @@ -2955,16 +3018,36 @@ impl App { egui::Order::Foreground, egui::Id::new("dropping files"), )); + // The window tinted and framed in the accent colour; the words on a card of + // the window's own background, readable in both themes. let visuals = ctx.global_style().visuals.clone(); let accent = visuals.selection.bg_fill; - painter.rect_filled(rect, 0.0, accent.gamma_multiply(0.12)); - painter.text( - rect.center(), - egui::Align2::CENTER_CENTER, - tr("Release to open"), + painter.rect_filled(rect, 0.0, accent.gamma_multiply(0.28)); + painter.rect_stroke( + rect.shrink(2.0), + 6.0, + egui::Stroke::new(4.0, accent), + egui::StrokeKind::Inside, + ); + let galley = painter.layout_no_wrap( + tr("Release to open").to_owned(), egui::FontId::proportional(22.0), visuals.strong_text_color(), ); + let card = + egui::Rect::from_center_size(rect.center(), galley.size() + egui::vec2(48.0, 32.0)); + painter.rect( + card, + 10.0, + visuals.window_fill, + egui::Stroke::new(2.0, accent), + egui::StrokeKind::Inside, + ); + painter.galley( + card.center() - galley.size() / 2.0, + galley, + visuals.strong_text_color(), + ); } } @@ -3108,7 +3191,7 @@ impl App { fn pick_database_folder(&self, ctx: &egui::Context) { let (tx, ctx) = (self.tx.clone(), ctx.clone()); crate::platform::files::pick_database_folder(move |picked| { - send_picked(&tx, picked); + send_picked(&tx, picked, false); ctx.request_repaint(); }); } @@ -3463,8 +3546,8 @@ impl eframe::App for App { self.engine_offer.start(&ctx); } } - if let Some(p) = self.review_wait { - self.need_review_engine(&ctx, p); + if !self.review_wait.is_empty() { + self.poll_review_wait(&ctx); } self.offer_events(&ctx); self.page_frame(&ctx); @@ -3594,8 +3677,11 @@ impl eframe::App for App { self.request_close(&ctx, CloseIntent::ReturnToPrevious); } } - GameAction::NeedEngine => { - self.need_review_engine(&ctx, crate::engine_offer::Pending::GameAnalysis) + GameAction::NeedEngine { full } => { + if let Some(game) = self.game.as_ref().map(|g| g.serial) { + let pending = crate::engine_offer::Pending::GameAnalysis { game, full }; + self.need_review_engine(&ctx, pending); + } } GameAction::Sound(s) => self.play(s), GameAction::CopyText(text, msg) => { @@ -4022,6 +4108,7 @@ impl eframe::App for App { fn on_exit(&mut self) { self.analysis.stop(); + crate::review_engine::shutdown(); if let Some(p) = self.prep.as_mut() { p.save(); } @@ -4038,10 +4125,19 @@ impl eframe::App for App { } /// What the user chose or dropped, to the screen. -fn send_picked(tx: &Sender, picked: crate::platform::files::Picked) { - if !picked.paths.is_empty() { +/// Sends what was chosen in a dialog (`dropped`: dropped on the window) to the screen. +/// A dialog's choice is sent even when empty (cancelled): «Choose again» ends with it. +fn send_picked(tx: &Sender, picked: crate::platform::files::Picked, dropped: bool) { + if dropped { + if !picked.paths.is_empty() { + let _ = tx.send(Async::DatabasesDropped(picked.paths)); + } + } else { let _ = tx.send(Async::DatabasesPicked(picked.paths)); } + if !picked.missing.is_empty() { + let _ = tx.send(Async::Missing(picked.missing)); + } if picked.empty_folder { let _ = tx.send(Async::EmptyFolder); } @@ -4059,6 +4155,35 @@ fn send_picked(tx: &Sender, picked: crate::platform::files::Picked) { } } +/// Whether an action waiting for an engine still has its screen: the game (by its +/// serial) or the preparation on which it was asked. +fn still_waiting( + pending: &crate::engine_offer::Pending, + game: Option, + prep: Option, +) -> bool { + use crate::engine_offer::Pending; + match pending { + Pending::GameAnalysis { game: g, .. } => Some(*g) == game, + Pending::OpeningErrors { prep: p } => Some(*p) == prep, + Pending::LiveAnalysis => false, + } +} + +/// Files' names for a message: at most three, each at most 40 characters. +fn names_text(names: &[String]) -> String { + let mut text = names + .iter() + .take(3) + .map(|n| crate::widgets::shorten(n, 40)) + .collect::>() + .join(", "); + if names.len() > 3 { + text.push_str(", …"); + } + text +} + fn sanitize(s: &str) -> String { s.chars() .map(|c| match c { @@ -4068,3 +4193,36 @@ fn sanitize(s: &str) -> String { }) .collect::() } + +#[cfg(test)] +mod waiting_tests { + use super::{names_text, still_waiting}; + use crate::engine_offer::Pending; + + /// An analysis waiting for an engine starts on its own game only: another game on + /// the screen, or none, drops it; the two kinds wait apart. + #[test] + fn a_waiting_analysis_belongs_to_its_game() { + let review = Pending::GameAnalysis { + game: 7, + full: true, + }; + let errors = Pending::OpeningErrors { prep: 3 }; + assert!(still_waiting(&review, Some(7), None)); + assert!(!still_waiting(&review, Some(8), Some(3))); + assert!(!still_waiting(&review, None, Some(3))); + assert!(still_waiting(&errors, Some(8), Some(3))); + assert!(!still_waiting(&errors, Some(7), Some(4))); + assert!(!still_waiting(&Pending::LiveAnalysis, Some(7), Some(3))); + } + + #[test] + fn names_in_messages_are_short() { + let names: Vec = ["a.pgn", "b.pgn", "c.pgn", "d.pgn"] + .map(String::from) + .into(); + assert_eq!(names_text(&names), "a.pgn, b.pgn, c.pgn, …"); + let long = vec!["x".repeat(100) + ".pgn"]; + assert_eq!(names_text(&long).chars().count(), 40); + } +} diff --git a/apps/desktop/src/engine_offer.rs b/apps/desktop/src/engine_offer.rs index a5fc98e..40828cf 100644 --- a/apps/desktop/src/engine_offer.rs +++ b/apps/desktop/src/engine_offer.rs @@ -18,9 +18,23 @@ pub const DOWNLOAD_INDICATOR: &str = "download_indicator"; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Pending { LiveAnalysis, - GameAnalysis, - /// The opponent preparation's search for opening errors. - OpeningErrors, + /// The analysis of the game on the screen whose `serial` is `game` (no other game's); + /// `full`: anew, over evaluations read from the PGN. + GameAnalysis { + game: u64, + full: bool, + }, + /// The search for opening errors of the preparation whose `serial` is `prep`. + OpeningErrors { + prep: u64, + }, +} + +/// A number of its own for a screen an action waits on (a game, a preparation), so +/// that an engine arriving later starts it there and nowhere else. +pub fn next_serial() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } /// What the owner should do. @@ -45,9 +59,8 @@ enum Mode { /// The game analysis or the opening errors, which need ChessPenguin's Stockfish 19 /// itself (their search is the same on every computer): only its download helps. Own, - /// The same, when the user's engine (its name here) is another one: another - /// version, network or build of Stockfish, or another engine (`review_engine`). - OwnInstead(String), + /// The same, when the user's engine does not do (`review_engine`): it is named. + OwnInstead(crate::review_engine::Unfit), } pub struct EngineOffer { @@ -98,11 +111,11 @@ impl EngineOffer { } /// Opens the offer of ChessPenguin's Stockfish 19 for the game analysis or the - /// opening errors, saying that the user's engine `name` is not it. - pub fn ask_instead_of(&mut self, pending: Pending, name: String) { + /// opening errors, saying why the user's engine does not do. + pub fn ask_instead_of(&mut self, pending: Pending, unfit: crate::review_engine::Unfit) { self.pending = Some(pending); self.failure = None; - self.mode = Mode::OwnInstead(name); + self.mode = Mode::OwnInstead(unfit); self.open = true; } @@ -140,13 +153,13 @@ impl EngineOffer { events.push(OfferEvent::Installed(pending)); events.push(OfferEvent::Toast( match pending { - Some(Pending::GameAnalysis) => { + Some(Pending::GameAnalysis { .. }) => { tr("Stockfish installed — game analysis started") } Some(Pending::LiveAnalysis) => { tr("Stockfish installed — analysis is on") } - Some(Pending::OpeningErrors) => { + Some(Pending::OpeningErrors { .. }) => { tr("Stockfish installed — the search for opening errors started") } None => tr("Stockfish installed"), @@ -245,19 +258,9 @@ impl EngineOffer { ) .into(), ), - Mode::OwnInstead(name) => ( + Mode::OwnInstead(unfit) => ( tr("Analysis needs Stockfish 19"), - if self.pending == Some(Pending::OpeningErrors) { - trf( - "The settings name {engine}. The search for opening errors needs Stockfish 19 itself, so that the marks are the same on every computer. Download Stockfish 19 ({mb} MB)?", - &[("engine", name), ("mb", &size)], - ) - } else { - trf( - "The settings name {engine}. Game analysis needs Stockfish 19 itself, so that the marks are the same on every computer. Download Stockfish 19 ({mb} MB)?", - &[("engine", name), ("mb", &size)], - ) - }, + instead_text(unfit, self.pending), ), }; ui.heading(title); @@ -285,12 +288,6 @@ impl EngineOffer { }); let size = trf("Size: {size}", &[("size", &format!("{size} MB"))]); ui.label(RichText::new(free.map_or(size.clone(), |f| format!("{size} · {f}"))).weak()); - } else if matches!(self.mode, Mode::OwnInstead(_)) { - // The size is in the question already. - ui.label(RichText::new(tr("Installed for your account only")).weak()) - .on_hover_text( - "https://github.com/official-stockfish/Stockfish/releases/tag/sf_19", - ); } else { ui.label( RichText::new(trf( @@ -391,10 +388,10 @@ impl EngineOffer { } ui.add_space(4.0); let after = match self.pending { - Some(Pending::GameAnalysis) => { + Some(Pending::GameAnalysis { .. }) => { tr("Game analysis will start by itself when the download finishes.") } - Some(Pending::OpeningErrors) => { + Some(Pending::OpeningErrors { .. }) => { tr("The search for opening errors will start by itself when the download finishes.") } _ => tr("Analysis will start by itself when the download finishes."), @@ -512,6 +509,62 @@ impl EngineOffer { } } +/// Why the user's engine does not do for the game analysis (or the opening errors), +/// what is offered instead, and that the analysis follows the download by itself. +fn instead_text(unfit: &crate::review_engine::Unfit, pending: Option) -> String { + use crate::review_engine::Why; + let errors = matches!(pending, Some(Pending::OpeningErrors { .. })); + let engine = crate::widgets::shorten(&unfit.name, 48); + let mut parts = vec![match unfit.why { + Why::Differs => tr( + "Your Stockfish 19 calculates differently from ChessPenguin's build (another build or network).", + ) + .to_owned(), + Why::NotStarted => trf("{engine} could not be started.", &[("engine", &engine)]), + Why::Other if unfit.from_settings => { + trf("The settings name {engine}.", &[("engine", &engine)]) + } + Why::Other => trf("The system has {engine}.", &[("engine", &engine)]), + }]; + parts.push( + match (unfit.why == Why::Differs, errors) { + (true, false) => tr( + "So that the marks are the same on every computer, game analysis runs on the official build.", + ), + (true, true) => tr( + "So that the marks are the same on every computer, the search for opening errors runs on the official build.", + ), + (false, false) => tr( + "Game analysis needs Stockfish 19 itself, so that the marks are the same on every computer.", + ), + (false, true) => tr( + "The search for opening errors needs Stockfish 19 itself, so that the marks are the same on every computer.", + ), + } + .to_owned(), + ); + parts.push( + if unfit.why == Why::Differs { + tr("Download it?") + } else { + tr("Download Stockfish 19?") + } + .to_owned(), + ); + if unfit.why != Why::NotStarted { + parts.push(tr("Your engine stays for position analysis.").to_owned()); + } + parts.push( + if errors { + tr("The search for opening errors will start by itself when the download finishes.") + } else { + tr("Game analysis will start by itself when the download finishes.") + } + .to_owned(), + ); + parts.join(" ") +} + /// What to tell the user about a failure, and the technical details (collapsed). fn failure_text(f: &Failure) -> (String, Option) { match f { @@ -545,3 +598,45 @@ fn failure_text(f: &Failure) -> (String, Option) { ), } } + +#[cfg(test)] +mod tests { + use super::{Pending, instead_text}; + use crate::review_engine::{Unfit, Why}; + + fn text(why: Why, from_settings: bool, pending: Pending) -> String { + let unfit = Unfit { + name: "Rodent V 1.2".into(), + from_settings, + why, + }; + instead_text(&unfit, Some(pending)) + } + + /// The offer says why the user's engine does not do and where it is from; the + /// user's engine stays for the live analysis, the analysis follows the download. + #[test] + fn the_offer_says_why_the_users_engine_does_not_do() { + let game = Pending::GameAnalysis { + game: 1, + full: false, + }; + let errors = Pending::OpeningErrors { prep: 1 }; + let t = text(Why::Other, true, game); + assert!(t.starts_with("The settings name Rodent V 1.2."), "{t}"); + assert!(t.contains("Your engine stays for position analysis.")); + assert!(t.ends_with("Game analysis will start by itself when the download finishes.")); + let t = text(Why::Other, false, errors); + assert!(t.starts_with("The system has Rodent V 1.2."), "{t}"); + assert!(t.contains("The search for opening errors needs Stockfish 19 itself")); + let t = text(Why::Differs, true, game); + assert!( + t.starts_with("Your Stockfish 19 calculates differently"), + "{t}" + ); + assert!(t.contains("Download it?")); + let t = text(Why::NotStarted, true, game); + assert!(t.starts_with("Rodent V 1.2 could not be started."), "{t}"); + assert!(!t.contains("stays for position analysis")); + } +} diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 24b649f..4e54fa6 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -49,6 +49,8 @@ impl Preview { } pub struct GameView { + /// This view's own number (`engine_offer::next_serial`). + pub serial: u64, pub game: Game, pub source: Option, /// A new game meant for this database (the table's «+ Game»): Ctrl+S adds it there. @@ -163,8 +165,11 @@ pub enum GameAction { ResumeLive, /// Find the current position in a database (`None`: the last chosen one). FindPosition(Option), - /// Game analysis needs an engine that is not there yet (offer to download one). - NeedEngine, + /// Game analysis (`full`: anew) needs an engine that is not there yet (offer to + /// download one). + NeedEngine { + full: bool, + }, /// The reference tab: use / load a database, open one of its games. ReferenceChoose(std::path::PathBuf), ReferenceLoad(std::path::PathBuf), @@ -186,6 +191,7 @@ impl GameView { let flipped = false; let review = Review::new(&game); Self { + serial: crate::engine_offer::next_serial(), game, source, diagnostics, @@ -859,7 +865,7 @@ impl GameView { /// download ours. fn start_review(&mut self, full: bool, ctx: &egui::Context, actions: &mut Vec) { let Some(path) = crate::review_engine::engine() else { - actions.push(GameAction::NeedEngine); + actions.push(GameAction::NeedEngine { full }); return; }; if self.review.start(&self.game, &path, full, ctx) { @@ -2129,10 +2135,11 @@ impl GameView { } } - /// Starts the game analysis right away (after an engine was installed for it). - pub fn start_review_now(&mut self, ctx: &egui::Context) -> Vec { + /// Starts the game analysis right away (after an engine was found or installed for + /// it); `full` as it was asked. + pub fn start_review_now(&mut self, ctx: &egui::Context, full: bool) -> Vec { let mut actions = Vec::new(); - self.start_review(false, ctx, &mut actions); + self.start_review(full, ctx, &mut actions); actions } diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 5241812..73e4e2c 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -15393,37 +15393,169 @@ const ROWS: &[[&str; 9]] = &[ "{judgement}: жақсысы {best} ({before} → {after}) · {n} партияда", ], [ - "The settings name {engine}. Game analysis needs Stockfish 19 itself, so that the marks are the same on every computer. Download Stockfish 19 ({mb} MB)?", - "В настройках указан {engine}. Для разбора партии нужен именно Stockfish 19 — так отметки одинаковы на любом компьютере. Скачать Stockfish 19 ({mb} МБ)?", - "Les réglages indiquent {engine}. L’analyse de partie a besoin de Stockfish 19 lui-même, pour que les signes soient les mêmes sur tous les ordinateurs. Télécharger Stockfish 19 ({mb} Mo) ?", - "In den Einstellungen steht {engine}. Die Partieanalyse braucht genau Stockfish 19, damit die Zeichen auf jedem Computer gleich sind. Stockfish 19 herunterladen ({mb} MB)?", - "En los ajustes figura {engine}. El análisis de partidas necesita justamente Stockfish 19, para que los signos sean iguales en cualquier ordenador. ¿Descargar Stockfish 19 ({mb} MB)?", - "Nelle impostazioni è indicato {engine}. L’analisi della partita richiede proprio Stockfish 19, perché i segni siano uguali su ogni computer. Scaricare Stockfish 19 ({mb} MB)?", - "Nas configurações está {engine}. A análise de partidas precisa justamente do Stockfish 19, para que as marcas sejam iguais em qualquer computador. Baixar o Stockfish 19 ({mb} MB)?", - "Sozlamalarda {engine} ko‘rsatilgan. Partiya tahlili uchun aynan Stockfish 19 kerak — belgilar har qanday kompyuterda bir xil chiqadi. Stockfish 19 yuklab olinsinmi ({mb} MB)?", - "Баптауларда {engine} көрсетілген. Партияны талдау үшін дәл Stockfish 19 керек — белгілер кез келген компьютерде бірдей болады. Stockfish 19 жүктеп алу керек пе ({mb} МБ)?", + "Checking whether your engine can run the analysis…", + "Проверяю, подойдёт ли ваш движок для разбора…", + "Vérification : votre moteur peut-il faire l’analyse…", + "Es wird geprüft, ob Ihre Engine die Analyse machen kann…", + "Comprobando si su motor puede hacer el análisis…", + "Verifica se il tuo motore può fare l’analisi…", + "Verificando se o seu motor pode fazer a análise…", + "Dvigatelingiz tahlilga yaraydimi, tekshirilmoqda…", + "Қозғалтқышыңыз талдауға жарай ма, тексерілуде…", ], [ - "The settings name {engine}. The search for opening errors needs Stockfish 19 itself, so that the marks are the same on every computer. Download Stockfish 19 ({mb} MB)?", - "В настройках указан {engine}. Для поиска ошибок в дебютах нужен именно Stockfish 19 — так отметки одинаковы на любом компьютере. Скачать Stockfish 19 ({mb} МБ)?", - "Les réglages indiquent {engine}. La recherche d’erreurs d’ouverture a besoin de Stockfish 19 lui-même, pour que les signes soient les mêmes sur tous les ordinateurs. Télécharger Stockfish 19 ({mb} Mo) ?", - "In den Einstellungen steht {engine}. Die Suche nach Eröffnungsfehlern braucht genau Stockfish 19, damit die Zeichen auf jedem Computer gleich sind. Stockfish 19 herunterladen ({mb} MB)?", - "En los ajustes figura {engine}. La búsqueda de errores de apertura necesita justamente Stockfish 19, para que los signos sean iguales en cualquier ordenador. ¿Descargar Stockfish 19 ({mb} MB)?", - "Nelle impostazioni è indicato {engine}. La ricerca degli errori d’apertura richiede proprio Stockfish 19, perché i segni siano uguali su ogni computer. Scaricare Stockfish 19 ({mb} MB)?", - "Nas configurações está {engine}. A procura de erros de abertura precisa justamente do Stockfish 19, para que as marcas sejam iguais em qualquer computador. Baixar o Stockfish 19 ({mb} MB)?", - "Sozlamalarda {engine} ko‘rsatilgan. Debyut xatolarini qidirish uchun aynan Stockfish 19 kerak — belgilar har qanday kompyuterda bir xil chiqadi. Stockfish 19 yuklab olinsinmi ({mb} MB)?", - "Баптауларда {engine} көрсетілген. Дебют қателерін іздеу үшін дәл Stockfish 19 керек — белгілер кез келген компьютерде бірдей болады. Stockfish 19 жүктеп алу керек пе ({mb} МБ)?", + "Your Stockfish 19 calculates differently from ChessPenguin's build (another build or network).", + "Ваш Stockfish 19 считает иначе, чем сборка ChessPenguin (другая сборка или сеть).", + "Votre Stockfish 19 calcule autrement que la version de ChessPenguin (autre compilation ou autre réseau).", + "Ihr Stockfish 19 rechnet anders als der Build von ChessPenguin (anderer Build oder anderes Netz).", + "Su Stockfish 19 calcula de otra manera que la compilación de ChessPenguin (otra compilación u otra red).", + "Il tuo Stockfish 19 calcola diversamente dalla build di ChessPenguin (un’altra build o un’altra rete).", + "Seu Stockfish 19 calcula de outro jeito que a versão do ChessPenguin (outra compilação ou outra rede).", + "Sizning Stockfish 19 ChessPenguin yig‘masidan boshqacha hisoblaydi (boshqa yig‘ma yoki tarmoq).", + "Сіздің Stockfish 19 ChessPenguin жинағынан басқаша есептейді (басқа жинақ немесе желі).", ], [ - "Checking the Stockfish of the settings…", - "Проверяю Stockfish из настроек…", - "Vérification du Stockfish des réglages…", - "Der Stockfish aus den Einstellungen wird geprüft…", - "Comprobando el Stockfish de los ajustes…", - "Verifica dello Stockfish delle impostazioni…", - "Verificando o Stockfish das configurações…", - "Sozlamalardagi Stockfish tekshirilmoqda…", - "Баптаулардағы Stockfish тексерілуде…", + "{engine} could not be started.", + "Не удалось запустить {engine}.", + "Impossible de lancer {engine}.", + "{engine} konnte nicht gestartet werden.", + "No se pudo iniciar {engine}.", + "Impossibile avviare {engine}.", + "Não foi possível iniciar {engine}.", + "{engine} ishga tushmadi.", + "{engine} іске қосылмады.", + ], + [ + "The settings name {engine}.", + "В настройках указан {engine}.", + "Les réglages indiquent {engine}.", + "In den Einstellungen steht {engine}.", + "En los ajustes figura {engine}.", + "Nelle impostazioni è indicato {engine}.", + "Nas configurações está {engine}.", + "Sozlamalarda {engine} ko‘rsatilgan.", + "Баптауларда {engine} көрсетілген.", + ], + [ + "The system has {engine}.", + "В системе найден {engine}.", + "Le système contient {engine}.", + "Im System gefunden: {engine}.", + "En el sistema se encontró {engine}.", + "Nel sistema è stato trovato {engine}.", + "No sistema foi encontrado {engine}.", + "Tizimda {engine} topildi.", + "Жүйеде {engine} табылды.", + ], + [ + "So that the marks are the same on every computer, game analysis runs on the official build.", + "Чтобы отметки совпадали на всех компьютерах, разбор партии идёт на официальной сборке.", + "Pour que les signes soient les mêmes sur tous les ordinateurs, l’analyse de partie se fait avec la version officielle.", + "Damit die Zeichen auf jedem Computer gleich sind, läuft die Partieanalyse mit dem offiziellen Build.", + "Para que los signos sean iguales en cualquier ordenador, el análisis de partidas usa la compilación oficial.", + "Perché i segni siano uguali su ogni computer, l’analisi della partita usa la build ufficiale.", + "Para que as marcas sejam iguais em qualquer computador, a análise de partidas usa a versão oficial.", + "Belgilar har qanday kompyuterda bir xil bo‘lishi uchun partiya tahlili rasmiy yig‘mada bo‘ladi.", + "Белгілер кез келген компьютерде бірдей болуы үшін партияны талдау ресми жинақта жүреді.", + ], + [ + "So that the marks are the same on every computer, the search for opening errors runs on the official build.", + "Чтобы отметки совпадали на всех компьютерах, поиск ошибок в дебютах идёт на официальной сборке.", + "Pour que les signes soient les mêmes sur tous les ordinateurs, la recherche d’erreurs d’ouverture se fait avec la version officielle.", + "Damit die Zeichen auf jedem Computer gleich sind, läuft die Suche nach Eröffnungsfehlern mit dem offiziellen Build.", + "Para que los signos sean iguales en cualquier ordenador, la búsqueda de errores de apertura usa la compilación oficial.", + "Perché i segni siano uguali su ogni computer, la ricerca degli errori d’apertura usa la build ufficiale.", + "Para que as marcas sejam iguais em qualquer computador, a procura de erros de abertura usa a versão oficial.", + "Belgilar har qanday kompyuterda bir xil bo‘lishi uchun debyut xatolarini qidirish rasmiy yig‘mada bo‘ladi.", + "Белгілер кез келген компьютерде бірдей болуы үшін дебют қателерін іздеу ресми жинақта жүреді.", + ], + [ + "Game analysis needs Stockfish 19 itself, so that the marks are the same on every computer.", + "Для разбора партии нужен именно Stockfish 19 — так отметки одинаковы на любом компьютере.", + "L’analyse de partie a besoin de Stockfish 19 lui-même, pour que les signes soient les mêmes sur tous les ordinateurs.", + "Die Partieanalyse braucht genau Stockfish 19, damit die Zeichen auf jedem Computer gleich sind.", + "El análisis de partidas necesita justamente Stockfish 19, para que los signos sean iguales en cualquier ordenador.", + "L’analisi della partita richiede proprio Stockfish 19, perché i segni siano uguali su ogni computer.", + "A análise de partidas precisa justamente do Stockfish 19, para que as marcas sejam iguais em qualquer computador.", + "Partiya tahlili uchun aynan Stockfish 19 kerak — belgilar har qanday kompyuterda bir xil chiqadi.", + "Партияны талдау үшін дәл Stockfish 19 керек — белгілер кез келген компьютерде бірдей болады.", + ], + [ + "The search for opening errors needs Stockfish 19 itself, so that the marks are the same on every computer.", + "Для поиска ошибок в дебютах нужен именно Stockfish 19 — так отметки одинаковы на любом компьютере.", + "La recherche d’erreurs d’ouverture a besoin de Stockfish 19 lui-même, pour que les signes soient les mêmes sur tous les ordinateurs.", + "Die Suche nach Eröffnungsfehlern braucht genau Stockfish 19, damit die Zeichen auf jedem Computer gleich sind.", + "La búsqueda de errores de apertura necesita justamente Stockfish 19, para que los signos sean iguales en cualquier ordenador.", + "La ricerca degli errori d’apertura richiede proprio Stockfish 19, perché i segni siano uguali su ogni computer.", + "A procura de erros de abertura precisa justamente do Stockfish 19, para que as marcas sejam iguais em qualquer computador.", + "Debyut xatolarini qidirish uchun aynan Stockfish 19 kerak — belgilar har qanday kompyuterda bir xil chiqadi.", + "Дебют қателерін іздеу үшін дәл Stockfish 19 керек — белгілер кез келген компьютерде бірдей болады.", + ], + [ + "Download it?", + "Скачать её?", + "La télécharger ?", + "Herunterladen?", + "¿Descargarla?", + "Scaricarla?", + "Baixá-la?", + "Yuklab olinsinmi?", + "Жүктеп алу керек пе?", + ], + [ + "Download Stockfish 19?", + "Скачать Stockfish 19?", + "Télécharger Stockfish 19 ?", + "Stockfish 19 herunterladen?", + "¿Descargar Stockfish 19?", + "Scaricare Stockfish 19?", + "Baixar o Stockfish 19?", + "Stockfish 19 yuklab olinsinmi?", + "Stockfish 19 жүктеп алу керек пе?", + ], + [ + "Your engine stays for position analysis.", + "Ваш движок остаётся для анализа позиции.", + "Votre moteur reste pour l’analyse de position.", + "Ihre Engine bleibt für die Stellungsanalyse.", + "Su motor sigue para el análisis de posiciones.", + "Il tuo motore resta per l’analisi della posizione.", + "Seu motor continua para a análise de posição.", + "Dvigatelingiz pozitsiya tahlili uchun qoladi.", + "Қозғалтқышыңыз позицияны талдау үшін қалады.", + ], + [ + "Not found: {files}", + "Не найдено: {files}", + "Introuvable : {files}", + "Nicht gefunden: {files}", + "No encontrado: {files}", + "Non trovato: {files}", + "Não encontrado: {files}", + "Topilmadi: {files}", + "Табылмады: {files}", + ], + [ + "Added to the shelf: {files}", + "Добавлено на полку: {files}", + "Ajouté à l’étagère : {files}", + "Zum Regal hinzugefügt: {files}", + "Añadido al estante: {files}", + "Aggiunto allo scaffale: {files}", + "Adicionado à estante: {files}", + "Javonga qo‘shildi: {files}", + "Сөреге қосылды: {files}", + ], + [ + "The engine is no longer the Stockfish 19 that was checked. Start the analysis again.", + "Движок уже не тот Stockfish 19, что прошёл проверку. Запустите разбор снова.", + "Le moteur n’est plus le Stockfish 19 vérifié. Relancez l’analyse.", + "Die Engine ist nicht mehr der geprüfte Stockfish 19. Starten Sie die Analyse erneut.", + "El motor ya no es el Stockfish 19 comprobado. Inicie el análisis de nuevo.", + "Il motore non è più lo Stockfish 19 verificato. Avvia di nuovo l’analisi.", + "O motor não é mais o Stockfish 19 verificado. Inicie a análise de novo.", + "Dvigatel endi tekshirilgan Stockfish 19 emas. Tahlilni qaytadan boshlang.", + "Қозғалтқыш енді тексерілген Stockfish 19 емес. Талдауды қайта бастаңыз.", ], [ "Analysis needs Stockfish 19", diff --git a/apps/desktop/src/maia_download.rs b/apps/desktop/src/maia_download.rs index 3af1a95..3ca7d00 100644 --- a/apps/desktop/src/maia_download.rs +++ b/apps/desktop/src/maia_download.rs @@ -60,7 +60,7 @@ impl Published for Model { } /// `/maia/`. -fn dir() -> Option { +pub fn dir() -> Option { directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") .map(|d| d.data_local_dir().join("maia")) } diff --git a/apps/desktop/src/platform/files.rs b/apps/desktop/src/platform/files.rs index bde6f52..a67d224 100644 --- a/apps/desktop/src/platform/files.rs +++ b/apps/desktop/src/platform/files.rs @@ -28,6 +28,8 @@ pub struct Picked { pub incomplete: Vec, pub empty_folder: bool, pub unsupported: Vec, + /// Files dropped on a computer's window that are no longer there (their names). + pub missing: Vec, } /// The files the user gave the page, made databases: the ChessBase ones of their @@ -293,34 +295,77 @@ pub fn dragging(ctx: &egui::Context) -> bool { ctx.input(|i| !i.raw.hovered_files.is_empty()) } +/// The extensions of the other files of a ChessBase database (beside its `.cbh`). +#[cfg(not(web))] +const CHESSBASE_PARTS: [&str; 14] = [ + "cbg", "cba", "cbp", "cbt", "cbc", "cbs", "cbj", "cbe", "cbm", "cbb", "cbgi", "cbtt", "cbpi", + "cbl", +]; + /// The databases of the files and folders dropped on a computer's window: a file of -/// [`chess_import::EXTENSIONS`] is one; any other file of a ChessBase database (its -/// `.cbg`, `.cba`, …: a `.cbh` of the same name beside it) stands for that database; -/// a folder gives the databases in it. Each database once, in the order dropped. +/// [`chess_import::EXTENSIONS`] is one; another file of a ChessBase database (its +/// `.cbg`, `.cba`, …: [`CHESSBASE_PARTS`]) stands for the `.cbh` of the same name +/// beside it; a folder gives the databases in it. Each database once (its real file), +/// in the order dropped; a file no longer there and a file of no database are named. #[cfg(not(web))] fn sort_dropped(paths: &[PathBuf]) -> Picked { + use std::collections::{HashMap, HashSet}; let mut picked = Picked::default(); - let add = |p: PathBuf, picked: &mut Picked| { - if !picked.paths.contains(&p) { - picked.paths.push(p); - } + let mut seen = HashSet::new(); + // Each folder is listed once, however many of its files were dropped. + let mut listed: HashMap> = HashMap::new(); + let mut list = |dir: &std::path::Path| -> Vec { + listed + .entry(dir.to_path_buf()) + .or_insert_with(|| { + let mut files: Vec = std::fs::read_dir(dir) + .map(|entries| { + entries + .flatten() + .map(|e| e.path()) + .filter(|f| f.is_file()) + .collect() + }) + .unwrap_or_default(); + files.sort(); + files + }) + .clone() + }; + let name = |p: &std::path::Path| { + p.file_name() + .map_or_else(|| p.display().to_string(), |n| n.to_string_lossy().into()) }; for p in paths { - if p.is_dir() { - let found = databases_in(p); + let found = if p.is_dir() { + let found: Vec = list(p) + .into_iter() + .filter(|f| chess_import::EXTENSIONS.contains(&extension(f).as_str())) + .collect(); if found.is_empty() { picked.empty_folder = true; } - for f in found { - add(f, &mut picked); - } - } else if let Some(db) = database_of(p) { - add(db, &mut picked); + found + } else if !p.is_file() { + picked.missing.push(name(p)); + continue; } else { - let name = p - .file_name() - .map_or_else(|| p.display().to_string(), |n| n.to_string_lossy().into()); - picked.unsupported.push(name); + let ext = extension(p); + if chess_import::EXTENSIONS.contains(&ext.as_str()) { + vec![p.clone()] + } else if CHESSBASE_PARTS.contains(&ext.as_str()) + && let Some(cbh) = p.parent().and_then(|dir| cbh_beside(p, &list(dir))) + { + vec![cbh] + } else { + picked.unsupported.push(name(p)); + continue; + } + }; + for f in found { + if seen.insert(f.canonicalize().unwrap_or_else(|_| f.clone())) { + picked.paths.push(f); + } } } picked @@ -334,39 +379,19 @@ fn extension(p: &std::path::Path) -> String { .unwrap_or_default() } -/// The database the file `p` is, or is a part of. +/// The `.cbh` of the ChessBase database the file `part` belongs to, among the files +/// of its folder (names differ in case in sets copied from Windows). #[cfg(not(web))] -fn database_of(p: &std::path::Path) -> Option { - if chess_import::EXTENSIONS.contains(&extension(p).as_str()) { - return Some(p.to_path_buf()); - } - // A part of a ChessBase database: its `.cbh` beside it (in any case of letters). - let stem = p.file_stem()?.to_string_lossy().to_lowercase(); +fn cbh_beside(part: &std::path::Path, folder: &[PathBuf]) -> Option { + let stem = part.file_stem()?.to_string_lossy().to_lowercase(); let want = format!("{stem}.cbh"); - std::fs::read_dir(p.parent()?) - .ok()? - .flatten() - .map(|e| e.path()) + folder + .iter() .find(|f| { - f.is_file() - && f.file_name() - .is_some_and(|n| n.to_string_lossy().to_lowercase() == want) + f.file_name() + .is_some_and(|n| n.to_string_lossy().to_lowercase() == want) }) -} - -/// The databases in the folder `dir` (not in folders inside it), by name. -#[cfg(not(web))] -fn databases_in(dir: &std::path::Path) -> Vec { - let Ok(entries) = std::fs::read_dir(dir) else { - return Vec::new(); - }; - let mut found: Vec = entries - .flatten() - .map(|e| e.path()) - .filter(|f| f.is_file() && chess_import::EXTENSIONS.contains(&extension(f).as_str())) - .collect(); - found.sort(); - found + .cloned() } /// Gives `pgn` to the user as the file `name` (a download, where the browser puts @@ -392,9 +417,10 @@ mod tests { let archive = dir.join("set.7z"); let notes = dir.join("notes.txt"); let cbh = base.join("Mega.CBH"); - let parts = ["Mega.cbg", "Mega.cba", "Mega.cbj", "Mega.ini"].map(|n| base.join(n)); + let parts = ["Mega.cbg", "Mega.cba", "Mega.cbj", "Mega.CBTT"].map(|n| base.join(n)); + let ini = base.join("Mega.ini"); let lonely = dir.join("lost.cbg"); - for p in [&games, &archive, ¬es, &cbh, &lonely] { + for p in [&games, &archive, ¬es, &cbh, &lonely, &ini] { touch(p); } for p in &parts { @@ -415,22 +441,35 @@ mod tests { picked.paths, vec![games.clone(), archive.clone(), cbh.clone()] ); - assert!(picked.unsupported.is_empty()); + assert!(picked.unsupported.is_empty() && picked.missing.is_empty()); assert!(!picked.empty_folder); - // What is no database is named; a ChessBase part without its .cbh is none. - let picked = sort_dropped(&[notes.clone(), lonely.clone(), games.clone()]); + // What is no database is named: another file, a ChessBase part without its + // .cbh, a file of an unknown kind beside a .cbh. + let picked = sort_dropped(&[notes.clone(), lonely.clone(), ini.clone(), games.clone()]); assert_eq!(picked.paths, vec![games.clone()]); - assert_eq!( - picked.unsupported, - vec!["notes.txt".to_string(), "lost.cbg".into()] - ); + assert_eq!(picked.unsupported, ["notes.txt", "lost.cbg", "Mega.ini"]); + + // A file no longer there: named, not taken. + let picked = sort_dropped(&[dir.join("gone.pgn"), games.clone()]); + assert_eq!(picked.paths, vec![games.clone()]); + assert_eq!(picked.missing, ["gone.pgn"]); + assert!(picked.unsupported.is_empty()); // A folder: its databases (by name); one without any is told. let picked = sort_dropped(&[base.clone(), empty.clone()]); assert_eq!(picked.paths, vec![cbh.clone(), cbv.clone()]); assert!(picked.empty_folder); + // The same file by a link and by its own path: once. + #[cfg(unix)] + { + let link = dir.join("link.pgn"); + std::os::unix::fs::symlink(&games, &link).unwrap(); + let picked = sort_dropped(&[link.clone(), games.clone()]); + assert_eq!(picked.paths, vec![link]); + } + let _ = std::fs::remove_dir_all(&dir); } } diff --git a/apps/desktop/src/prep_ui.rs b/apps/desktop/src/prep_ui.rs index af8559a..1043c31 100644 --- a/apps/desktop/src/prep_ui.rs +++ b/apps/desktop/src/prep_ui.rs @@ -1087,6 +1087,8 @@ fn cache_dir() -> Option { } pub struct PrepScreen { + /// This screen's own number (`engine_offer::next_serial`). + pub serial: u64, pub path: PathBuf, db: Arc, db_name: String, @@ -1422,6 +1424,7 @@ impl PrepScreen { }; let names = start.player.names(&db); let mut screen = PrepScreen { + serial: crate::engine_offer::next_serial(), db_name: base_name(&start.path), path: start.path, db, diff --git a/apps/desktop/src/review.rs b/apps/desktop/src/review.rs index 60baa28..3b0dc11 100644 --- a/apps/desktop/src/review.rs +++ b/apps/desktop/src/review.rs @@ -3,8 +3,9 @@ //! evaluations, judgements, cache and the job itself are the `game-review` crate's, //! shared with the Android app. //! -//! The job uses engine processes of its own — ChessPenguin's Stockfish 19 with the fixed -//! search of `game_review::run`, the same on every computer, not the user's engine — and +//! The job uses engine processes of its own — Stockfish 19 (ChessPenguin's, or the user's +//! that searches the same, `review_engine`) with the fixed search of `game_review::run`, +//! the same on every computer — and //! never touches the game; writing the results into the game is a separate, undoable //! action ([`Review::write_to_game`]). @@ -108,17 +109,39 @@ pub fn spawn_job( std::thread::Builder::new() .name(name.to_owned()) .spawn(move || { + // A user's engine must still be the Stockfish 19 probed (a wrapper may + // start another program now): else the job stops at once, before any + // evaluation is taken, and the engine is probed again next time. + let mut changed = false; let result = game_review::run( engine_config(&path), &settings, targets, &cancel, &mut |e| { + if changed { + return; + } + if let JobEvent::Engine(name) = &e + && !crate::review_engine::name_fits(&path, name) + { + changed = true; + cancel.store(true, Ordering::Relaxed); + return; + } let _ = tx.send(JobMsg::Event(e)); ctx.request_repaint(); }, ); - let _ = tx.send(job_end(result)); + let end = if changed { + JobMsg::Failed( + tr("The engine is no longer the Stockfish 19 that was checked. Start the analysis again.") + .into(), + ) + } else { + job_end(result) + }; + let _ = tx.send(end); ctx.request_repaint(); }) .map(|_| JobRunner {}) diff --git a/apps/desktop/src/review_engine.rs b/apps/desktop/src/review_engine.rs index 04ced11..527a64c 100644 --- a/apps/desktop/src/review_engine.rs +++ b/apps/desktop/src/review_engine.rs @@ -1,12 +1,36 @@ //! The engine of the game analysis and the search for opening errors: ChessPenguin's //! Stockfish 19, or else a Stockfish 19 of the user's (from the settings, or the one in //! `PATH`) that searches exactly as ours (decision of 2026-10-31). Whether it does is -//! told by short searches of the analysis's fixed mode (`game_review::probe`), made on -//! a thread of their own; the verdict is remembered with the file's size and time, so -//! a file is probed once, and again only when it changes. +//! told by `game_review::probe` on a thread of its own: an engine not called +//! «Stockfish 19» is turned down at its `uci` answer, without a search; one that is +//! makes three short searches of the analysis's fixed mode. The verdict is remembered +//! for the real file (links followed) with its size and time, and with the probe's +//! reference: a file is probed once, again when it or the reference changes. An engine +//! that did not start is not remembered: it is tried again at the next request. use crate::engines::EngineLocation; +/// Why the user's engine does not do for the analysis. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Why { + /// Another engine, or another version of Stockfish. + Other, + /// It calls itself Stockfish 19 but searches otherwise (another build or network). + Differs, + /// It did not start or did not answer. + NotStarted, +} + +/// The user's engine that does not do: its name (`id name`, else what the settings +/// call it, else its file's name), where it is from, and why. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Unfit { + pub name: String, + /// From the settings (else `stockfish` found in `PATH`). + pub from_settings: bool, + pub why: Why, +} + /// The engine to analyse with, now. #[derive(Debug, PartialEq, Eq)] pub enum Lookup { @@ -14,9 +38,8 @@ pub enum Lookup { /// An engine of the user's is being probed: asked again when it is done (the /// screen is repainted then). Checking, - /// The user's engines are other ones: the name of the first (its `id name`, or - /// what the settings call it). - Other(String), + /// The user's engines do not do: the first of them. + Unfit(Unfit), /// No engine at all. None, } @@ -31,8 +54,8 @@ pub fn engine() -> Option { } /// The engines of the user's to consider, in this order: the active one, the others of -/// the settings, `stockfish` from `PATH`. Called at the start and when the settings -/// are saved. +/// the settings, `stockfish` from `PATH`. Called at the start, when the settings are +/// saved and when an analysis asks for an engine (not every frame). #[cfg_attr(web, allow(unused_variables))] pub fn set_candidates(settings: &crate::settings::Settings) { #[cfg(not(web))] @@ -52,43 +75,82 @@ pub fn lookup(ctx: &egui::Context) -> Lookup { } } +/// Whether the engine at `path`, which said it is `name` at the start of a job, is the +/// one probed: ours always is; a user's one must still call itself Stockfish 19 (a +/// wrapper script may start another program than it did). One that does not is +/// forgotten, to be probed again. +#[cfg(not(web))] +pub fn name_fits(path: &std::path::Path, name: &str) -> bool { + native::name_fits(path, name) +} + +/// The program quits: the probes under way stop, their engines quit (or are killed). +pub fn shutdown() { + #[cfg(not(web))] + native::shutdown(); +} + #[cfg(not(web))] mod native { use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; + use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Mutex, OnceLock}; + use std::thread::JoinHandle; + use game_review::probe::{ProbeLimits, STOCKFISH_19, reference_key}; use serde::{Deserialize, Serialize}; - use super::Lookup; + use super::{Lookup, Unfit, Why}; use crate::engines::EngineLocation; /// A probe's verdict on a file as it was. - #[derive(Clone, Debug, Serialize, Deserialize)] + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub(super) struct Verdict { pub size: u64, pub modified: u64, pub same: bool, pub name: Option, - /// The engine did not start or answer: tried again at the next start (never - /// kept on the disk). - #[serde(skip)] - pub failed: bool, } - /// An engine of the user's: its file and what the settings call it. + /// What is kept on the disk: the verdicts and the reference they were made with. + #[derive(Serialize, Deserialize)] + pub(super) struct Kept { + pub reference: String, + pub engines: HashMap, + } + + /// An engine of the user's: its file as given, the real file (links followed), + /// what the settings call it, and whether it is from them. #[derive(Clone, Debug, PartialEq)] pub(super) struct Candidate { pub path: PathBuf, + pub real: PathBuf, pub label: String, + pub from_settings: bool, + } + + impl Candidate { + pub(super) fn new(path: PathBuf, label: String, from_settings: bool) -> Candidate { + Candidate { + real: path.canonicalize().unwrap_or_else(|_| path.clone()), + path, + label, + from_settings, + } + } } #[derive(Default)] pub(super) struct State { pub candidates: Vec, + /// By the real file. pub known: HashMap, + /// Files that did not start, until it is said (by the real file). + pub failed: HashSet, pub checking: HashSet, - /// Where the verdicts are kept (`None`: not read yet, or nowhere). + pub threads: Vec>, + /// Where the verdicts are kept (`None`: nowhere). pub file: Option, pub loaded: bool, } @@ -98,23 +160,41 @@ mod native { STATE.get_or_init(Default::default) } + /// Set when the program quits: the probes give up. + static QUITTING: AtomicBool = AtomicBool::new(false); + fn with(f: impl FnOnce(&mut State) -> T) -> T { let mut s = state().lock().unwrap_or_else(|e| e.into_inner()); if !s.loaded { s.loaded = true; s.file = crate::settings::Settings::cache_dir().map(|d| d.join("review-engines.json")); - if let Some(known) = s - .file - .as_ref() - .and_then(|f| std::fs::read(f).ok()) - .and_then(|b| serde_json::from_slice(&b).ok()) - { - s.known = known; + if let Some(bytes) = s.file.as_ref().and_then(|f| std::fs::read(f).ok()) { + s.known = read_kept(&bytes); } } f(&mut s) } + /// The verdicts kept, if they were made with the probe of this program. + pub(super) fn read_kept(bytes: &[u8]) -> HashMap { + serde_json::from_slice::(bytes) + .ok() + .filter(|k| k.reference == reference_key()) + .map(|k| k.engines) + .unwrap_or_default() + } + + fn save(s: &State) { + let Some(f) = &s.file else { return }; + let kept = Kept { + reference: reference_key(), + engines: s.known.clone(), + }; + if let Ok(json) = serde_json::to_vec(&kept) { + let _ = crate::platform::fs::write_atomic(f, &json); + } + } + pub(super) fn candidates(settings: &crate::settings::Settings) -> Vec { let active = settings.active_engine.and_then(|i| settings.engines.get(i)); let others = settings.engines.iter().filter(|e| Some(*e) != active); @@ -122,27 +202,41 @@ mod native { .into_iter() .chain(others) .filter(|e| !e.builtin) - .map(|e| Candidate { - path: e.path.clone(), - label: e.name.clone(), - }) + .map(|e| Candidate::new(e.path.clone(), e.name.clone(), true)) .collect(); if let Some(p) = crate::engines::system_stockfish() { - out.push(Candidate { - label: p - .file_name() - .map_or_else(|| p.display().to_string(), |n| n.to_string_lossy().into()), - path: p, - }); + let label = p.display().to_string(); + out.push(Candidate::new(p, label, false)); } // The same file twice (the system's Stockfish added in the settings): once. let mut seen = HashSet::new(); - out.retain(|c| seen.insert(c.path.canonicalize().unwrap_or_else(|_| c.path.clone()))); + out.retain(|c| seen.insert(c.real.clone())); + // The engines of the games against the computer (Rodent, Maia) are never + // analysis engines, whatever the settings say: never probed. + let play = play_dirs(); + out.retain(|c| !play.iter().any(|d| c.real.starts_with(d))); out } + /// The folders of the engines ChessPenguin plays with (links followed). + pub(super) fn play_dirs() -> Vec { + [ + crate::rodent_download::dir(), + crate::rodent4_download::dir(), + crate::maia_download::dir(), + ] + .into_iter() + .flatten() + .map(|d| d.canonicalize().unwrap_or(d)) + .collect() + } + pub(super) fn set_candidates(candidates: Vec) { - with(|s| s.candidates = candidates); + with(|s| { + if s.candidates != candidates { + s.candidates = candidates; + } + }); } /// The file's size and time (seconds), when it is there. @@ -159,11 +253,11 @@ mod native { Some((m.len(), modified)) } - /// The verdict on the file as it is now, if there is one. - fn fresh<'a>(s: &'a State, path: &Path) -> Option<&'a Verdict> { - let (size, modified) = stamp(path)?; + /// The verdict on the real file as it is now, if there is one. + fn fresh<'a>(s: &'a State, real: &Path) -> Option<&'a Verdict> { + let (size, modified) = stamp(real)?; s.known - .get(path) + .get(real) .filter(|v| (v.size, v.modified) == (size, modified)) } @@ -171,7 +265,7 @@ mod native { with(|s| { s.candidates .iter() - .find(|c| fresh(s, &c.path).is_some_and(|v| v.same)) + .find(|c| fresh(s, &c.real).is_some_and(|v| v.same)) .map(|c| EngineLocation::Program(c.path.clone())) }) } @@ -185,8 +279,7 @@ mod native { /// [`lookup`] among the user's engines only. pub(super) fn lookup_without_own(ctx: &egui::Context) -> Lookup { - let to_probe = with(decide); - match to_probe { + match with(decide) { Decision::Done(l) => l, Decision::Probe(paths) => { for p in paths { @@ -199,28 +292,45 @@ mod native { pub(super) enum Decision { Done(Lookup), - /// These files are to be probed (and are marked as being probed). + /// These real files are to be probed (and are marked as being probed). Probe(Vec), } /// What the verdicts say of the candidates; files without one are to be probed. + /// The files that did not start are said once (then tried again). pub(super) fn decide(s: &mut State) -> Decision { - let mut other = None; + let mut unfit = None; let mut checking = false; let mut to_probe = Vec::new(); for c in &s.candidates { - if stamp(&c.path).is_none() { + if stamp(&c.real).is_none() { continue; } - match fresh(s, &c.path) { - Some(v) if v.same => { - return Decision::Done(Lookup::Ready(EngineLocation::Program(c.path.clone()))); + let said = |name: Option<&String>, why| Unfit { + name: name.cloned().unwrap_or_else(|| c.label.clone()), + from_settings: c.from_settings, + why, + }; + if s.checking.contains(&c.real) { + checking = true; + } else if s.failed.contains(&c.real) { + unfit.get_or_insert_with(|| said(None, Why::NotStarted)); + } else { + match fresh(s, &c.real) { + Some(v) if v.same => { + let ready = EngineLocation::Program(c.path.clone()); + return Decision::Done(Lookup::Ready(ready)); + } + Some(v) => { + let why = if v.name.as_deref() == Some(STOCKFISH_19) { + Why::Differs + } else { + Why::Other + }; + unfit.get_or_insert_with(|| said(v.name.as_ref(), why)); + } + None => to_probe.push(c.real.clone()), } - Some(v) => { - other.get_or_insert_with(|| v.name.clone().unwrap_or_else(|| c.label.clone())); - } - None if s.checking.contains(&c.path) => checking = true, - None => to_probe.push(c.path.clone()), } } if !to_probe.is_empty() { @@ -230,72 +340,100 @@ mod native { if checking { return Decision::Done(Lookup::Checking); } - Decision::Done(other.map_or(Lookup::None, Lookup::Other)) + s.failed.clear(); + Decision::Done(unfit.map_or(Lookup::None, Lookup::Unfit)) } - /// Probes the file on a thread of its own and keeps the verdict. - fn spawn_probe(path: PathBuf, ctx: egui::Context) { + /// Probes the real file on a thread of its own and keeps the verdict. + fn spawn_probe(real: PathBuf, ctx: egui::Context) { let spawned = std::thread::Builder::new() .name("review-engine-probe".into()) .spawn({ - let path = path.clone(); + let real = real.clone(); move || { - let stamp = stamp(&path); + let stamp = stamp(&real); let config = uci::EngineConfig { nice: 10, - ..uci::EngineConfig::new(&path) + ..uci::EngineConfig::new(&real) }; - let probe = game_review::probe::probe(config); - record(&path, stamp, probe); - ctx.request_repaint(); + let quitting = || QUITTING.load(Ordering::Relaxed); + let probe = + game_review::probe::probe(config, ProbeLimits::default(), &quitting); + if !quitting() { + record(&real, stamp, probe); + ctx.request_repaint(); + } } }); - if spawned.is_err() { - record( - &path, - stamp(&path), - Err(game_review::JobFailure::Start("no thread".into())), - ); + match spawned { + Ok(t) => with(|s| { + s.threads.retain(|t| !t.is_finished()); + s.threads.push(t); + }), + Err(e) => record( + &real, + stamp(&real), + Err(game_review::JobFailure::Start(e.to_string())), + ), } } pub(super) fn record( - path: &Path, + real: &Path, stamp: Option<(u64, u64)>, probe: Result, ) { with(|s| { - s.checking.remove(path); + s.checking.remove(real); let Some((size, modified)) = stamp else { return; }; - let verdict = match probe { - Ok(p) => Verdict { - size, - modified, - same: p.same(), - name: p.name, - failed: false, - }, - Err(_) => Verdict { - size, - modified, - same: false, - name: None, - failed: true, - }, - }; - s.known.insert(path.to_path_buf(), verdict); - if let Some(f) = &s.file { - let kept: HashMap<&PathBuf, &Verdict> = - s.known.iter().filter(|(_, v)| !v.failed).collect(); - if let Ok(json) = serde_json::to_vec(&kept) { - let _ = crate::platform::fs::write_atomic(f, &json); + match probe { + Ok(p) => { + s.known.insert( + real.to_path_buf(), + Verdict { + size, + modified, + same: p.same(), + name: p.name, + }, + ); + save(s); + } + // Not remembered: tried again at the next request. + Err(_) => { + s.failed.insert(real.to_path_buf()); } } }); } + pub(super) fn name_fits(path: &Path, name: &str) -> bool { + let own = crate::engines::own_stockfish() + .is_some_and(|EngineLocation::Program(p)| p.as_path() == path); + if own || name == STOCKFISH_19 { + return true; + } + let real = path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); + with(|s| { + if s.known.remove(&real).is_some() { + save(s); + } + }); + false + } + + pub(super) fn shutdown() { + QUITTING.store(true, Ordering::Relaxed); + let threads = with(|s| std::mem::take(&mut s.threads)); + // Each gives up within a tenth of a second, and its engine quits or is killed + // within the `uci` crate's stop and quit timeouts. + for t in threads { + let _ = t.join(); + } + } + #[cfg(test)] pub(super) fn reset(candidates: Vec) { let mut s = state().lock().unwrap_or_else(|e| e.into_inner()); @@ -309,9 +447,9 @@ mod native { #[cfg(all(test, not(web)))] mod tests { - use super::native::*; - use super::*; - use std::path::PathBuf; + use super::native::{Candidate, Kept, Verdict, lookup_without_own, read_kept, reset, verified}; + use super::{EngineLocation, Lookup, Unfit, Why, name_fits}; + use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; fn fake() -> PathBuf { @@ -326,8 +464,9 @@ mod tests { fake } - /// A script starting the fake engine that answers the probe as `answers` say. - fn engine(dir: &std::path::Path, file: &str, name: &str, nodes_delta: u64) -> PathBuf { + /// A script starting the fake engine named `name` that answers the probe with the + /// reference, `nodes_delta` nodes more. + fn engine(dir: &Path, file: &str, name: &str, nodes_delta: u64) -> PathBuf { use game_review::probe::{PROBE_POSITIONS, REFERENCE}; let mut args = vec![format!("--name '{name}'")]; for (fen, (best, score, nodes)) in PROBE_POSITIONS.iter().zip(REFERENCE) { @@ -358,7 +497,7 @@ mod tests { fn settle(ctx: &egui::Context) -> Lookup { let deadline = Instant::now() + Duration::from_secs(10); loop { - let l = native::lookup_without_own(ctx); + let l = lookup_without_own(ctx); if l != Lookup::Checking || Instant::now() > deadline { return l; } @@ -366,6 +505,14 @@ mod tests { } } + fn unfit(name: &str, from_settings: bool, why: Why) -> Lookup { + Lookup::Unfit(Unfit { + name: name.into(), + from_settings, + why, + }) + } + /// One test: the state is global. #[test] fn a_users_stockfish_19_is_taken_only_when_it_searches_as_ours() { @@ -373,60 +520,129 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let ctx = egui::Context::default(); - let other = engine(&dir, "sf-other", "Stockfish 19", 1); + let differs = engine(&dir, "sf-other", "Stockfish 19", 1); let same = engine(&dir, "sf-same", "Stockfish 19", 0); let named = engine(&dir, "sf-18", "Stockfish 18", 0); - let candidate = |p: &PathBuf, label: &str| Candidate { - path: p.clone(), - label: label.into(), - }; + let settings = |p: &PathBuf, label: &str| Candidate::new(p.clone(), label.into(), true); // No engine of the user's. reset(Vec::new()); assert_eq!(settle(&ctx), Lookup::None); - // Another search (one node more): not taken; its name is told. - reset(vec![candidate(&other, "My engine")]); - assert_eq!(native::lookup_without_own(&ctx), Lookup::Checking); - assert_eq!(settle(&ctx), Lookup::Other("Stockfish 19".into())); - assert_eq!(native::verified(), None); + // A Stockfish 19 searching otherwise (one node more): not taken. + reset(vec![settings(&differs, "My engine")]); + assert_eq!(lookup_without_own(&ctx), Lookup::Checking); + assert_eq!(settle(&ctx), unfit("Stockfish 19", true, Why::Differs)); + assert_eq!(verified(), None); - // The same answers under another name: not taken either. - reset(vec![candidate(&named, "SF")]); - assert_eq!(settle(&ctx), Lookup::Other("Stockfish 18".into())); + // Another name: turned down (without a search); from `PATH` it says so. + reset(vec![Candidate::new( + named.clone(), + "/usr/bin/x".into(), + false, + )]); + assert_eq!(settle(&ctx), unfit("Stockfish 18", false, Why::Other)); - // An engine that does not start: its name from the settings. - let missing = dir.join("broken"); - std::fs::write(&missing, "not a program").unwrap(); - reset(vec![candidate(&missing, "Broken one")]); - assert_eq!(settle(&ctx), Lookup::Other("Broken one".into())); + // An engine that does not start: its name from the settings; not remembered, + // so the next request tries it again. + let broken = dir.join("broken"); + std::fs::write(&broken, "not a program").unwrap(); + reset(vec![settings(&broken, "Broken one")]); + assert_eq!(settle(&ctx), unfit("Broken one", true, Why::NotStarted)); + assert_eq!(lookup_without_own(&ctx), Lookup::Checking); + assert_eq!(settle(&ctx), unfit("Broken one", true, Why::NotStarted)); // The reference answers: taken, even after another engine in the list. - reset(vec![candidate(&other, "A"), candidate(&same, "B")]); - assert_eq!( - settle(&ctx), - Lookup::Ready(EngineLocation::Program(same.clone())) - ); - assert_eq!( - native::verified(), - Some(EngineLocation::Program(same.clone())) - ); + reset(vec![settings(&differs, "A"), settings(&same, "B")]); + let ready = Lookup::Ready(EngineLocation::Program(same.clone())); + assert_eq!(settle(&ctx), ready); + assert_eq!(verified(), Some(EngineLocation::Program(same.clone()))); // Remembered: no second probe. - assert_eq!( - native::lookup_without_own(&ctx), - Lookup::Ready(EngineLocation::Program(same.clone())) - ); + assert_eq!(lookup_without_own(&ctx), ready); + + // A link to it: the real file's verdict, nothing probed again. + #[cfg(unix)] + { + let link = dir.join("link-to-same"); + std::os::unix::fs::symlink(&same, &link).unwrap(); + super::native::set_candidates(vec![settings(&link, "Link")]); + assert_eq!( + lookup_without_own(&ctx), + Lookup::Ready(EngineLocation::Program(link.clone())) + ); + super::native::set_candidates(vec![settings(&same, "B")]); + } + + // At a job's start it says another name (a wrapper changed): forgotten. + assert!(name_fits(&same, "Stockfish 19")); + assert!(!name_fits(&same, "Stockfish 18")); + assert_eq!(verified(), None); + assert_eq!(settle(&ctx), ready); // The file changed: probed again (a changed size). let text = std::fs::read_to_string(&same).unwrap(); std::fs::write(&same, format!("{text}\n")).unwrap(); - assert_eq!(native::verified(), None); - assert_eq!(native::lookup_without_own(&ctx), Lookup::Checking); - assert_eq!( - settle(&ctx), - Lookup::Ready(EngineLocation::Program(same.clone())) - ); + assert_eq!(verified(), None); + assert_eq!(lookup_without_own(&ctx), Lookup::Checking); + assert_eq!(settle(&ctx), ready); let _ = std::fs::remove_dir_all(&dir); } + + /// The engines of the games against the computer are never candidates, whatever + /// the settings say; the analysis engines are, the active one first. + #[test] + fn play_engines_are_never_probed() { + use crate::settings::{EngineConfig, Settings}; + let rodent = crate::rodent_download::dir() + .expect("a data folder") + .join("rodent_v"); + let rodent4 = crate::rodent4_download::dir() + .expect("a data folder") + .join("rodent4"); + let mine = PathBuf::from("/opt/engines/stockfish-19"); + let other = PathBuf::from("/opt/engines/komodo"); + let settings = Settings { + engines: vec![ + EngineConfig::new("Rodent".into(), rodent), + EngineConfig::new("Komodo".into(), other.clone()), + EngineConfig::new("Rodent IV".into(), rodent4), + EngineConfig::new("Mine".into(), mine.clone()), + ], + active_engine: Some(3), + ..Settings::default() + }; + let found: Vec<(PathBuf, bool)> = super::native::candidates(&settings) + .into_iter() + .map(|c| (c.path, c.from_settings)) + .filter(|(_, from_settings)| *from_settings) + .collect(); + assert_eq!(found, vec![(mine, true), (other, true)]); + } + + /// Verdicts kept with another reference (another probe) are not trusted. + #[test] + fn verdicts_of_another_reference_are_dropped() { + let verdict = Verdict { + size: 1, + modified: 2, + same: true, + name: Some("Stockfish 19".into()), + }; + let kept = |reference: String| { + serde_json::to_vec(&Kept { + reference, + engines: [(PathBuf::from("/x/stockfish"), verdict.clone())].into(), + }) + .unwrap() + }; + let ours = read_kept(&kept(game_review::probe::reference_key())); + assert_eq!(ours.get(Path::new("/x/stockfish")), Some(&verdict)); + assert!(read_kept(&kept("0000000000000000".into())).is_empty()); + // The first version's file (a bare map): dropped too. + assert!( + read_kept(br#"{"/x/stockfish":{"size":1,"modified":2,"same":true,"name":null}}"#) + .is_empty() + ); + } } diff --git a/apps/desktop/src/widgets.rs b/apps/desktop/src/widgets.rs index 551a050..5dc2fa8 100644 --- a/apps/desktop/src/widgets.rs +++ b/apps/desktop/src/widgets.rs @@ -138,3 +138,28 @@ pub fn icon_button(ui: &mut Ui, check: bool, primary: bool) -> egui::Response { } resp } + +/// `text` cut to `max` characters, with «…» in the middle when longer (a file's or an +/// engine's name keeps its start and its end, where versions and extensions are). +pub fn shorten(text: &str, max: usize) -> String { + let n = text.chars().count(); + if n <= max || max < 3 { + return text.to_owned(); + } + let head = (max - 1) / 2; + let tail = max - 1 - head; + let start: String = text.chars().take(head).collect(); + let end: String = text.chars().skip(n - tail).collect(); + format!("{start}…{end}") +} + +#[cfg(test)] +mod shorten_tests { + #[test] + fn long_names_are_cut_in_the_middle() { + assert_eq!(super::shorten("Stockfish 19", 48), "Stockfish 19"); + assert_eq!(super::shorten("abcdefghij", 5), "ab…ij"); + assert_eq!(super::shorten("абвгдежзик", 7), "абв…зик"); + assert_eq!(super::shorten("abcdefghij", 7).chars().count(), 7); + } +} diff --git a/crates/game-review/src/job/engines.rs b/crates/game-review/src/job/engines.rs index 3198886..8e5b5ea 100644 --- a/crates/game-review/src/job/engines.rs +++ b/crates/game-review/src/job/engines.rs @@ -105,7 +105,15 @@ fn worker( let mut search = |pos: &EnginePosition, among: Vec, nodes: u64| { next_id += 1; let _ = handle.new_game(); - search_once(&handle, pos, SearchId(next_id), among, nodes, halted) + search_once( + &handle, + pos, + SearchId(next_id), + among, + nodes, + SEARCH_GUARD, + halted, + ) }; 'targets: while let Some(t) = targets.get(next.fetch_add(1, Ordering::Relaxed)) { if halted() { @@ -135,13 +143,15 @@ fn worker( } /// One node-limited search: its last full line and the best move. `None` when it gave -/// no line or the job was halted. +/// no line or the job was halted. After `guard` the search is stopped (an engine that +/// ignores `stop` is killed by the `uci` crate's stop timeout: `Terminated`). pub(super) fn search_once( handle: &uci::EngineHandle, pos: &EnginePosition, id: SearchId, among: Vec, nodes: u64, + guard: Duration, halted: &dyn Fn() -> bool, ) -> Result { handle @@ -154,7 +164,7 @@ pub(super) fn search_once( if halted() { return Ok(None); } - if !stopping && started.elapsed() > SEARCH_GUARD { + if !stopping && started.elapsed() > guard { let _ = handle.stop(); stopping = true; } diff --git a/crates/game-review/src/job/probe.rs b/crates/game-review/src/job/probe.rs index e9e80ee..b0956f2 100644 --- a/crates/game-review/src/job/probe.rs +++ b/crates/game-review/src/job/probe.rs @@ -11,7 +11,7 @@ //! set: its own check of the universal build (`scripts/check_universal.sh` of the //! release) requires the same `bench` node count from every per-CPU build. -use std::sync::atomic::AtomicBool; +use std::time::{Duration, Instant}; use uci::{EnginePosition, Score}; @@ -55,8 +55,11 @@ pub const REFERENCE: [(&str, Score, u64); 3] = [ pub struct Probe { /// The engine's name (`id name`). pub name: Option, - /// The answers, one per position of [`PROBE_POSITIONS`] (fewer when one gave none). + /// The answers, one per position of [`PROBE_POSITIONS`] (fewer when one gave none, + /// took too long, or the engine is not called Stockfish 19: then none is searched). pub answers: Vec, + /// A search took longer than allowed (an engine that ignores `go nodes`). + pub timed_out: bool, } impl Probe { @@ -74,23 +77,75 @@ impl Probe { } } -/// Runs the probe searches in a process of the engine. Takes about a second (the -/// engine's start included); the engine is quit at the end. -pub fn probe(config: uci::EngineConfig) -> Result { +/// How long the probe may take: a search (Stockfish needs about 0.1 s) and all of it. +#[derive(Clone, Copy, Debug)] +pub struct ProbeLimits { + pub search: Duration, + pub total: Duration, +} + +impl Default for ProbeLimits { + fn default() -> Self { + ProbeLimits { + search: Duration::from_secs(10), + total: Duration::from_secs(30), + } + } +} + +/// What [`REFERENCE`] is a reference of — the positions, the nodes, the hash, the +/// answers — as a short text kept with the verdicts: a verdict of another probe is +/// not trusted. (FNV-1a of their text: the same in every build.) +pub fn reference_key() -> String { + let text = format!("{PROBE_POSITIONS:?}|{PROBE_NODES}|{SEARCH_HASH_MB}|{REFERENCE:?}"); + let hash = text.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| { + (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3) + }); + format!("{hash:016x}") +} + +/// Runs the probe in a process of the engine; `halted` gives it up (the program +/// quits). An engine not called Stockfish 19 is not searched at all. The engine is +/// quit at the end (killed if it does not go). +pub fn probe( + config: uci::EngineConfig, + limits: ProbeLimits, + halted: &dyn Fn() -> bool, +) -> Result { + let started = Instant::now(); let handle = uci::Engine::spawn_with(config, Box::new(|| {})) .map_err(|e| JobFailure::Start(e.to_string()))?; - let name = handle.info().name.clone(); + let mut probe = Probe { + name: handle.info().name.clone(), + answers: Vec::new(), + timed_out: false, + }; + if probe.name.as_deref() != Some(STOCKFISH_19) { + handle.quit(); + return Ok(probe); + } let _ = handle.set_threads(1); let _ = handle.set_hash_mb(SEARCH_HASH_MB); let _ = handle.set_multipv(1); - let never = AtomicBool::new(false); - let halted = || never.load(std::sync::atomic::Ordering::Relaxed); - let mut answers = Vec::new(); + let over = || halted() || started.elapsed() > limits.total; for (i, fen) in PROBE_POSITIONS.iter().enumerate() { let _ = handle.new_game(); let pos = EnginePosition::fen(*fen, Vec::::new()); let id = uci::SearchId(i as u64 + 1); - let answer = search_once(&handle, &pos, id, Vec::new(), PROBE_NODES, &halted)?; + let search_started = Instant::now(); + let answer = search_once( + &handle, + &pos, + id, + Vec::new(), + PROBE_NODES, + limits.search, + &over, + )?; + if search_started.elapsed() > limits.search || started.elapsed() > limits.total { + probe.timed_out = true; + break; + } let Some((info, best)) = answer else { break }; let (Some(best), Some(score), Some(nodes)) = ( best.or_else(|| info.pv.first().cloned()), @@ -99,20 +154,24 @@ pub fn probe(config: uci::EngineConfig) -> Result { ) else { break; }; - answers.push(ProbeAnswer { + probe.answers.push(ProbeAnswer { best, score: score.score, nodes, }); } handle.quit(); - Ok(Probe { name, answers }) + Ok(probe) } #[cfg(test)] mod tests { use super::*; + fn run(config: uci::EngineConfig) -> Result { + probe(config, ProbeLimits::default(), &|| false) + } + fn fake() -> &'static str { let fake = concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/debug/fake_uci"); assert!( @@ -143,7 +202,7 @@ mod tests { #[test] fn the_reference_answers_pass() { - let p = probe(engine(STOCKFISH_19, &REFERENCE)).expect("the probe runs"); + let p = run(engine(STOCKFISH_19, &REFERENCE)).expect("the probe runs"); assert_eq!(p.name.as_deref(), Some(STOCKFISH_19)); assert_eq!(p.answers.len(), 3); assert!(p.same(), "{p:?}"); @@ -154,24 +213,24 @@ mod tests { // Another network or version: one score differs. let mut other = REFERENCE; other[1].1 = Score::Cp(-117); - let p = probe(engine(STOCKFISH_19, &other)).expect("the probe runs"); + let p = run(engine(STOCKFISH_19, &other)).expect("the probe runs"); assert!(!p.same()); // The nodes differ (another search), the move and score the same. let mut other = REFERENCE; other[2].2 += 1; - assert!(!probe(engine(STOCKFISH_19, &other)).unwrap().same()); + assert!(!run(engine(STOCKFISH_19, &other)).unwrap().same()); // Another best move. let mut other = REFERENCE; other[0].0 = "g8f6"; - assert!(!probe(engine(STOCKFISH_19, &other)).unwrap().same()); + assert!(!run(engine(STOCKFISH_19, &other)).unwrap().same()); // The same answers under another name. - let p = probe(engine("Stockfish 18", &REFERENCE)).unwrap(); + let p = run(engine("Stockfish 18", &REFERENCE)).unwrap(); assert_eq!(p.name.as_deref(), Some("Stockfish 18")); assert!(!p.same()); // An engine that answers nothing of the kind (the fake's own lines). let mut plain = uci::EngineConfig::new(fake()); plain.args = vec!["--name".into(), STOCKFISH_19.into()]; - assert!(!probe(plain).unwrap().same()); + assert!(!run(plain).unwrap().same()); } /// A real Stockfish 19 gives [`REFERENCE`] (run when the reference is taken again @@ -181,15 +240,72 @@ mod tests { #[ignore = "needs a Stockfish 19 in CP_PROBE_ENGINE"] fn a_real_stockfish_19_gives_the_reference() { let path = std::env::var("CP_PROBE_ENGINE").expect("CP_PROBE_ENGINE"); - let p = probe(uci::EngineConfig::new(path)).expect("the probe runs"); + let p = run(uci::EngineConfig::new(path)).expect("the probe runs"); println!("{p:?}"); assert!(p.same(), "{p:?}"); } + /// An engine not called Stockfish 19 is not searched (Rodent searches on past + /// `go nodes`): its name is the verdict, at once. + #[test] + fn another_engine_is_not_searched() { + let mut config = uci::EngineConfig::new(fake()); + config.args = vec![ + "--name".into(), + "Rodent V 1.2".into(), + "--ignore-nodes".into(), + ]; + let started = Instant::now(); + let p = run(config).expect("the probe runs"); + assert_eq!(p.name.as_deref(), Some("Rodent V 1.2")); + assert!(p.answers.is_empty() && !p.timed_out && !p.same()); + assert!(started.elapsed() < Duration::from_secs(5)); + } + + /// A «Stockfish 19» that ignores `go nodes`: stopped by the guard, not the same. + #[test] + fn an_endless_search_is_cut_short() { + let mut config = uci::EngineConfig::new(fake()); + config.args = vec![ + "--name".into(), + STOCKFISH_19.into(), + "--ignore-nodes".into(), + ]; + let limits = ProbeLimits { + search: Duration::from_millis(300), + total: Duration::from_secs(2), + }; + let started = Instant::now(); + let p = probe(config, limits, &|| false).expect("the probe runs"); + assert!(p.timed_out && !p.same(), "{p:?}"); + assert!( + started.elapsed() < Duration::from_secs(5), + "{:?}", + started.elapsed() + ); + // Halted from outside (the program quits): at once. + let mut config = uci::EngineConfig::new(fake()); + config.args = vec![ + "--name".into(), + STOCKFISH_19.into(), + "--ignore-nodes".into(), + ]; + let started = Instant::now(); + let p = probe(config, ProbeLimits::default(), &|| true).expect("the probe runs"); + assert!(!p.same()); + assert!(started.elapsed() < Duration::from_secs(5)); + } + + #[test] + fn the_reference_key_is_stable() { + assert_eq!(reference_key(), reference_key()); + assert_eq!(reference_key().len(), 16); + } + #[test] fn an_engine_that_does_not_start_fails() { assert!(matches!( - probe(uci::EngineConfig::new("/nonexistent/engine")), + run(uci::EngineConfig::new("/nonexistent/engine")), Err(JobFailure::Start(_)) )); } diff --git a/crates/uci/src/bin/fake_uci.rs b/crates/uci/src/bin/fake_uci.rs index cf3604c..9eed3e5 100644 --- a/crates/uci/src/bin/fake_uci.rs +++ b/crates/uci/src/bin/fake_uci.rs @@ -30,6 +30,7 @@ //! best move, scored 30 cp lower (a worse move) //! --shallow N MOVE `go nodes n` with n < N (no `searchmoves`): MOVE is the //! best move (a shallow search choosing another move) +//! --ignore-nodes `go nodes N` searches until `stop` (as Rodent does) //! --answer MARKER TAIL `go` in the position of MARKER answers at once with //! `info depth 10 multipv 1 score TAIL` and the bestmove of //! the first move after `pv` in TAIL (repeatable) @@ -64,6 +65,7 @@ struct Cfg { searchmoves: bool, shallow: Option<(u64, String)>, answers: Vec<(String, String)>, + ignore_nodes: bool, } fn parse_args() -> Cfg { @@ -98,6 +100,7 @@ fn parse_args() -> Cfg { let n = num(args.next()); c.shallow = args.next().map(|m| (n, m)); } + "--ignore-nodes" => c.ignore_nodes = true, "--answer" => { if let (Some(m), Some(t)) = (args.next(), args.next()) { c.answers.push((m, t)); @@ -309,7 +312,7 @@ fn main() { .and_then(|p| toks.get(p + 1)) .and_then(|v| v.parse().ok()) // `go nodes N`: a short search that ends by itself, like a real one. - .or_else(|| toks.contains(&"nodes").then_some(3)); + .or_else(|| (toks.contains(&"nodes") && !cfg.ignore_nodes).then_some(3)); since_new_game += 1; let mut bias = if cfg.hash_memory { let of_position = marker.bytes().map(i32::from).sum::() % 97; diff --git a/docs/decisions.md b/docs/decisions.md index 6b58941..a1424e9 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -227,7 +227,10 @@ Владелец одобрил по жалобе пользователя (свой stockfish в настройках, анализ позиции работает, а разбор просил скачать). -- **Движок разбора на компьютере** (`apps/desktop/src/review_engine.rs`): свой Stockfish 19 программы → движок пользователя (активный, остальные из настроек, `stockfish` из `PATH`), прошедший проверку → предложение скачать. Android и веб не меняются. -- **Проверка** (`game_review::probe`): `id name` ровно «Stockfish 19» **и** три поиска в режиме разбора (`Threads=1`, `Hash=32`, `MultiPV=1`, `ucinewgame` перед каждым, `go nodes 100000`, строка выбирается как в разборе) дают те же лучший ход, оценку и число узлов, что эталон `REFERENCE` (снят 2026-10-31 нашим `stockfish-linux-x86-64-universal`). Тот же ответ дали сборки SF19 из исходников релиза под x86-64 (SSE2) и x86-64-bmi2; Stockfish и сам требует одинакового `bench` от всех срезов универсальной сборки (`scripts/check_universal.sh` релиза). Проверка — в фоне (`nice 10`), разбор ждёт её (тост «Проверяю Stockfish из настроек…»); итог запоминается по пути + размеру + времени файла (`/review-engines.json`; неудачный запуск — только до перезапуска). Оценки те же, поэтому `SEARCH_VERSION` и кэш разборов не меняются. -- Движок не прошёл проверку — окно называет его: «В настройках указан . Для разбора партии нужен именно Stockfish 19 — так отметки одинаковы на любом компьютере. Скачать Stockfish 19 (N МБ)?» (для ошибок в дебютах — свой текст). Без движка — как прежде. -- **Перетаскивание на компьютере** (`platform::files::take_dropped`): брошенные файлы открываются как «Добавить базу» (на полку, выбирается первая; партия на экране не закрывается). `.pgn/.cbh/.cbv/.zip/.7z` — базы; любой другой файл ChessBase-базы (`.cbg`, `.cba`, …) — её `.cbh` рядом, база один раз; папка — базы в ней (без вложенных), пустая — тост «В этой папке нет баз»; прочее — тост «Это не база: … ChessPenguin открывает файлы .pgn, .cbh, .cbv, .zip и .7z». Пока файл над окном — подсветка «Отпустите, чтобы открыть», как в вебе. +- **Движок разбора на компьютере** (`apps/desktop/src/review_engine.rs`): свой Stockfish 19 программы → движок пользователя, прошедший проверку → предложение скачать. Кандидаты — движки анализа из настроек (активный первым) и `stockfish` из `PATH`; движки игры (Rodent IV/V, Maia — их папки) не проверяются никогда, при любых настройках. Android и веб не меняются. +- **Проверка** (`game_review::probe`): движок, назвавшийся (`id name`) не «Stockfish 19», отвергается сразу после `uci`, без поисков (Rodent, Komodo — доли секунды). «Stockfish 19» делает три поиска в режиме разбора (`Threads=1`, `Hash=32`, `MultiPV=1`, `ucinewgame` перед каждым, `go nodes 100000`, строка — как в разборе); лучший ход, оценка и число узлов должны совпасть с эталоном `REFERENCE` (снят 2026-10-31 нашим `stockfish-linux-x86-64-universal`; тот же ответ дали сборки SF19 из исходников релиза под x86-64 (SSE2) и x86-64-bmi2; Stockfish и сам требует одинакового `bench` от всех срезов универсальной сборки, `scripts/check_universal.sh` релиза). Сторож: 10 с на поиск, 30 с на всю проверку — дольше значит «не тот». Проверка — в фоне (`nice 10`); при выходе из программы прерывается, процесс движка завершается (или убивается). +- **Кэш**: вердикт по реальному файлу (ссылки разрешены) + размер + время, вместе с ключом эталона (`reference_key`, FNV позиций/узлов/хэша/ответов) в `/review-engines.json`; другой ключ — всё проверяется заново. «Не запустился» не запоминается: сказано один раз, при следующем запросе — новая попытка. При старте разбора `id name` движка пользователя сверяется ещё раз (обёртка могла начать запускать другое): не «Stockfish 19» — разбор останавливается до первой оценки, вердикт забывается. Оценки те же, поэтому `SEARCH_VERSION` и кэш разборов не меняются. +- **Ожидание проверки** привязано к своей партии/подготовке (номер экрана): закрыта или открыта другая — разбор не начнётся на чужой; разбор партии и ошибки в дебютах ждут отдельно; «Проанализировать движком» (заново) сохраняется. Тост «Проверяю, подойдёт ли ваш движок для разбора…». +- **Окно, если не подошёл** — четыре случая: другой движок («В настройках указан …» / «В системе найден …»), «Ваш Stockfish 19 считает иначе, чем сборка ChessPenguin (другая сборка или сеть)…», «Не удалось запустить …»; затем зачем нужна официальная сборка, «Скачать?», «Ваш движок остаётся для анализа позиции» (кроме незапустившегося) и «…начнётся сам после загрузки»; ниже — «N МБ · с официальной страницы Stockfish». Без движка — как прежде. +- **Перетаскивание на компьютере** (`platform::files::take_dropped`): брошенные файлы открываются как «Добавить базу» (на полку, выбирается первая; партия на экране не закрывается, тогда тост «Добавлено на полку: …»). `.pgn/.cbh/.cbv/.zip/.7z` — базы; другие файлы ChessBase-базы (`.cbg`, `.cba`, `.cbj`, … — известные расширения) — её `.cbh` рядом, база один раз (дубли по реальному файлу); папка — базы в ней (без вложенных), пустая — тост; несуществующий файл — «Не найдено: …»; прочее — «Это не база: …». Брошенные файлы не заменяют базу из «Выбрать снова»; отмена этого диалога его завершает. Пока файл над окном — подсветка окна с рамкой и карточка «Отпустите, чтобы открыть». +- **Где работает перетаскивание**: Windows, macOS, Linux в X11 и XWayland. В сеансе Wayland окно перетаскивание не принимает (система и не показывает «можно отпустить»): в winit 0.30.13, на котором стоит eframe 0.36, перетаскивание есть только в X11 (`platform_impl/linux/x11/event_processor.rs`), в `wayland/` его нет. Принудительный запуск через X11 не делаем (без обходов).