diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index d12e7f5..806bb14 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -2513,11 +2513,14 @@ impl App { } Async::DatabasesDropped(paths) => { // As «Add database»; the game on the screen stays, so it is told. + // The first one ends up first on the shelf (as the shelf has it: a + // link to a database there is that database). + let mut first = None; for p in paths.iter().rev() { - self.settings.touch_database(p); + first = Some(self.settings.touch_database(p)); } - if let Some(first) = paths.first() { - self.library.select_db(first, ctx); + if let Some(first) = first { + self.library.select_db(&first, ctx); } self.settings_dirty = true; if self.game.is_some() { @@ -2542,11 +2545,14 @@ impl App { self.library.forget(&old); crate::platform::files::forget(&old); } + // The first one ends up first on the shelf (as the shelf has it: a + // link to a database there is that database). + let mut first = None; for p in paths.iter().rev() { - self.settings.touch_database(p); + first = Some(self.settings.touch_database(p)); } - if let Some(first) = paths.first() { - self.library.select_db(first, ctx); + if let Some(first) = first { + self.library.select_db(&first, ctx); } self.settings_dirty = true; } @@ -2831,12 +2837,7 @@ impl App { /// 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) { 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…"), - ); - } + let waited = !self.review_wait.is_empty(); // 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| { @@ -2844,13 +2845,21 @@ impl App { }; self.review_wait.retain(|p| !same_kind(p)); self.review_wait.push(pending); - self.poll_review_wait(ctx); + // Said only when an engine is really being checked (not when the answer is + // known already: then it starts, or the offer says why not). + if self.poll_review_wait(ctx) && !waited { + self.toast( + ctx, + tr("Checking whether your engine can run the analysis…"), + ); + } } /// 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) { + /// Returns whether they still wait. + fn poll_review_wait(&mut self, ctx: &egui::Context) -> bool { use crate::review_engine::Lookup; let (game, prep) = ( self.game.as_ref().map(|g| g.serial), @@ -2858,10 +2867,10 @@ impl App { ); self.review_wait.retain(|p| still_waiting(p, game, prep)); if self.review_wait.is_empty() { - return; + return false; } match crate::review_engine::lookup(ctx) { - Lookup::Checking => {} + Lookup::Checking => return true, Lookup::Ready(_) => { for p in std::mem::take(&mut self.review_wait) { self.run_engine_pending(ctx, Some(p)); @@ -2880,6 +2889,7 @@ impl App { } } } + false } /// Runs what the user was doing when an engine had to be found first: on the game @@ -3547,7 +3557,7 @@ impl eframe::App for App { } } if !self.review_wait.is_empty() { - self.poll_review_wait(&ctx); + let _ = self.poll_review_wait(&ctx); } self.offer_events(&ctx); self.page_frame(&ctx); diff --git a/apps/desktop/src/engine_offer.rs b/apps/desktop/src/engine_offer.rs index 40828cf..866e0cd 100644 --- a/apps/desktop/src/engine_offer.rs +++ b/apps/desktop/src/engine_offer.rs @@ -521,13 +521,18 @@ fn instead_text(unfit: &crate::review_engine::Unfit, pending: Option) - ) .to_owned(), Why::NotStarted => trf("{engine} could not be started.", &[("engine", &engine)]), + Why::TimedOut => trf( + "{engine} did not finish the check in time; it will be checked again next time.", + &[("engine", &engine)], + ), Why::Other if unfit.from_settings => { trf("The settings name {engine}.", &[("engine", &engine)]) } Why::Other => trf("The system has {engine}.", &[("engine", &engine)]), }]; + let official = matches!(unfit.why, Why::Differs | Why::TimedOut); parts.push( - match (unfit.why == Why::Differs, errors) { + match (official, errors) { (true, false) => tr( "So that the marks are the same on every computer, game analysis runs on the official build.", ), @@ -544,7 +549,7 @@ fn instead_text(unfit: &crate::review_engine::Unfit, pending: Option) - .to_owned(), ); parts.push( - if unfit.why == Why::Differs { + if official { tr("Download it?") } else { tr("Download Stockfish 19?") @@ -635,6 +640,12 @@ mod tests { "{t}" ); assert!(t.contains("Download it?")); + let t = text(Why::TimedOut, true, game); + assert!( + t.starts_with("Rodent V 1.2 did not finish the check in time"), + "{t}" + ); + assert!(t.contains("runs on the official build") && 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/i18n.rs b/apps/desktop/src/i18n.rs index 73e4e2c..ef326c1 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -15414,6 +15414,17 @@ const ROWS: &[[&str; 9]] = &[ "Sizning Stockfish 19 ChessPenguin yig‘masidan boshqacha hisoblaydi (boshqa yig‘ma yoki tarmoq).", "Сіздің Stockfish 19 ChessPenguin жинағынан басқаша есептейді (басқа жинақ немесе желі).", ], + [ + "{engine} did not finish the check in time; it will be checked again next time.", + "{engine} не успел ответить на проверку — проверю снова в следующий раз.", + "{engine} n’a pas répondu à temps à la vérification ; il sera vérifié à nouveau la prochaine fois.", + "{engine} hat die Prüfung nicht rechtzeitig beantwortet; beim nächsten Mal wird erneut geprüft.", + "{engine} no respondió a tiempo a la comprobación; se comprobará de nuevo la próxima vez.", + "{engine} non ha risposto in tempo alla verifica; sarà verificato di nuovo la prossima volta.", + "{engine} não respondeu a tempo à verificação; será verificado de novo na próxima vez.", + "{engine} tekshiruvga o‘z vaqtida javob bermadi — keyingi safar yana tekshiriladi.", + "{engine} тексеруге уақытында жауап бермеді — келесі жолы қайта тексеріледі.", + ], [ "{engine} could not be started.", "Не удалось запустить {engine}.", diff --git a/apps/desktop/src/review_engine.rs b/apps/desktop/src/review_engine.rs index 527a64c..6ed3d12 100644 --- a/apps/desktop/src/review_engine.rs +++ b/apps/desktop/src/review_engine.rs @@ -19,6 +19,9 @@ pub enum Why { Differs, /// It did not start or did not answer. NotStarted, + /// It calls itself Stockfish 19 but did not finish the check in time (a slow or + /// stuck machine): not remembered, checked again at the next request. + TimedOut, } /// The user's engine that does not do: its name (`id name`, else what the settings @@ -146,10 +149,13 @@ mod native { 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, + /// Files that did not start or did not finish the check, until it is said (by + /// the real file): why, and the name the engine gave. + pub failed: HashMap)>, pub checking: HashSet, pub threads: Vec>, + /// How long a probe may take (shorter in the tests). + pub limits: ProbeLimits, /// Where the verdicts are kept (`None`: nowhere). pub file: Option, pub loaded: bool, @@ -281,9 +287,9 @@ mod native { pub(super) fn lookup_without_own(ctx: &egui::Context) -> Lookup { match with(decide) { Decision::Done(l) => l, - Decision::Probe(paths) => { - for p in paths { - spawn_probe(p, ctx.clone()); + Decision::Probe(candidates) => { + for c in candidates { + spawn_probe(c, ctx.clone()); } Lookup::Checking } @@ -292,8 +298,9 @@ mod native { pub(super) enum Decision { Done(Lookup), - /// These real files are to be probed (and are marked as being probed). - Probe(Vec), + /// These candidates are to be probed (their real files are marked as being + /// probed). + Probe(Vec), } /// What the verdicts say of the candidates; files without one are to be probed. @@ -313,8 +320,8 @@ mod native { }; 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 if let Some((why, name)) = s.failed.get(&c.real) { + unfit.get_or_insert_with(|| said(name.as_ref(), *why)); } else { match fresh(s, &c.real) { Some(v) if v.same => { @@ -329,12 +336,12 @@ mod native { }; unfit.get_or_insert_with(|| said(v.name.as_ref(), why)); } - None => to_probe.push(c.real.clone()), + None => to_probe.push(c.clone()), } } } if !to_probe.is_empty() { - s.checking.extend(to_probe.iter().cloned()); + s.checking.extend(to_probe.iter().map(|c| c.real.clone())); return Decision::Probe(to_probe); } if checking { @@ -344,8 +351,13 @@ mod native { Decision::Done(unfit.map_or(Lookup::None, Lookup::Unfit)) } - /// Probes the real file on a thread of its own and keeps the verdict. - fn spawn_probe(real: PathBuf, ctx: egui::Context) { + /// Probes the engine on a thread of its own, started by the path it is known by + /// (a snap or a wrapper looks at the name it is started by), and keeps the verdict + /// for its real file. The engine dies with that thread (the program quitting in + /// the middle of a handshake leaves no process behind). + fn spawn_probe(c: Candidate, ctx: egui::Context) { + let real = c.real.clone(); + let limits = with(|s| s.limits); let spawned = std::thread::Builder::new() .name("review-engine-probe".into()) .spawn({ @@ -354,11 +366,11 @@ mod native { let stamp = stamp(&real); let config = uci::EngineConfig { nice: 10, - ..uci::EngineConfig::new(&real) + kill_with_parent: true, + ..uci::EngineConfig::new(&c.path) }; let quitting = || QUITTING.load(Ordering::Relaxed); - let probe = - game_review::probe::probe(config, ProbeLimits::default(), &quitting); + let probe = game_review::probe::probe(config, limits, &quitting); if !quitting() { record(&real, stamp, probe); ctx.request_repaint(); @@ -389,6 +401,10 @@ mod native { return; }; match probe { + // Not remembered: tried again at the next request. + Ok(p) if p.timed_out => { + s.failed.insert(real.to_path_buf(), (Why::TimedOut, p.name)); + } Ok(p) => { s.known.insert( real.to_path_buf(), @@ -401,9 +417,8 @@ mod native { ); save(s); } - // Not remembered: tried again at the next request. Err(_) => { - s.failed.insert(real.to_path_buf()); + s.failed.insert(real.to_path_buf(), (Why::NotStarted, None)); } } }); @@ -424,13 +439,23 @@ mod native { false } + /// How long the program waits for the probes when it quits. + const QUIT_WAIT: std::time::Duration = std::time::Duration::from_secs(2); + 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. + // A probe in a search gives up within a tenth of a second and quits its engine; + // one in a hung handshake is not waited for: its engine dies with its thread + // when the program ends (`kill_with_parent`). + let deadline = std::time::Instant::now() + QUIT_WAIT; for t in threads { - let _ = t.join(); + while !t.is_finished() && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + if t.is_finished() { + let _ = t.join(); + } } } @@ -440,6 +465,10 @@ mod native { *s = State { candidates, loaded: true, + limits: ProbeLimits { + search: std::time::Duration::from_millis(300), + total: std::time::Duration::from_secs(2), + }, ..State::default() }; } @@ -552,6 +581,44 @@ mod tests { assert_eq!(lookup_without_own(&ctx), Lookup::Checking); assert_eq!(settle(&ctx), unfit("Broken one", true, Why::NotStarted)); + // A «Stockfish 19» that does not finish in time: said once, not remembered. + let slow = dir.join("sf-slow"); + let script = format!( + "#!/bin/sh\nexec '{}' --name 'Stockfish 19' --ignore-nodes\n", + fake().display() + ); + std::fs::write(&slow, script).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&slow, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + reset(vec![settings(&slow, "Slow")]); + assert_eq!(settle(&ctx), unfit("Stockfish 19", true, Why::TimedOut)); + assert_eq!(lookup_without_own(&ctx), Lookup::Checking); + assert_eq!(settle(&ctx), unfit("Stockfish 19", true, Why::TimedOut)); + + // Started by the name it is known by (a wrapper looking at its name), the + // verdict kept for the real file. + #[cfg(unix)] + { + let picky = dir.join("picky"); + let script = format!( + "#!/bin/sh\n[ \"$(basename \"$0\")\" = sf-launch ] || exit 3\nexec '{}'\n", + same.display() + ); + std::fs::write(&picky, script).unwrap(); + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&picky, std::fs::Permissions::from_mode(0o755)).unwrap(); + let launch = dir.join("sf-launch"); + std::os::unix::fs::symlink(&picky, &launch).unwrap(); + reset(vec![settings(&launch, "Launcher")]); + assert_eq!( + settle(&ctx), + Lookup::Ready(EngineLocation::Program(launch.clone())) + ); + } + // The reference answers: taken, even after another engine in the list. reset(vec![settings(&differs, "A"), settings(&same, "B")]); let ready = Lookup::Ready(EngineLocation::Program(same.clone())); diff --git a/apps/desktop/src/settings.rs b/apps/desktop/src/settings.rs index 15eec29..c293d35 100644 --- a/apps/desktop/src/settings.rs +++ b/apps/desktop/src/settings.rs @@ -283,9 +283,17 @@ impl Settings { self.active_engine.and_then(|i| self.engines.get(i)) } - pub fn touch_database(&mut self, path: &Path) { - self.databases.retain(|p| p != path); - self.databases.insert(0, path.to_path_buf()); + /// Puts the database first on the shelf; a database there already by another path + /// to the same file (a link) keeps its path. Returns the path on the shelf. + pub fn touch_database(&mut self, path: &Path) -> PathBuf { + let real = |p: &Path| std::fs::canonicalize(p).ok(); + let same = |p: &PathBuf| p == path || real(p).is_some_and(|r| Some(r) == real(path)); + let kept = match self.databases.iter().position(same) { + Some(i) => self.databases.remove(i), + None => path.to_path_buf(), + }; + self.databases.insert(0, kept.clone()); + kept } } @@ -312,6 +320,31 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { mod tests { use super::*; + /// A database put on the shelf again by a link to its file stays itself, once. + #[cfg(unix)] + #[test] + fn a_link_to_a_database_on_the_shelf_does_not_add_it_twice() { + let dir = std::env::temp_dir().join(format!("cp-shelf-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (base, other, link) = (dir.join("a.pgn"), dir.join("b.pgn"), dir.join("link.pgn")); + std::fs::write(&base, "").unwrap(); + std::fs::write(&other, "").unwrap(); + std::os::unix::fs::symlink(&base, &link).unwrap(); + let mut s = Settings::default(); + s.databases.clear(); + assert_eq!(s.touch_database(&base), base); + assert_eq!(s.touch_database(&other), other); + assert_eq!(s.touch_database(&link), base); + assert_eq!(s.databases, vec![base.clone(), other.clone()]); + // A database gone from the disk is still told by its path. + let gone = dir.join("gone.pgn"); + s.touch_database(&gone); + assert_eq!(s.touch_database(&gone), gone); + assert_eq!(s.databases.len(), 3); + let _ = std::fs::remove_dir_all(&dir); + } + /// The settings of 1.x kept the engine options of the game analysis and the /// quality of the preparation: they are read without them now. #[test] diff --git a/crates/uci/Cargo.toml b/crates/uci/Cargo.toml index 277b87b..edf7801 100644 --- a/crates/uci/Cargo.toml +++ b/crates/uci/Cargo.toml @@ -17,7 +17,7 @@ js-sys = "0.3" web-sys = { version = "0.3", features = ["Worker", "MessageEvent", "ErrorEvent"] } [target.'cfg(unix)'.dependencies] -# nice(2) for EngineConfig::nice (std has no way to lower a child's priority). +# nice(2) for EngineConfig::nice, prctl(2) for kill_with_parent (std has neither). libc = "0.2" # Test helper: deterministic fake UCI engine used by tests/ via CARGO_BIN_EXE_fake_uci. diff --git a/crates/uci/src/process.rs b/crates/uci/src/process.rs index 97b92a6..76912a6 100644 --- a/crates/uci/src/process.rs +++ b/crates/uci/src/process.rs @@ -38,6 +38,10 @@ pub struct EngineConfig { /// Variables added to the engine's environment (Rodent IV on Android finds its /// personalities and books by `RODENT4HOME`). pub env: Vec<(OsString, OsString)>, + /// Linux and Android: the engine is killed when the thread that started it ends + /// (`PR_SET_PDEATHSIG`), and so when the program ends, even in the middle of the + /// handshake. For engines whose starting thread lives as long as they should. + pub kill_with_parent: bool, } impl EngineConfig { @@ -49,6 +53,7 @@ impl EngineConfig { timeouts: Timeouts::default(), nice: 0, env: Vec::new(), + kill_with_parent: false, } } } @@ -307,14 +312,23 @@ fn spawn_impl(cfg: EngineConfig, waker: Waker) -> Result Option { + let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + stat.rsplit_once(") ")?.1.chars().next() +} + +/// `kill_with_parent`: the engine dies with the thread that started it (the program +/// quitting while a handshake hangs); without it, it lives on. +#[cfg(target_os = "linux")] +#[test] +fn an_engine_can_die_with_its_starting_thread() { + let start = |kill: bool| { + std::thread::spawn(move || { + let mut c = config(&[]); + c.kill_with_parent = kill; + let handle = Engine::spawn_with(c, Box::new(|| {})).expect("spawn fake engine"); + let pid = handle.pid(); + // Never quit: as if the program ended under it. + std::mem::forget(handle); + pid + }) + .join() + .expect("the thread") + }; + let gone = |pid: u32| { + let deadline = Instant::now() + Duration::from_secs(5); + loop { + match proc_state(pid) { + None | Some('Z') | Some('X') => return true, + _ if Instant::now() > deadline => return false, + _ => std::thread::sleep(Duration::from_millis(20)), + } + } + }; + let killed = start(true); + assert!(gone(killed), "the engine outlived its thread"); + let kept = start(false); + std::thread::sleep(Duration::from_millis(300)); + assert!( + matches!(proc_state(kept), Some('S' | 'R')), + "{:?}", + proc_state(kept) + ); + unsafe { + libc::kill(kept as i32, libc::SIGKILL); + } +} diff --git a/docs/decisions.md b/docs/decisions.md index a1424e9..e53e9a3 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -228,9 +228,9 @@ Владелец одобрил по жалобе пользователя (свой stockfish в настройках, анализ позиции работает, а разбор просил скачать). - **Движок разбора на компьютере** (`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`); при выходе из программы прерывается, процесс движка завершается (или убивается). +- **Проверка** (`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`), движок запускается по пути из настроек/`PATH` (snap и обёртки смотрят на имя запуска), вердикт — для реального файла. При выходе программа ждёт проверки не дольше 2 с; движок, зависший на рукопожатии, умирает вместе с потоком проверки (`EngineConfig::kill_with_parent`, `PR_SET_PDEATHSIG` на Linux). - **Кэш**: вердикт по реальному файлу (ссылки разрешены) + размер + время, вместе с ключом эталона (`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` рядом, база один раз (дубли по реальному файлу); папка — базы в ней (без вложенных), пустая — тост; несуществующий файл — «Не найдено: …»; прочее — «Это не база: …». Брошенные файлы не заменяют базу из «Выбрать снова»; отмена этого диалога его завершает. Пока файл над окном — подсветка окна с рамкой и карточка «Отпустите, чтобы открыть». +- **Ожидание проверки** привязано к своей партии/подготовке (номер экрана): закрыта или открыта другая — разбор не начнётся на чужой; разбор партии и ошибки в дебютах ждут отдельно; «Проанализировать движком» (заново) сохраняется. Тост «Проверяю, подойдёт ли ваш движок для разбора…» — только когда движок действительно проверяется. +- **Окно, если не подошёл** — пять случаев: другой движок («В настройках указан …» / «В системе найден …»), «Ваш Stockfish 19 считает иначе, чем сборка ChessPenguin (другая сборка или сеть)…», «Не удалось запустить …», «… не успел ответить на проверку — проверю снова в следующий раз»; затем зачем нужна официальная сборка, «Скачать?», «Ваш движок остаётся для анализа позиции» (кроме незапустившегося) и «…начнётся сам после загрузки»; ниже — «N МБ · с официальной страницы Stockfish». Без движка — как прежде. +- **Перетаскивание на компьютере** (`platform::files::take_dropped`): брошенные файлы открываются как «Добавить базу» (на полку, выбирается первая; партия на экране не закрывается, тогда тост «Добавлено на полку: …»). `.pgn/.cbh/.cbv/.zip/.7z` — базы; другие файлы ChessBase-базы (`.cbg`, `.cba`, `.cbj`, … — известные расширения) — её `.cbh` рядом, база один раз (дубли по реальному файлу); папка — базы в ней (без вложенных), пустая — тост; несуществующий файл — «Не найдено: …»; прочее — «Это не база: …». База, уже стоящая на полке под другим путём к тому же файлу (ссылка), второй раз не добавляется (`touch_database` сравнивает реальные файлы). Брошенные файлы не заменяют базу из «Выбрать снова»; отмена этого диалога его завершает. Пока файл над окном — подсветка окна с рамкой и карточка «Отпустите, чтобы открыть». - **Где работает перетаскивание**: Windows, macOS, Linux в X11 и XWayland. В сеансе Wayland окно перетаскивание не принимает (система и не показывает «можно отпустить»): в winit 0.30.13, на котором стоит eframe 0.36, перетаскивание есть только в X11 (`platform_impl/linux/x11/event_processor.rs`), в `wayland/` его нет. Принудительный запуск через X11 не делаем (без обходов).