diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index cdd038b..5e67c20 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -39,9 +39,10 @@ enum Async { /// ChessBase databases not all files of which were chosen (their `.cbh` names). #[cfg(web)] Incomplete(Vec), - /// A folder was chosen with no database in it. - #[cfg(web)] + /// A folder was chosen (or dropped) with no database in it. EmptyFolder, + /// Files dropped on the window that are no databases (their names). + NotDatabases(Vec), /// A copy of the visit's database `.0` kept in the browser, or why not. #[cfg(web)] CopyKept(PathBuf, Result), @@ -256,6 +257,8 @@ 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, offer_hook_done: bool, /// What only the desktop program has: online games, updates. #[cfg(not(web))] @@ -505,6 +508,7 @@ impl App { prep_quit_ask: false, prep_quit_ok: false, engine_offer: crate::engine_offer::EngineOffer::new(), + review_wait: None, offer_hook_done: false, #[cfg(not(web))] desktop, @@ -514,6 +518,7 @@ impl App { debug: DebugStartup::from_env(), } .with_debug_settings(); + crate::review_engine::set_candidates(&app.settings); #[cfg(not(web))] if let Some(from) = updated_from { let msg = trf( @@ -975,9 +980,9 @@ impl App { self.live_paused = false; } PrepAction::EngineEnded => {} - PrepAction::NeedEngine => self - .engine_offer - .ask(crate::engine_offer::Pending::OpeningErrors, &self.settings), + PrepAction::NeedEngine => { + self.need_review_engine(ctx, crate::engine_offer::Pending::OpeningErrors) + } PrepAction::SettingsChanged => self.settings_dirty = true, PrepAction::Toast(m) => self.toast(ctx, m), PrepAction::CopyText(text, msg) => { @@ -2475,13 +2480,25 @@ impl App { self.web_notice = Some(WebNotice::Incomplete(name)); } } - #[cfg(web)] Async::EmptyFolder => { self.toast( ctx, tr("There is no database in this folder (.pgn, .cbh, .cbv, .zip, .7z)."), ); } + Async::NotDatabases(names) => { + let mut files = names.iter().take(3).cloned().collect::>().join(", "); + if names.len() > 3 { + files.push_str(", …"); + } + self.toast( + ctx, + trf( + "Not a database: {files}. ChessPenguin opens .pgn, .cbh, .cbv, .zip and .7z files.", + &[("files", &files)], + ), + ); + } #[cfg(web)] Async::CopyKept(path, kept) => self.copy_kept(ctx, path, kept), Async::DatabasesPicked(paths) => { @@ -2771,6 +2788,44 @@ impl App { self.settings.active_engine = Some(index); } self.settings_dirty = true; + self.run_engine_pending(ctx, pending); + } + + /// 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. + 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); + match crate::review_engine::lookup(ctx) { + 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…")); + } + self.review_wait = Some(pending); + } + Lookup::Other(name) => { + self.review_wait = None; + self.engine_offer.ask_instead_of(pending, name); + } + Lookup::None => { + self.review_wait = None; + self.engine_offer.ask(pending, &self.settings); + } + } + } + + /// Runs what the user was doing when an engine had to be found first. + fn run_engine_pending( + &mut self, + ctx: &egui::Context, + pending: Option, + ) { match pending { Some(crate::engine_offer::Pending::LiveAnalysis) => { if !self.analysis.is_on() { @@ -3408,6 +3463,9 @@ impl eframe::App for App { self.engine_offer.start(&ctx); } } + if let Some(p) = self.review_wait { + self.need_review_engine(&ctx, p); + } self.offer_events(&ctx); self.page_frame(&ctx); #[cfg(web)] @@ -3536,9 +3594,9 @@ impl eframe::App for App { self.request_close(&ctx, CloseIntent::ReturnToPrevious); } } - GameAction::NeedEngine => self - .engine_offer - .ask(crate::engine_offer::Pending::GameAnalysis, &self.settings), + GameAction::NeedEngine => { + self.need_review_engine(&ctx, crate::engine_offer::Pending::GameAnalysis) + } GameAction::Sound(s) => self.play(s), GameAction::CopyText(text, msg) => { ctx.copy_text(text); @@ -3958,6 +4016,7 @@ impl eframe::App for App { if let Err(e) = self.settings.save() { eprintln!("settings: save failed: {e}"); } + crate::review_engine::set_candidates(&self.settings); } } @@ -3983,6 +4042,12 @@ fn send_picked(tx: &Sender, picked: crate::platform::files::Picked) { if !picked.paths.is_empty() { let _ = tx.send(Async::DatabasesPicked(picked.paths)); } + if picked.empty_folder { + let _ = tx.send(Async::EmptyFolder); + } + if !picked.unsupported.is_empty() { + let _ = tx.send(Async::NotDatabases(picked.unsupported)); + } #[cfg(web)] { if !picked.too_big.is_empty() { @@ -3991,9 +4056,6 @@ fn send_picked(tx: &Sender, picked: crate::platform::files::Picked) { if !picked.incomplete.is_empty() { let _ = tx.send(Async::Incomplete(picked.incomplete)); } - if picked.empty_folder { - let _ = tx.send(Async::EmptyFolder); - } } } diff --git a/apps/desktop/src/engine_offer.rs b/apps/desktop/src/engine_offer.rs index 5a8ec25..a5fc98e 100644 --- a/apps/desktop/src/engine_offer.rs +++ b/apps/desktop/src/engine_offer.rs @@ -45,6 +45,9 @@ 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), } pub struct EngineOffer { @@ -94,6 +97,15 @@ impl EngineOffer { self.open = true; } + /// 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) { + self.pending = Some(pending); + self.failure = None; + self.mode = Mode::OwnInstead(name); + self.open = true; + } + /// Starts the download (from the offer or from the settings). pub fn start(&mut self, ctx: &egui::Context) { if self.download.as_ref().is_some_and(Download::running) { @@ -210,26 +222,42 @@ impl EngineOffer { fn offer_body(&mut self, ui: &mut Ui, events: &mut Vec) { let size = engine_download::size_mb(); - let (title, text) = match &self.mode { + let (title, text): (&str, String) = match &self.mode { Mode::Offer => ( tr("Analysis needs a chess engine"), tr( "Download Stockfish, the strongest free chess engine? Analysis will start as soon as the download finishes.", - ), + ) + .into(), ), Mode::System(_) => ( tr("Analysis needs a chess engine"), - tr("Stockfish is already installed on this computer."), + tr("Stockfish is already installed on this computer.").into(), ), Mode::Missing => ( tr("Stockfish not found"), - tr("The Stockfish file is missing from the disk. Download it again?"), + tr("The Stockfish file is missing from the disk. Download it again?").into(), ), Mode::Own => ( tr("Analysis needs Stockfish 19"), tr( "Game analysis and the search for opening errors always use ChessPenguin's Stockfish 19, so that their marks are the same on every computer. Download it? The analysis will start as soon as the download finishes.", - ), + ) + .into(), + ), + Mode::OwnInstead(name) => ( + 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)], + ) + }, ), }; ui.heading(title); @@ -257,6 +285,12 @@ 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( @@ -308,7 +342,7 @@ impl EngineOffer { // Another engine does not do for the game analysis (and a browser has // no engine programs). #[cfg(not(web))] - if self.mode != Mode::Own { + if !matches!(self.mode, Mode::Own | Mode::OwnInstead(_)) { ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { if ui.button(tr("Choose engine file…")).clicked() { events.push(OfferEvent::ChooseFile); @@ -395,7 +429,10 @@ impl EngineOffer { ui.label(RichText::new(d).small().weak()); }); } - if matches!(f, Failure::Network(_)) && cfg!(target_os = "linux") && self.mode != Mode::Own { + if matches!(f, Failure::Network(_)) + && cfg!(target_os = "linux") + && !matches!(self.mode, Mode::Own | Mode::OwnInstead(_)) + { ui.label( RichText::new(tr( "A stockfish package of your distribution is found by ChessPenguin too.", @@ -418,7 +455,7 @@ impl EngineOffer { self.pending = None; } #[cfg(not(web))] - if self.mode != Mode::Own { + if !matches!(self.mode, Mode::Own | Mode::OwnInstead(_)) { ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { if ui.button(tr("Choose engine file…")).clicked() { events.push(OfferEvent::ChooseFile); diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index d9e04c3..24b649f 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -854,10 +854,11 @@ impl GameView { actions } - /// Starts the game analysis with ChessPenguin's Stockfish; without it, the offer to - /// download it comes first. + /// Starts the game analysis with Stockfish 19 (ChessPenguin's, or the user's that + /// searches the same, `review_engine`); without it, the app finds one or offers to + /// download ours. fn start_review(&mut self, full: bool, ctx: &egui::Context, actions: &mut Vec) { - let Some(path) = crate::engines::own_stockfish() else { + let Some(path) = crate::review_engine::engine() else { actions.push(GameAction::NeedEngine); return; }; diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index cdc4802..5241812 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -580,6 +580,17 @@ const ROWS: &[[&str; 9]] = &[ "sayt uchun bo‘sh: {free}", "сайт үшін бос: {free}", ], + [ + "Not a database: {files}. ChessPenguin opens .pgn, .cbh, .cbv, .zip and .7z files.", + "Это не база: {files}. ChessPenguin открывает файлы .pgn, .cbh, .cbv, .zip и .7z.", + "Ce n’est pas une base : {files}. ChessPenguin ouvre les fichiers .pgn, .cbh, .cbv, .zip et .7z.", + "Keine Datenbank: {files}. ChessPenguin öffnet .pgn-, .cbh-, .cbv-, .zip- und .7z-Dateien.", + "No es una base: {files}. ChessPenguin abre archivos .pgn, .cbh, .cbv, .zip y .7z.", + "Non è un database: {files}. ChessPenguin apre i file .pgn, .cbh, .cbv, .zip e .7z.", + "Não é uma base: {files}. O ChessPenguin abre arquivos .pgn, .cbh, .cbv, .zip e .7z.", + "Bu baza emas: {files}. ChessPenguin .pgn, .cbh, .cbv, .zip va .7z fayllarini ochadi.", + "Бұл база емес: {files}. ChessPenguin .pgn, .cbh, .cbv, .zip және .7z файлдарын ашады.", + ], [ "Release to open", "Отпустите, чтобы открыть", @@ -15381,6 +15392,39 @@ const ROWS: &[[&str; 9]] = &[ "{judgement}: yaxshisi {best} ({before} → {after}) · {n} partiyada", "{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} МБ)?", + ], + [ + "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} МБ)?", + ], + [ + "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 тексерілуде…", + ], [ "Analysis needs Stockfish 19", "Для анализа нужен Stockfish 19", diff --git a/apps/desktop/src/lib.rs b/apps/desktop/src/lib.rs index 978557f..dc9b3ac 100644 --- a/apps/desktop/src/lib.rs +++ b/apps/desktop/src/lib.rs @@ -44,6 +44,7 @@ mod player_games; mod prep_ui; mod reference; mod review; +mod review_engine; mod rodent4_download; mod rodent_download; mod san; diff --git a/apps/desktop/src/platform/files.rs b/apps/desktop/src/platform/files.rs index 8a429f0..bde6f52 100644 --- a/apps/desktop/src/platform/files.rs +++ b/apps/desktop/src/platform/files.rs @@ -18,14 +18,16 @@ pub const TOO_BIG: u64 = 2_000_000_000; /// What the user chose or dropped: the databases to open, the ones left out because /// they are too big for a browser (name, bytes of their files), the ChessBase -/// databases not all files of which were given (the name of their `.cbh`), and -/// whether a chosen folder held no database. -#[derive(Default)] +/// databases not all files of which were given (the name of their `.cbh`), whether a +/// chosen (or, on a computer, dropped) folder held no database, and the files dropped +/// on a computer's window that are no databases (their names). +#[derive(Debug, Default, PartialEq)] pub struct Picked { pub paths: Vec, pub too_big: Vec<(String, u64)>, pub incomplete: Vec, pub empty_folder: bool, + pub unsupported: Vec, } /// The files the user gave the page, made databases: the ChessBase ones of their @@ -250,11 +252,25 @@ pub fn forget(path: &std::path::Path) { /// The files dropped on the window in this frame, as databases to open: `then` gets /// their paths once read (in a browser they are kept for the session like chosen -/// ones). The desktop program does not take dropped files: nothing comes there. +/// ones; on a computer they are opened where they are, as «Add database» does). pub fn take_dropped(ctx: &egui::Context, then: impl FnOnce(Picked) + Send + 'static) { #[cfg(not(web))] { - let _ = (ctx, then); + let paths: Vec = ctx.input(|i| { + i.raw + .dropped_files + .iter() + .map(|f| f.path().to_path_buf()) + .filter(|p| p.is_absolute()) + .collect() + }); + if paths.is_empty() { + return; + } + // Folders are listed and files' neighbours looked at: off the screen's thread. + let _ = std::thread::Builder::new() + .name("dropped".into()) + .spawn(move || then(sort_dropped(&paths))); } #[cfg(web)] { @@ -274,7 +290,83 @@ pub fn take_dropped(ctx: &egui::Context, then: impl FnOnce(Picked) + Send + 'sta /// Files are dragged over the window now (the page shows where they go). pub fn dragging(ctx: &egui::Context) -> bool { - cfg!(web) && ctx.input(|i| !i.raw.hovered_files.is_empty()) + ctx.input(|i| !i.raw.hovered_files.is_empty()) +} + +/// 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. +#[cfg(not(web))] +fn sort_dropped(paths: &[PathBuf]) -> Picked { + let mut picked = Picked::default(); + let add = |p: PathBuf, picked: &mut Picked| { + if !picked.paths.contains(&p) { + picked.paths.push(p); + } + }; + for p in paths { + if p.is_dir() { + let found = databases_in(p); + 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); + } else { + let name = p + .file_name() + .map_or_else(|| p.display().to_string(), |n| n.to_string_lossy().into()); + picked.unsupported.push(name); + } + } + picked +} + +/// The extension of `p`, in lower case. +#[cfg(not(web))] +fn extension(p: &std::path::Path) -> String { + p.extension() + .map(|e| e.to_string_lossy().to_lowercase()) + .unwrap_or_default() +} + +/// The database the file `p` is, or is a part of. +#[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(); + let want = format!("{stem}.cbh"); + std::fs::read_dir(p.parent()?) + .ok()? + .flatten() + .map(|e| e.path()) + .find(|f| { + f.is_file() + && 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 } /// Gives `pgn` to the user as the file `name` (a download, where the browser puts @@ -284,3 +376,61 @@ pub fn download_pgn(name: &str, pgn: &str) -> Result<(), String> { super::web::page::download(name, "application/x-chess-pgn", pgn.as_bytes()) .map_err(|e| format!("{e:?}")) } + +#[cfg(all(test, not(web)))] +mod tests { + use super::*; + + #[test] + fn dropped_files_are_sorted_into_databases() { + let dir = std::env::temp_dir().join(format!("cp-dropped-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let base = dir.join("Mega"); + std::fs::create_dir_all(&base).unwrap(); + let touch = |p: &std::path::Path| std::fs::write(p, b"x").unwrap(); + let games = dir.join("games.PGN"); + 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 lonely = dir.join("lost.cbg"); + for p in [&games, &archive, ¬es, &cbh, &lonely] { + touch(p); + } + for p in &parts { + touch(p); + } + let cbv = base.join("Other.cbv"); + touch(&cbv); + let empty = dir.join("empty"); + std::fs::create_dir_all(&empty).unwrap(); + touch(&empty.join("readme.md")); + + // Files of each kind; all the files of a ChessBase database give it once. + let mut dropped = vec![games.clone(), archive.clone()]; + dropped.extend(parts.iter().cloned()); + dropped.push(cbh.clone()); + let picked = sort_dropped(&dropped); + assert_eq!( + picked.paths, + vec![games.clone(), archive.clone(), cbh.clone()] + ); + assert!(picked.unsupported.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()]); + assert_eq!(picked.paths, vec![games.clone()]); + assert_eq!( + picked.unsupported, + vec!["notes.txt".to_string(), "lost.cbg".into()] + ); + + // 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); + + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/apps/desktop/src/prep_ui.rs b/apps/desktop/src/prep_ui.rs index abb99e0..af8559a 100644 --- a/apps/desktop/src/prep_ui.rs +++ b/apps/desktop/src/prep_ui.rs @@ -1929,7 +1929,7 @@ impl PrepScreen { ctx: &egui::Context, actions: &mut Vec, ) { - if crate::engines::own_stockfish().is_none() { + if crate::review_engine::engine().is_none() { actions.push(PrepAction::NeedEngine); return; } @@ -1940,11 +1940,11 @@ impl PrepScreen { } } - /// Starts the search for opening errors: ChessPenguin's Stockfish with the fixed + /// Starts the search for opening errors: Stockfish 19 (`review_engine`) with the fixed /// search of the game analysis (`game_review::run`), the same on every computer. fn start_engine(&mut self, ctx: &egui::Context, actions: &mut Vec) { self.error = None; - let Some(path) = crate::engines::own_stockfish() else { + let Some(path) = crate::review_engine::engine() else { actions.push(PrepAction::NeedEngine); return; }; diff --git a/apps/desktop/src/review_engine.rs b/apps/desktop/src/review_engine.rs new file mode 100644 index 0000000..04ced11 --- /dev/null +++ b/apps/desktop/src/review_engine.rs @@ -0,0 +1,432 @@ +//! 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. + +use crate::engines::EngineLocation; + +/// The engine to analyse with, now. +#[derive(Debug, PartialEq, Eq)] +pub enum Lookup { + Ready(EngineLocation), + /// 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), + /// No engine at all. + None, +} + +/// The engine to analyse with, from what is known (nothing is probed here): ours, or a +/// user's engine already found to be the same. +pub fn engine() -> Option { + #[cfg(not(web))] + return crate::engines::own_stockfish().or_else(native::verified); + #[cfg(web)] + crate::engines::own_stockfish() +} + +/// 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. +#[cfg_attr(web, allow(unused_variables))] +pub fn set_candidates(settings: &crate::settings::Settings) { + #[cfg(not(web))] + native::set_candidates(native::candidates(settings)); +} + +/// The engine to analyse with; an engine of the user's not probed yet (or changed since) +/// is probed now, in the background. +#[cfg_attr(web, allow(unused_variables))] +pub fn lookup(ctx: &egui::Context) -> Lookup { + #[cfg(not(web))] + return native::lookup(ctx); + #[cfg(web)] + match engine() { + Some(l) => Lookup::Ready(l), + None => Lookup::None, + } +} + +#[cfg(not(web))] +mod native { + use std::collections::{HashMap, HashSet}; + use std::path::{Path, PathBuf}; + use std::sync::{Mutex, OnceLock}; + + use serde::{Deserialize, Serialize}; + + use super::Lookup; + use crate::engines::EngineLocation; + + /// A probe's verdict on a file as it was. + #[derive(Clone, Debug, 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. + #[derive(Clone, Debug, PartialEq)] + pub(super) struct Candidate { + pub path: PathBuf, + pub label: String, + } + + #[derive(Default)] + pub(super) struct State { + pub candidates: Vec, + pub known: HashMap, + pub checking: HashSet, + /// Where the verdicts are kept (`None`: not read yet, or nowhere). + pub file: Option, + pub loaded: bool, + } + + fn state() -> &'static Mutex { + static STATE: OnceLock> = OnceLock::new(); + STATE.get_or_init(Default::default) + } + + 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; + } + } + f(&mut s) + } + + 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); + let mut out: Vec = active + .into_iter() + .chain(others) + .filter(|e| !e.builtin) + .map(|e| Candidate { + path: e.path.clone(), + label: e.name.clone(), + }) + .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, + }); + } + // 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 + } + + pub(super) fn set_candidates(candidates: Vec) { + with(|s| s.candidates = candidates); + } + + /// The file's size and time (seconds), when it is there. + pub(super) fn stamp(path: &Path) -> Option<(u64, u64)> { + let m = std::fs::metadata(path).ok()?; + if !m.is_file() { + return None; + } + let modified = m + .modified() + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map_or(0, |d| d.as_secs()); + 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)?; + s.known + .get(path) + .filter(|v| (v.size, v.modified) == (size, modified)) + } + + pub(super) fn verified() -> Option { + with(|s| { + s.candidates + .iter() + .find(|c| fresh(s, &c.path).is_some_and(|v| v.same)) + .map(|c| EngineLocation::Program(c.path.clone())) + }) + } + + pub(super) fn lookup(ctx: &egui::Context) -> Lookup { + match crate::engines::own_stockfish() { + Some(own) => Lookup::Ready(own), + None => lookup_without_own(ctx), + } + } + + /// [`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 { + Decision::Done(l) => l, + Decision::Probe(paths) => { + for p in paths { + spawn_probe(p, ctx.clone()); + } + Lookup::Checking + } + } + } + + pub(super) enum Decision { + Done(Lookup), + /// These 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. + pub(super) fn decide(s: &mut State) -> Decision { + let mut other = None; + let mut checking = false; + let mut to_probe = Vec::new(); + for c in &s.candidates { + if stamp(&c.path).is_none() { + continue; + } + match fresh(s, &c.path) { + Some(v) if v.same => { + return Decision::Done(Lookup::Ready(EngineLocation::Program(c.path.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() { + s.checking.extend(to_probe.iter().cloned()); + return Decision::Probe(to_probe); + } + if checking { + return Decision::Done(Lookup::Checking); + } + Decision::Done(other.map_or(Lookup::None, Lookup::Other)) + } + + /// Probes the file on a thread of its own and keeps the verdict. + fn spawn_probe(path: PathBuf, ctx: egui::Context) { + let spawned = std::thread::Builder::new() + .name("review-engine-probe".into()) + .spawn({ + let path = path.clone(); + move || { + let stamp = stamp(&path); + let config = uci::EngineConfig { + nice: 10, + ..uci::EngineConfig::new(&path) + }; + let probe = game_review::probe::probe(config); + record(&path, stamp, probe); + ctx.request_repaint(); + } + }); + if spawned.is_err() { + record( + &path, + stamp(&path), + Err(game_review::JobFailure::Start("no thread".into())), + ); + } + } + + pub(super) fn record( + path: &Path, + stamp: Option<(u64, u64)>, + probe: Result, + ) { + with(|s| { + s.checking.remove(path); + 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); + } + } + }); + } + + #[cfg(test)] + pub(super) fn reset(candidates: Vec) { + let mut s = state().lock().unwrap_or_else(|e| e.into_inner()); + *s = State { + candidates, + loaded: true, + ..State::default() + }; + } +} + +#[cfg(all(test, not(web)))] +mod tests { + use super::native::*; + use super::*; + use std::path::PathBuf; + use std::time::{Duration, Instant}; + + fn fake() -> PathBuf { + let fake = PathBuf::from(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../target/debug/fake_uci" + )); + assert!( + fake.exists(), + "build the fake engine first: cargo build -p uci --bin fake_uci" + ); + 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 { + 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) { + let uci::Score::Cp(cp) = score else { + unreachable!("the reference scores are in centipawns") + }; + let marker = fen.split(' ').next().unwrap_or_default(); + args.push(format!( + "--answer '{marker}' 'cp {cp} nodes {} pv {best}'", + nodes + nodes_delta + )); + } + let path = dir.join(file); + let script = format!( + "#!/bin/sh\nexec '{}' {}\n", + fake().display(), + args.join(" ") + ); + std::fs::write(&path, script).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + path + } + + fn settle(ctx: &egui::Context) -> Lookup { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let l = native::lookup_without_own(ctx); + if l != Lookup::Checking || Instant::now() > deadline { + return l; + } + std::thread::sleep(Duration::from_millis(20)); + } + } + + /// One test: the state is global. + #[test] + fn a_users_stockfish_19_is_taken_only_when_it_searches_as_ours() { + let dir = std::env::temp_dir().join(format!("cp-review-engine-{}", std::process::id())); + 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 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(), + }; + + // 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); + + // The same answers under another name: not taken either. + reset(vec![candidate(&named, "SF")]); + assert_eq!(settle(&ctx), Lookup::Other("Stockfish 18".into())); + + // 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())); + + // 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())) + ); + // Remembered: no second probe. + assert_eq!( + native::lookup_without_own(&ctx), + Lookup::Ready(EngineLocation::Program(same.clone())) + ); + + // 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())) + ); + + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/game-review/src/job.rs b/crates/game-review/src/job.rs index 6ac3834..d215e20 100644 --- a/crates/game-review/src/job.rs +++ b/crates/game-review/src/job.rs @@ -22,6 +22,9 @@ mod work; mod engines; #[cfg(not(target_family = "wasm"))] pub use engines::run; +// Whether an engine is the Stockfish 19 of the analysis (a user's own one). +#[cfg(not(target_family = "wasm"))] +pub mod probe; // The job in Web Workers: a browser's. #[cfg(target_family = "wasm")] mod workers; diff --git a/crates/game-review/src/job/engines.rs b/crates/game-review/src/job/engines.rs index eaf585e..3198886 100644 --- a/crates/game-review/src/job/engines.rs +++ b/crates/game-review/src/job/engines.rs @@ -136,7 +136,7 @@ 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. -fn search_once( +pub(super) fn search_once( handle: &uci::EngineHandle, pos: &EnginePosition, id: SearchId, diff --git a/crates/game-review/src/job/probe.rs b/crates/game-review/src/job/probe.rs new file mode 100644 index 0000000..e9e80ee --- /dev/null +++ b/crates/game-review/src/job/probe.rs @@ -0,0 +1,196 @@ +//! Whether an engine is the Stockfish 19 of the game analysis: its search gives the same +//! evaluations as ChessPenguin's, so a user's own Stockfish 19 can do the analysis and +//! the marks stay the same on every computer. +//! +//! Its name is not enough (a build of another commit, another network or a patched one +//! says the same). A few short searches in the fixed mode of the analysis — one +//! thread, a hash of [`SEARCH_HASH_MB`], `ucinewgame` before each, [`PROBE_NODES`] +//! nodes — are compared with those of ChessPenguin's Stockfish 19 ([`REFERENCE`]): the +//! best move, the score and the nodes of the line taken must all be the same. Stockfish +//! with one thread and a node limit is deterministic, whatever the CPU's instruction +//! 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 uci::{EnginePosition, Score}; + +use super::engines::search_once; +use super::{JobFailure, SEARCH_HASH_MB}; + +/// Nodes of each probe search (about 0.1 s each). +pub const PROBE_NODES: u64 = 100_000; + +/// The name Stockfish 19 gives itself (`id name`). +pub const STOCKFISH_19: &str = "Stockfish 19"; + +/// What a probe search gives: the best move, the score of the line taken (the side to +/// move's) and its nodes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ProbeAnswer { + pub best: String, + pub score: Score, + pub nodes: u64, +} + +/// The positions of the probe: an opening, a middlegame full of tactics, an endgame. +pub const PROBE_POSITIONS: [&str; 3] = [ + "r1bqkbnr/pppp1ppp/2n5/1B2p3/4P3/5N2/PPPP1PPP/RNBQK2R b KQkq - 3 3", + "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1", + "8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1", +]; + +/// ChessPenguin's Stockfish 19 (the official `stockfish-linux-x86-64-universal`, sha256 +/// of its archive in `engine_download`) on [`PROBE_POSITIONS`], taken 2026-10-31. The +/// same from its x86-64-avxvnni slice and from builds of its source for x86-64 (SSE2) +/// and x86-64-bmi2. +pub const REFERENCE: [(&str, Score, u64); 3] = [ + ("a7a6", Score::Cp(-36), 76_994), + ("e2a6", Score::Cp(-196), 49_328), + ("b4f4", Score::Cp(176), 38_955), +]; + +/// What the probe found. +#[derive(Clone, Debug, PartialEq, Eq)] +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). + pub answers: Vec, +} + +impl Probe { + /// Whether the engine is the Stockfish 19 of the analysis: its name and every answer. + pub fn same(&self) -> bool { + self.name.as_deref() == Some(STOCKFISH_19) + && self.answers.len() == REFERENCE.len() + && self + .answers + .iter() + .zip(REFERENCE) + .all(|(a, (best, score, nodes))| { + a.best == best && a.score == score && a.nodes == nodes + }) + } +} + +/// 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 { + let handle = uci::Engine::spawn_with(config, Box::new(|| {})) + .map_err(|e| JobFailure::Start(e.to_string()))?; + let name = handle.info().name.clone(); + 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(); + 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 Some((info, best)) = answer else { break }; + let (Some(best), Some(score), Some(nodes)) = ( + best.or_else(|| info.pv.first().cloned()), + info.score, + info.nodes, + ) else { + break; + }; + answers.push(ProbeAnswer { + best, + score: score.score, + nodes, + }); + } + handle.quit(); + Ok(Probe { name, answers }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fake() -> &'static str { + let fake = concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/debug/fake_uci"); + assert!( + std::path::Path::new(fake).exists(), + "build the fake engine first: cargo build -p uci --bin fake_uci" + ); + fake + } + + /// A fake engine answering every probe position as `answers` say. + fn engine(name: &str, answers: &[(&str, Score, u64)]) -> uci::EngineConfig { + let mut config = uci::EngineConfig::new(fake()); + config.args = vec!["--name".into(), name.into()]; + for (fen, (best, score, nodes)) in PROBE_POSITIONS.iter().zip(answers) { + let score = match score { + Score::Cp(cp) => format!("cp {cp}"), + Score::Mate(n) => format!("mate {n}"), + }; + let marker = fen.split(' ').next().unwrap_or_default(); + config.args.extend([ + "--answer".into(), + marker.into(), + format!("{score} nodes {nodes} pv {best}").into(), + ]); + } + config + } + + #[test] + fn the_reference_answers_pass() { + let p = probe(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:?}"); + } + + #[test] + fn other_answers_or_names_do_not() { + // 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"); + 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()); + // Another best move. + let mut other = REFERENCE; + other[0].0 = "g8f6"; + assert!(!probe(engine(STOCKFISH_19, &other)).unwrap().same()); + // The same answers under another name. + let p = probe(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()); + } + + /// A real Stockfish 19 gives [`REFERENCE`] (run when the reference is taken again + /// or another build is checked): + /// `CP_PROBE_ENGINE=/path/to/stockfish cargo test -p game-review probe -- --ignored`. + #[test] + #[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"); + println!("{p:?}"); + assert!(p.same(), "{p:?}"); + } + + #[test] + fn an_engine_that_does_not_start_fails() { + assert!(matches!( + probe(uci::EngineConfig::new("/nonexistent/engine")), + Err(JobFailure::Start(_)) + )); + } +} diff --git a/crates/game-review/src/lib.rs b/crates/game-review/src/lib.rs index 107415f..bad9f14 100644 --- a/crates/game-review/src/lib.rs +++ b/crates/game-review/src/lib.rs @@ -24,12 +24,12 @@ pub mod report; pub use features::{MoveFeatures, Rules}; #[cfg(target_family = "wasm")] pub use job::Dispatcher; -#[cfg(not(target_family = "wasm"))] -pub use job::run; pub use job::{ JobEvent, JobFailure, JobSettings, MAX_PROCESSES, PHONE_PROCESSES, SEARCH_HASH_MB, SEARCH_NODES, SEARCH_VERSION, SHALLOW_NODES, Target, estimate_secs, processes, }; +#[cfg(not(target_family = "wasm"))] +pub use job::{probe, run}; pub use report::{ Eval, Hardness, Judgement, Measure, Phase, Phases, Ply, Report, SideStats, judge, }; diff --git a/crates/uci/src/bin/fake_uci.rs b/crates/uci/src/bin/fake_uci.rs index 9c504b9..cf3604c 100644 --- a/crates/uci/src/bin/fake_uci.rs +++ b/crates/uci/src/bin/fake_uci.rs @@ -30,6 +30,9 @@ //! 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) +//! --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) //! //! Protocol violations by the GUI (`position`/`go`/`setoption`/`ucinewgame` //! during a search) are reported as `info string ERROR ...`. @@ -60,6 +63,7 @@ struct Cfg { hash_memory: bool, searchmoves: bool, shallow: Option<(u64, String)>, + answers: Vec<(String, String)>, } fn parse_args() -> Cfg { @@ -94,6 +98,11 @@ fn parse_args() -> Cfg { let n = num(args.next()); c.shallow = args.next().map(|m| (n, m)); } + "--answer" => { + if let (Some(m), Some(t)) = (args.next(), args.next()) { + c.answers.push((m, t)); + } + } other => { eprintln!("fake_uci: unknown flag {other}"); std::process::exit(2); @@ -280,6 +289,16 @@ fn main() { out("info string ERROR go during search"); } gos += 1; + if let Some((_, tail)) = cfg.answers.iter().find(|(m, _)| *m == marker) { + out(&format!("info depth 10 multipv 1 score {tail}")); + let best = tail + .split_whitespace() + .skip_while(|&t| t != "pv") + .nth(1) + .unwrap_or("0000"); + out(&format!("bestmove {best}")); + continue; + } if cfg.exit_after_go == Some(gos) { info_lines(&cfg, &marker, 1, multipv, 0); std::process::exit(1); diff --git a/docs/decisions.md b/docs/decisions.md index 832faf5..6b58941 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -193,7 +193,7 @@ Владелец: разбор партии всегда идёт на одних и тех же параметрах движка, пользователь их не выбирает — чтобы отметки ?!/?/??/!/!! и точность были одинаковы у всех людей и на всех машинах, а на слабых компьютерах и телефонах разбор шёл с разумной скоростью. Для анализа позиции «живым» движком выбор движка, потоков и памяти остаётся. -- **Поиск** (`crates/game-review/src/job.rs`): каждая позиция — `go nodes 1 000 000` (`SEARCH_NODES`; 0,85 с на i7-13700KF, глубина ≈ 24), Stockfish с `Threads=1`, `Hash=32` МБ (`SEARCH_HASH_MB`), `MultiPV=1`, `ucinewgame` перед **каждым** поиском, включая второй (`searchmoves`, для !!/!). Результат зависит только от позиции (с её историей): не от машины, порядка позиций и числа процессов. Движок — Stockfish 19 из ChessPenguin (на компьютере — встроенный или скачанный программой, на Android — его сборка); пользовательский движок для разбора не берётся. +- **Поиск** (`crates/game-review/src/job.rs`): каждая позиция — `go nodes 1 000 000` (`SEARCH_NODES`; 0,85 с на i7-13700KF, глубина ≈ 24), Stockfish с `Threads=1`, `Hash=32` МБ (`SEARCH_HASH_MB`), `MultiPV=1`, `ucinewgame` перед **каждым** поиском, включая второй (`searchmoves`, для !!/!). Результат зависит только от позиции (с её историей): не от машины, порядка позиций и числа процессов. Движок — Stockfish 19 из ChessPenguin (на компьютере — встроенный или скачанный программой, на Android — его сборка); пользовательский движок для разбора не берётся (с 2026-10-31 на компьютере — берётся Stockfish 19 пользователя, прошедший проверку, см. ниже). - **Параллельность** — несколькими процессами движка, каждый берёт следующую позицию: по числу логических ЦП, на компьютере не больше 8, на телефоне не больше 4, и не больше, чем помещается в свободную память (`MemAvailable` в `/proc/meminfo` на Linux и Android: ≈ 200 МБ сети NNUE — она у Stockfish 19 в общей памяти, одна на все процессы, — плюс ≈ 70 МБ на процесс; где память не узнать — только пределы). Итого ≈ 0,8 ГБ на 8 процессов, ≈ 0,5 ГБ на телефоне. Процессы — с `nice 10` и на компьютере, и на Android. - **Замер** (i7-13700KF, партия `rodent-roman-2026-10-27.pgn`: 113 позиций, 163 поиска): 1 процесс — 106 с, 4 — 28 с, 8 — 16 с; оценки всех трёх прогонов побайтно одинаковы (`examples/review_bench.rs`). Тест на `fake_uci --hash-memory` проверяет то же для 1/3/8 процессов и обратного порядка позиций. - **Версия поиска** `SEARCH_VERSION` (сейчас 1) записывается в кэш разбора (`ReviewMeta.search`). Разбор другой версии (в том числе все разборы до этого решения, на «Быстро/Обычно/Глубоко») — устаревший: отчёт показывается, в панели отчёта «Этот анализ сделан с прежними настройками движка» и «Обновить», которое пересчитывает всё заново (не дополняет). Смена узлов, памяти, движка или его версии — повышать `SEARCH_VERSION`. @@ -222,3 +222,12 @@ - **Базы — только чтение, прямо с диска**, без копии: Chrome/Edge помнят выбранный файл (одно «разрешить»), Firefox/Safari — файл выбирается заново после перезагрузки; по желанию — «оставить копию в браузере» с показом занятого и свободного места (квота браузера) и отказом с объяснением, если не помещается. - **Свои партии** (игры с движком, созданные для анализа), разборы и настройки — в хранилище браузера (OPFS/IndexedDB) с запросом постоянного хранения, показом занятого места и кнопкой «скачать мои партии в PGN». - **Интерфейс адаптируется под веб** (палец, узкие экраны, открытие файлов кнопкой/перетаскиванием, замена Ctrl+W/Ctrl+N, установка на главный экран) — сначала дизайн. + +## Разбор партии на Stockfish 19 пользователя; перетаскивание файлов (2026-10-31) + +Владелец одобрил по жалобе пользователя (свой 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». Пока файл над окном — подсветка «Отпустите, чтобы открыть», как в вебе.