great moves (task 27): the button and progress in the conditions line, the «!!» column, the question, the summary, one engine job

This commit is contained in:
vrubelroman 2026-11-27 16:03:04 +03:00
parent c3a06653d6
commit 9a2cebd940
8 changed files with 2227 additions and 18 deletions

View file

@ -301,6 +301,11 @@ pub struct App {
toast_repertoire: Option<(trainer::repertoire::RepertoireId, String)>,
/// The database a copy of chosen games made: the toast's «Open».
toast_open_db: Option<PathBuf>,
/// The search for great moves (task 27): its question, the list and conditions of
/// the pass under way, and its summary.
brilliant_start: Option<crate::brilliant_ui::StartDialog>,
brilliant_pass: Option<crate::brilliant::PassMeta>,
brilliant_summary: Option<crate::brilliant_ui::Summary>,
applied_dark: Option<bool>,
debug: DebugStartup,
}
@ -572,6 +577,9 @@ impl App {
#[cfg(not(web))]
toast_repertoire: None,
toast_open_db: None,
brilliant_start: None,
brilliant_pass: None,
brilliant_summary: None,
applied_dark: None,
debug: DebugStartup::from_env(),
}
@ -1948,6 +1956,296 @@ impl App {
self.own.new_base = Some(own_db::NewBaseDialog::new(dir, after));
}
/// Why the engine cannot take the search for great moves now, if it cannot (one engine
/// job in the program, task 27 §4.5).
fn engine_job_busy(&self) -> Option<String> {
if self.prep.as_ref().is_some_and(|p| p.running()) {
return Some(
tr("The engine is busy searching opening errors in a preparation: wait or stop it")
.to_owned(),
);
}
if let Some(g) = self.game.as_ref().filter(|g| g.review_running()) {
return Some(trf(
"The engine is busy reviewing {game}",
&[("game", &g.title())],
));
}
None
}
/// While the search for great moves runs, what cannot start says why.
fn pass_busy(&self) -> Option<String> {
let job = self.library.pass.as_ref()?;
Some(trf(
"Searching for great moves in «{db}»: {i} of {n}. Stop it in the library",
&[
("db", &own_db::base_name(&job.source)),
("i", &job.done()),
("n", &job.records.len()),
],
))
}
/// «!! Find great moves»: the question first (or the summary, when every game is
/// analysed already).
fn ask_great_moves(
&mut self,
ctx: &egui::Context,
path: PathBuf,
records: Vec<u32>,
filter: chess_import::chessbase::base::Filter,
) {
if self.library.pass.is_some() {
return;
}
if let Some(why) = self.engine_job_busy() {
self.toast(ctx, why);
return;
}
let (Some(db), Some(cache)) = (self.library.database(&path), crate::review::cache_dir())
else {
return;
};
let about = if filter == chess_import::chessbase::base::Filter::default() {
tr("all games").to_owned()
} else {
tr("matching the conditions").to_owned()
};
let mut dialog =
crate::brilliant_ui::StartDialog::new(ctx, path, db, records, filter, about, cache);
// `CP_BRILLIANT_RUN=1`: no question.
if std::env::var_os("CP_BRILLIANT_RUN").is_some() {
let cancel = std::sync::atomic::AtomicBool::new(false);
if let (Some(db), Some(cache)) = (
self.library.database(&dialog.source),
crate::review::cache_dir(),
) {
dialog.counted = Some(crate::brilliant_ui::count(
&db,
&dialog.records,
&dialog.filter,
&cache,
&cancel,
));
}
self.start_great_moves(ctx, dialog);
return;
}
self.brilliant_start = Some(dialog);
}
/// Starts the pass of `dialog` over its games not analysed yet.
fn start_great_moves(&mut self, ctx: &egui::Context, dialog: crate::brilliant_ui::StartDialog) {
let mut dialog = dialog;
let Some(counted) = dialog.counted.take() else {
return;
};
let Some(crate::engines::EngineLocation::Program(engine)) = crate::review_engine::engine()
else {
self.toast(
ctx,
tr("The search needs Stockfish 19: start «Analyse game» once to get it"),
);
return;
};
let (Some(db), Some(cache)) = (
self.library.database(&dialog.source),
crate::review::cache_dir(),
) else {
return;
};
// One engine job: the live analysis stops.
if self.analysis.is_on() {
self.analysis.stop();
self.live_paused = false;
}
let path = engine.clone();
let engine = crate::brilliant::Engine {
config: crate::review::engine_config(&engine),
settings: game_review::JobSettings::new(crate::review::processes(), None),
fits: Box::new(move |name| crate::review_engine::name_fits(&path, name)),
pause: if std::env::var_os("CP_BRILLIANT_SLOW").is_some() {
std::time::Duration::from_millis(1500)
} else {
std::time::Duration::ZERO
},
};
let index = self.library.marks(&dialog.source);
// The list in the table's order: the analysed ones are taken first (at once).
let mut list = counted.reviewed.clone();
list.extend(&counted.left);
let order: std::collections::HashMap<u32, usize> = dialog
.records
.iter()
.enumerate()
.map(|(i, r)| (*r, i))
.collect();
list.sort_by_key(|r| order.get(r).copied().unwrap_or(usize::MAX));
match crate::brilliant::PassJob::start(
ctx,
dialog.source.clone(),
db,
list,
dialog.filter.clone(),
index,
cache,
engine,
) {
Ok(job) => {
self.library.set_pass_error(&dialog.source, None);
self.library.pass = Some(job);
self.brilliant_pass =
Some((dialog.filter.clone(), dialog.about.clone(), counted.skipped));
}
Err(e) => self.toast(ctx, e.to_string()),
}
}
/// The summary of `records` of `source`.
#[allow(clippy::too_many_arguments)]
fn great_moves_summary(
&mut self,
source: &std::path::Path,
records: &[u32],
sides: &crate::brilliant::Sides,
filter: &chess_import::chessbase::base::Filter,
about: String,
stopped: Option<(usize, usize)>,
skipped: Vec<(u32, crate::brilliant::Skip)>,
) {
let Some(db) = self.library.database(source) else {
return;
};
let index = self.library.marks(source);
let Ok(index) = index.lock() else {
return;
};
self.brilliant_summary = Some(crate::brilliant_ui::Summary::new(
source, &db, &index, records, sides, filter, about, stopped, skipped,
));
}
/// Every frame: the pass's state in the conditions lines, its end, the question and
/// the summary; and the engine taken by the pass for everything else.
fn great_moves_frame(&mut self, ctx: &egui::Context) {
let busy = self.engine_job_busy();
self.library.set_engine_busy(busy);
let pass_busy = self.pass_busy();
if let Some(p) = self.prep.as_mut() {
p.engine_blocked = pass_busy;
}
let estimate = |rest: &[u32]| rest.len() as f64 * 60.0 / crate::review::processes() as f64;
self.library.show_pass(estimate);
if let Some(job) = self.library.pass.as_ref()
&& let Some((end, sides)) = job.poll()
{
let job = self.library.pass.take().expect("pass");
let (filter, about, mut skipped) = self.brilliant_pass.take().unwrap_or_default();
skipped.extend(end.skipped.iter().copied());
skipped.sort_unstable_by_key(|(r, _)| *r);
skipped.dedup();
let reviewed = end.reviewed.len();
let total = job.records.len();
match &end.outcome {
crate::brilliant::Outcome::Finished => self.great_moves_summary(
&job.source,
&job.records,
&sides,
&filter,
about,
None,
skipped,
),
crate::brilliant::Outcome::Stopped if reviewed == 0 => {
self.toast(ctx, tr("Search stopped: no game was reviewed"));
}
crate::brilliant::Outcome::Stopped => self.great_moves_summary(
&job.source,
&job.records,
&sides,
&filter,
about,
Some((reviewed, total)),
skipped,
),
crate::brilliant::Outcome::EngineFailed(why) => {
let text = trf(
"The engine failed: {reason}. {i} of {n} reviewed",
&[("reason", why), ("i", &reviewed), ("n", &total)],
);
self.library.set_pass_error(&job.source, Some(text));
}
crate::brilliant::Outcome::SourceChanged => {
let text = trf(
"«{db}» changed; the search stopped. {i} of {n} reviewed",
&[
("db", &own_db::base_name(&job.source)),
("i", &reviewed),
("n", &total),
],
);
self.library.set_pass_error(&job.source, Some(text));
}
}
}
if let Some(dialog) = self.brilliant_start.as_mut()
&& let Some(outcome) = dialog.show(ctx)
{
let dialog = self.brilliant_start.take().expect("dialog");
match outcome {
crate::brilliant_ui::StartOutcome::Cancel => {}
crate::brilliant_ui::StartOutcome::Start => self.start_great_moves(ctx, dialog),
crate::brilliant_ui::StartOutcome::Summary => {
if let Some(c) = &dialog.counted {
let reviewed = c.reviewed.clone();
self.great_moves_summary(
&dialog.source,
&reviewed,
&c.sides,
&dialog.filter,
dialog.about.clone(),
None,
c.skipped.clone(),
);
}
}
}
}
if self.game.is_none()
&& let Some(summary) = self.brilliant_summary.as_mut()
&& let Some(action) = summary.show(ctx)
{
let source = summary.source.clone();
use crate::brilliant_ui::SummaryAction;
match action {
SummaryAction::Close => self.brilliant_summary = None,
SummaryAction::Select(record) => {
self.library.choose_only(&source, record as usize);
}
SummaryAction::Sort => self.library.sort_by_marks(&source),
SummaryAction::Continue(rest) => {
let filter = self
.brilliant_summary
.take()
.map(|_| chess_import::chessbase::base::Filter::default())
.unwrap_or_default();
self.ask_great_moves(ctx, source, rest, filter);
}
SummaryAction::Open { record, ply } => {
self.brilliant_summary = None;
let at = self.library.database(&source).and_then(|db| {
let game = db.load_game(record as usize)?.game;
let node = *game.mainline().get(ply as usize)?;
Some(game.node(node)?.position().clone())
});
self.library.choose_only(&source, record as usize);
self.open_game(ctx, source, record as usize, at);
}
}
}
}
/// Starts the copy of the chosen records of the new-database dialog into `path`
/// (task 42): the file appears only when the copy is whole; the user stays in the
/// source database.
@ -2476,6 +2774,12 @@ impl App {
/// A new game against Maia. Her model missing (a rematch, a game from a position):
/// the dialog with the same choices, to download it.
fn start_play(&mut self, ctx: &egui::Context, start: crate::play::Start) {
// No game against the engine while the search for great moves runs (the owner's
// decision, task 27).
if let Some(why) = self.pass_busy() {
self.toast(ctx, why);
return;
}
let Some(maia) = crate::play::engine_for(&start) else {
self.play_dialog = Some(crate::play::Dialog::for_start(&self.settings, &start));
return;
@ -3200,6 +3504,13 @@ impl App {
fn toggle_engine(&mut self, ctx: &egui::Context) {
self.live_paused = false;
// The search for great moves has the engine (task 27 §4.5).
if !self.analysis.is_on()
&& let Some(why) = self.pass_busy()
{
self.toast(ctx, why);
return;
}
if self.prep.as_ref().is_some_and(|p| p.running()) && !self.analysis.is_on() {
self.toast(
ctx,
@ -4068,6 +4379,7 @@ impl eframe::App for App {
// dropped before the game is drawn (its header names the target).
let _ = self.current_target();
let shelf = self.shelf_dbs();
let pass_busy = self.pass_busy();
if repertoire_visible {
#[cfg(not(web))]
self.show_repertoire(ui, &ctx);
@ -4078,7 +4390,9 @@ impl eframe::App for App {
self.library.poll();
self.reference.dbs = shelf;
// The preparation's engine goes on under the game; no game analysis meanwhile.
game.engine_busy = self.prep.as_ref().is_some_and(|p| p.running());
game.engine_busy =
self.prep.as_ref().is_some_and(|p| p.running()) || self.library.pass.is_some();
game.engine_busy_why = pass_busy.clone();
if let Some(p) = self.prep.as_mut() {
p.poll_quietly(&ctx, &self.settings);
}
@ -4265,6 +4579,15 @@ impl eframe::App for App {
self.settings_ui.tab = Tab::Translation;
}
GameAction::Toast(m) => self.toast(&ctx, m),
GameAction::Reviewed { path, index, entry } => {
let marks = self.library.marks(&path);
if let Ok(mut marks) = marks.lock() {
marks.set(index as u32, entry);
if let Err(e) = marks.save() {
eprintln!("marks: {e}");
}
}
}
GameAction::HintsChanged => self.settings_dirty = true,
GameAction::PauseLive => {
if self.analysis.is_on() {
@ -4431,6 +4754,11 @@ impl eframe::App for App {
}
}
LibraryAction::Notice(text) => self.toast(&ctx, text),
LibraryAction::FindGreatMoves {
path,
records,
filter,
} => self.ask_great_moves(&ctx, path, records, filter),
LibraryAction::EditGameData { path, index } => {
self.open_game(&ctx, path, index, None);
self.edit_game_data();
@ -4559,6 +4887,7 @@ impl eframe::App for App {
}
}
// A copy of chosen games ends whatever is on the screen.
self.great_moves_frame(&ctx);
if let Some(end) = self.library.poll_batch(&ctx) {
self.batch_ended(&ctx, end);
}
@ -4661,6 +4990,9 @@ impl eframe::App for App {
fn on_exit(&mut self) {
self.library.stop_batch();
if let Some(job) = self.library.pass.as_mut() {
job.shutdown(std::time::Duration::from_secs(3));
}
self.analysis.stop();
crate::review_engine::shutdown();
if let Some(p) = self.prep.as_mut() {

View file

@ -0,0 +1,615 @@
//! The windows of the search for great moves (task 27,
//! docs/design/task-27-brilliant-search-2026-11-27.md): the question before a pass
//! (§4.4) and the summary after it (§4.9).
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, channel};
use chess_import::Database;
use chess_import::chessbase::base::Filter;
use egui::{Key, RichText};
use game_review::{GameAnalysis, Judgement};
use crate::brilliant::{Found, Index, Sides, Skip, Totals};
use crate::i18n::{tr, trf};
/// What a list holds before a pass: the records already analysed, those to analyse with
/// their plies, those that cannot be, and the sides of the filter's player.
pub struct Counted {
pub reviewed: Vec<u32>,
pub left: Vec<u32>,
pub plies_left: Vec<usize>,
pub skipped: Vec<(u32, Skip)>,
pub sides: Sides,
}
/// Counts what of `records` is analysed (the analysis cache in `cache`), on this thread.
pub fn count(
db: &Database,
records: &[u32],
filter: &Filter,
cache: &Path,
cancel: &AtomicBool,
) -> Counted {
let store = crate::review::Cache(cache.to_path_buf());
let mut c = Counted {
reviewed: Vec::new(),
left: Vec::new(),
plies_left: Vec::new(),
skipped: Vec::new(),
sides: crate::brilliant::player_sides(db, filter, cancel),
};
for &r in records {
if cancel.load(Ordering::Relaxed) {
break;
}
let Some(parsed) = db.load_game(r as usize) else {
c.skipped.push((r, Skip::Unreadable));
continue;
};
if let Some(skip) = crate::brilliant::skip_of(&parsed.game, db.row(r as usize).chess960) {
c.skipped.push((r, skip));
continue;
}
let a = GameAnalysis::with_store(&parsed.game, Some(&store));
let by_engine = a.has_data() && a.meta.as_ref().is_some_and(|m| m.nodes > 0);
if by_engine && (a.stale() || a.missing() == 0) {
c.reviewed.push(r);
} else {
c.left.push(r);
c.plies_left.push(parsed.game.mainline().len());
}
}
c
}
/// The question before a pass.
pub struct StartDialog {
pub source: PathBuf,
pub records: Vec<u32>,
pub filter: Filter,
pub about: String,
rx: Receiver<Counted>,
cancel: Arc<AtomicBool>,
pub counted: Option<Counted>,
}
pub enum StartOutcome {
Start,
/// Every game is analysed already, or «Summary of the reviewed».
Summary,
Cancel,
}
impl StartDialog {
pub fn new(
ctx: &egui::Context,
source: PathBuf,
db: Arc<Database>,
records: Vec<u32>,
filter: Filter,
about: String,
cache: PathBuf,
) -> StartDialog {
let (tx, rx) = channel();
let cancel = Arc::new(AtomicBool::new(false));
let (list, f, c, ctx) = (records.clone(), filter.clone(), cancel.clone(), ctx.clone());
let _ = std::thread::Builder::new()
.name("brilliant-count".into())
.spawn(move || {
let _ = tx.send(count(&db, &list, &f, &cache, &c));
ctx.request_repaint();
});
StartDialog {
source,
records,
filter,
about,
rx,
cancel,
counted: None,
}
}
pub fn show(&mut self, ctx: &egui::Context) -> Option<StartOutcome> {
if self.counted.is_none()
&& let Ok(c) = self.rx.try_recv()
{
// All analysed: no question, the summary at once.
if c.left.is_empty() {
self.counted = Some(c);
return Some(StartOutcome::Summary);
}
self.counted = Some(c);
}
let mut out = None;
let name = crate::own_db::base_name(&self.source);
egui::Window::new(tr("Find great moves"))
.id(egui::Id::new("brilliant_start"))
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
.default_width(520.0)
.show(ctx, |ui| {
ui.set_width(520.0);
ui.label(
RichText::new(format!(
"{name} · {} {}",
crate::i18n::games(self.records.len()),
self.about
))
.weak()
.size(12.0),
);
ui.add_space(8.0);
// Two lines kept for the counts: the window does not jump when they come.
ui.allocate_ui(egui::vec2(520.0, 40.0), |ui| match &self.counted {
None => {
ui.horizontal(|ui| {
ui.spinner();
ui.label(tr("Counting the games already reviewed…"));
});
}
Some(c) => {
let secs = crate::brilliant::estimate_secs(
c.plies_left.iter().copied(),
crate::review::processes(),
);
ui.label(trf(
"The engine will review {games}: about {time}.",
&[
("games", &crate::i18n::games(c.left.len())),
("time", &crate::review::format_duration(secs)),
],
));
if !c.reviewed.is_empty() {
ui.label(trf(
"{k} are already reviewed: their marks come from the saved review.",
&[("k", &c.reviewed.len())],
));
}
}
});
ui.add_space(6.0);
ui.label(trf(
"The computer will be busy (up to {p} Stockfish 19 processes). You can keep working and stop at any time; the reviewed games are kept.",
&[("p", &crate::review::processes())],
));
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let ready = self.counted.is_some();
let start = ui.add_enabled(ready, egui::Button::new(tr("Start")));
if start.clicked() || (ready && ui.input(|i| i.key_pressed(Key::Enter))) {
out = Some(StartOutcome::Start);
}
if ui.button(tr("Cancel")).clicked() {
out = Some(StartOutcome::Cancel);
}
if let Some(c) = &self.counted
&& !c.reviewed.is_empty()
&& ui
.button(trf(
"Summary of the reviewed ({k})",
&[("k", &c.reviewed.len())],
))
.clicked()
{
out = Some(StartOutcome::Summary);
}
});
});
if out.is_none() && ctx.input(|i| i.key_pressed(Key::Escape)) {
out = Some(StartOutcome::Cancel);
}
out
}
}
impl Drop for StartDialog {
fn drop(&mut self) {
self.cancel.store(true, Ordering::Relaxed);
}
}
/// A row of the summary's list: a !! move of a game.
pub struct BrilliantRow {
pub record: u32,
pub found: Found,
/// «White — Black · result · event · date».
pub game: String,
}
/// The summary of a pass (§4.9), counted anew from the index for the pass's list.
pub struct Summary {
pub source: PathBuf,
pub about: String,
pub totals: Totals,
/// The filter's player and the games counted for each colour.
pub player: Option<(String, usize, usize)>,
/// Stopped: analysed of all.
pub stopped: Option<(usize, usize)>,
/// Not analysed (for «Continue»).
pub rest: Vec<u32>,
pub skipped: Vec<(u32, Skip)>,
pub rows: Vec<BrilliantRow>,
pub selected: Option<usize>,
}
pub enum SummaryAction {
/// The game of a row chosen in the table behind.
Select(u32),
/// Open the game at the position after the move.
Open {
record: u32,
ply: u16,
},
Continue(Vec<u32>),
/// Sort the table by the «!!» column.
Sort,
Close,
}
impl Summary {
/// The summary of `records` (a pass's list, in its order) from `index`.
#[allow(clippy::too_many_arguments)]
pub fn new(
source: &Path,
db: &Database,
index: &Index,
records: &[u32],
sides: &Sides,
filter: &Filter,
about: String,
stopped: Option<(usize, usize)>,
skipped: Vec<(u32, Skip)>,
) -> Summary {
let totals = crate::brilliant::totals(index, records, sides);
let rest = records
.iter()
.copied()
.filter(|r| index.get(*r).is_none())
.collect();
let player = sides.player.as_ref().map(|(w, b)| {
let count = |v: &Vec<u32>| {
records
.iter()
.filter(|r| v.binary_search(r).is_ok())
.count()
};
(filter.player.text.trim().to_owned(), count(w), count(b))
});
let rows = totals
.brilliant
.iter()
.map(|(r, f)| {
let row = db.row(*r as usize);
let mut parts = vec![format!("{} — {}", row.white, row.black)];
parts.push(row.result.to_string());
if !row.event.trim().is_empty() && row.event != "?" {
parts.push(row.event.to_string());
}
let date = crate::library::display_date(&row.date);
if !date.is_empty() {
parts.push(date);
}
BrilliantRow {
record: *r,
found: f.clone(),
game: parts.join(" · "),
}
})
.collect();
Summary {
source: source.to_path_buf(),
about,
totals,
player,
stopped,
rest,
skipped,
rows,
selected: None,
}
}
pub fn show(&mut self, ctx: &egui::Context) -> Option<SummaryAction> {
let mut out = None;
let mut open = true;
let t = &self.totals;
let title = match self.stopped {
Some((i, n)) => trf(
"Search stopped · reviewed: {i} of {n}",
&[("i", &i), ("n", &n)],
),
None => trf(
"Summary · reviewed: {games}",
&[("games", &crate::i18n::games(t.games))],
),
};
let width = (ctx.content_rect().width() - 40.0).min(600.0);
egui::Window::new(title)
.id(egui::Id::new("brilliant_summary"))
.open(&mut open)
.collapsible(false)
.resizable(false)
.default_width(width)
.max_height(ctx.content_rect().height() - 80.0)
.show(ctx, |ui| {
ui.set_width(width);
let weak = |ui: &mut egui::Ui, text: String| {
ui.add(egui::Label::new(RichText::new(text).weak().size(12.0)).truncate());
};
weak(
ui,
format!("{} · {}", crate::own_db::base_name(&self.source), self.about),
);
if let Some((name, w, b)) = &self.player {
weak(
ui,
trf(
"Only the moves of «{name}» count: as White {w}, as Black {b}",
&[("name", name), ("w", w), ("b", b)],
),
);
}
if !self.skipped.is_empty() {
let reasons: Vec<&str> = {
let mut r: Vec<&str> = self.skipped.iter().map(|(_, s)| s.reason()).collect();
r.sort_unstable();
r.dedup();
r
};
weak(
ui,
trf(
"Not reviewed: {k} ({reason})",
&[("k", &self.skipped.len()), ("reason", &reasons.join(", "))],
),
);
}
if t.stale > 0 {
weak(
ui,
trf(
"{k} of them were reviewed with the previous engine settings",
&[("k", &t.stale)],
),
);
}
if !t.player_missing.is_empty() {
let numbers: Vec<String> =
t.player_missing.iter().map(|r| (r + 1).to_string()).collect();
ui.add(
egui::Label::new(
RichText::new(trf(
"In {k} games the player was not found by name: their moves did not count",
&[("k", &t.player_missing.len())],
))
.weak()
.size(12.0),
)
.truncate(),
)
.on_hover_text(numbers.join(", "));
}
if self.stopped.is_some() && !self.rest.is_empty() {
weak(
ui,
trf(
"{k} games are not reviewed: «Continue» reviews only them",
&[("k", &self.rest.len())],
),
);
}
ui.add_space(8.0);
let dark = ui.visuals().dark_mode;
egui::Grid::new("brilliant_totals")
.num_columns(2)
.spacing([12.0, 4.0])
.show(ui, |ui| {
let c = &t.counts;
for (j, n) in [
(Judgement::Brilliant, c.brilliant),
(Judgement::Great, c.great),
(Judgement::Inaccuracy, c.inaccuracies),
(Judgement::Mistake, c.mistakes),
(Judgement::Blunder, c.blunders),
] {
let color = if n == 0 {
ui.visuals().weak_text_color()
} else {
crate::review::judgement_text_color(j, dark)
};
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.label(RichText::new(n.to_string()).strong().size(15.0).color(color));
});
ui.label(
RichText::new(crate::review::judgement_plural(j))
.size(15.0)
.color(color),
);
ui.end_row();
}
let shown = |v: Option<String>| v.unwrap_or_else(|| "—".to_owned());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.label(
RichText::new(shown(t.acpl.map(|a| format!("{}", a.round() as i64))))
.strong()
.size(15.0),
);
});
ui.label(RichText::new(tr("Average centipawn loss")).size(15.0));
ui.end_row();
let color = t
.accuracy
.map(|a| crate::review::accuracy_color(a, dark))
.unwrap_or(ui.visuals().weak_text_color());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.label(
RichText::new(shown(t.accuracy.map(|a| format!("{}%", a.round() as i64))))
.strong()
.size(15.0)
.color(color),
);
});
let label = ui.label(RichText::new(tr("Average accuracy")).size(15.0));
if let Some((lo, hi)) = t.accuracy_range {
label.on_hover_text(trf(
"Average over {k}: from {min}% to {max}%",
&[
("k", &crate::i18n::games(t.sides)),
("min", &(lo.round() as i64)),
("max", &(hi.round() as i64)),
],
));
}
ui.end_row();
});
ui.separator();
if self.rows.is_empty() {
if t.counts.great > 0 {
ui.horizontal(|ui| {
ui.label(
RichText::new(tr(
"No brilliant moves. Games with ! — sort by the «!!» column",
))
.weak(),
);
if ui.link(tr("Sort")).clicked() {
out = Some(SummaryAction::Sort);
}
});
} else {
ui.label(RichText::new(tr("No brilliant or great moves")).weak());
}
} else {
ui.label(
RichText::new(trf("Games with !! ({n})", &[("n", &self.rows.len())]))
.strong()
.size(13.0),
);
let teal = crate::review::judgement_text_color(Judgement::Brilliant, dark);
let labels: Vec<String> = self.rows.iter().map(|r| r.found.label()).collect();
let move_w = labels
.iter()
.map(|l| {
ui.fonts_mut(|f| {
f.layout_no_wrap(
l.clone(),
egui::TextStyle::Body.resolve(ui.style()),
egui::Color32::WHITE,
)
.size()
.x
})
})
.fold(0.0, f32::max)
+ 12.0;
let rows = if ctx.content_rect().height() < 700.0 { 3 } else { 6 };
egui::ScrollArea::vertical()
.max_height(24.0 * rows as f32)
.auto_shrink([false, true])
.show_rows(ui, 24.0, self.rows.len(), |ui, range| {
for i in range {
let row = &self.rows[i];
let selected = self.selected == Some(i);
let (rect, resp) = ui.allocate_exact_size(
egui::vec2(ui.available_width(), 24.0),
egui::Sense::click(),
);
if selected {
ui.painter().rect_filled(rect, 0.0, ui.visuals().selection.bg_fill);
} else if resp.hovered() {
ui.painter()
.rect_filled(rect, 0.0, ui.visuals().widgets.hovered.weak_bg_fill);
}
let mut child = ui.new_child(
egui::UiBuilder::new()
.max_rect(rect.shrink2(egui::vec2(4.0, 0.0)))
.layout(egui::Layout::left_to_right(egui::Align::Center)),
);
let color = if selected { ui.visuals().selection.stroke.color } else { teal };
child.add_sized(
egui::vec2(move_w, 24.0),
egui::Label::new(RichText::new(&labels[i]).strong().color(color))
.selectable(false),
);
child.add(egui::Label::new(&row.game).truncate().selectable(false));
if resp.clicked() {
self.selected = Some(i);
out = Some(SummaryAction::Select(row.record));
}
if resp.double_clicked() {
out = Some(SummaryAction::Open {
record: row.record,
ply: row.found.ply,
});
}
}
});
ui.label(
RichText::new(tr(
"Click: choose the row in the table; double click: open at this move",
))
.weak()
.size(12.0),
);
// ↑ ↓ through the list, Enter opens.
let (up, down, enter) = ui.input(|i| {
(
i.key_pressed(Key::ArrowUp),
i.key_pressed(Key::ArrowDown),
i.key_pressed(Key::Enter),
)
});
if up || down {
let last = self.rows.len() - 1;
let next = match (self.selected, down) {
(None, _) => 0,
(Some(s), true) => (s + 1).min(last),
(Some(s), false) => s.saturating_sub(1),
};
self.selected = Some(next);
out = Some(SummaryAction::Select(self.rows[next].record));
}
if enter && let Some(s) = self.selected {
out = Some(SummaryAction::Open {
record: self.rows[s].record,
ply: self.rows[s].found.ply,
});
}
}
ui.add_space(6.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button(tr("Close")).clicked() {
out = Some(SummaryAction::Close);
}
if !self.rows.is_empty() {
let pick = self.selected.map(|s| &self.rows[s]);
if ui
.add_enabled(pick.is_some(), egui::Button::new(tr("Open game")))
.clicked()
&& let Some(r) = pick
{
out = Some(SummaryAction::Open {
record: r.record,
ply: r.found.ply,
});
}
}
if self.stopped.is_some()
&& !self.rest.is_empty()
&& ui.button(tr("Continue")).clicked()
{
out = Some(SummaryAction::Continue(self.rest.clone()));
}
});
});
if !open || (out.is_none() && ctx.input(|i| i.key_pressed(Key::Escape))) {
out = Some(SummaryAction::Close);
}
out
}
}

View file

@ -106,6 +106,9 @@ pub struct GameView {
/// The engine is busy with the opponent preparation: no game analysis meanwhile
/// (one engine job for the whole program, opponent-prep.md §4.3).
pub engine_busy: bool,
/// Why, when another job than the search for opening errors has it (the search for
/// great moves, task 27).
pub engine_busy_why: Option<String>,
/// The game's data were asked once (on its first add); not again.
pub data_asked: bool,
/// A newer version to offer (its number), next to Settings.
@ -182,6 +185,13 @@ pub enum GameAction {
OpenEngineSettings,
OpenSettings,
Toast(String),
/// The analysis of a game of a database ended: its marks go into that database's
/// index (task 27), so its row shows them.
Reviewed {
path: PathBuf,
index: usize,
entry: crate::brilliant::Entry,
},
/// A whole-game analysis started: pause the live engine (they would share the CPU).
PauseLive,
/// The whole-game analysis ended: resume the live engine if it was paused.
@ -251,6 +261,7 @@ impl GameView {
previous: None,
previous_prep: false,
engine_busy: false,
engine_busy_why: None,
data_asked: false,
target: None,
update: None,
@ -863,13 +874,26 @@ impl GameView {
) -> Vec<GameAction> {
let mut actions = Vec::new();
self.translation.update(ui.ctx(), &self.game, settings, hub);
if self.review.poll() {
let reviewed = self.review.poll();
if reviewed {
actions.push(GameAction::ResumeLive);
if let Some(e) = &self.review.error {
actions.push(GameAction::Toast(e.clone()));
}
}
self.review.refresh(&self.game);
if reviewed
&& self.review.error.is_none()
&& !self.game.is_modified()
&& self.review.missing() == 0
&& let Some(src) = &self.source
{
actions.push(GameAction::Reviewed {
path: src.path.clone(),
index: src.index,
entry: crate::brilliant::entry_of(&self.review.analysis, &self.game),
});
}
if analysis.status == Status::Running
&& let Some(e) = settings.active_engine()
{
@ -969,8 +993,10 @@ impl GameView {
if std::mem::take(&mut self.review_asked) {
if self.engine_busy {
actions.push(GameAction::Toast(
tr("Opening errors are being searched — wait or stop it in the report")
.to_owned(),
self.engine_busy_why.clone().unwrap_or_else(|| {
tr("Opening errors are being searched — wait or stop it in the report")
.to_owned()
}),
));
} else {
self.start_review(false, ui.ctx(), &mut actions);
@ -1074,9 +1100,9 @@ impl GameView {
tr("Analyse game: accuracy, inaccuracies, mistakes, blunders (Shift+A)"),
self.review.estimate()
))
.on_disabled_hover_text(tr(
"Opening errors are being searched — wait or stop it in the report",
))
.on_disabled_hover_text(self.engine_busy_why.clone().unwrap_or_else(|| {
tr("Opening errors are being searched — wait or stop it in the report").to_owned()
}))
.clicked()
{
self.review_asked = true;

View file

@ -20025,6 +20025,615 @@ const ROWS: &[[&str; 9]] = &[
"Tanlov bekor qilindi: baza o‘zgardi",
"Таңдау алынды: база өзгерді",
],
[
"The engine is busy searching opening errors in a preparation: wait or stop it",
"Движок занят: идёт поиск ошибок дебюта в подготовке — дождитесь или остановите его",
"Le moteur est occupé à chercher les erreurs d’ouverture d’une préparation : attendez ou arrêtez-le",
"Die Engine sucht gerade Eröffnungsfehler in einer Vorbereitung: warten oder anhalten",
"El motor está buscando errores de apertura en una preparación: espere o deténgalo",
"Il motore sta cercando errori d’apertura in una preparazione: attendi o fermalo",
"O motor está a procurar erros de abertura numa preparação: aguarde ou pare-o",
"Dvigatel tayyorgarlikda debyut xatolarini qidirmoqda — kuting yoki to‘xtating",
"Қозғалтқыш дайындықта дебют қателерін іздеуде — күтіңіз не тоқтатыңыз",
],
[
"all games",
"все партии базы",
"toutes les parties",
"alle Partien",
"todas las partidas",
"tutte le partite",
"todas as partidas",
"bazadagi barcha partiyalar",
"базаның барлық партиялары",
],
[
"matching the conditions",
"по условиям",
"selon les conditions",
"nach den Bedingungen",
"según las condiciones",
"secondo le condizioni",
"segundo as condições",
"shartlar bo‘yicha",
"шарттар бойынша",
],
[
"The search needs Stockfish 19: start «Analyse game» once to get it",
"Для поиска нужен Stockfish 19: один раз запустите «Анализ партии», чтобы его получить",
"La recherche a besoin de Stockfish 19 : lancez une fois « Analyser la partie » pour l’obtenir",
"Die Suche braucht Stockfish 19: einmal «Partie analysieren» starten, um ihn zu bekommen",
"La búsqueda necesita Stockfish 19: inicie una vez «Analizar partida» para obtenerlo",
"La ricerca richiede Stockfish 19: avvia una volta «Analizza partita» per ottenerlo",
"A pesquisa precisa do Stockfish 19: inicie uma vez «Analisar partida» para o obter",
"Qidiruv uchun Stockfish 19 kerak: uni olish uchun bir marta «Partiya tahlili»ni ishga tushiring",
"Іздеуге Stockfish 19 керек: оны алу үшін бір рет «Партия талдауын» іске қосыңыз",
],
[
"Search stopped: no game was reviewed",
"Поиск остановлен: ни одна партия не разобрана",
"Recherche arrêtée : aucune partie n’a été analysée",
"Suche angehalten: keine Partie wurde analysiert",
"Búsqueda detenida: no se analizó ninguna partida",
"Ricerca fermata: nessuna partita analizzata",
"Pesquisa parada: nenhuma partida foi analisada",
"Qidiruv to‘xtatildi: birorta ham partiya tahlil qilinmadi",
"Іздеу тоқтатылды: бірде-бір партия талданбады",
],
[
"The engine is busy reviewing {game}",
"Движок занят: идёт разбор партии {game}",
"Le moteur est occupé à analyser {game}",
"Die Engine analysiert gerade {game}",
"El motor está analizando {game}",
"Il motore sta analizzando {game}",
"O motor está a analisar {game}",
"Dvigatel {game} partiyasini tahlil qilmoqda",
"Қозғалтқыш {game} партиясын талдауда",
],
[
"Searching for great moves in «{db}»: {i} of {n}. Stop it in the library",
"Идёт поиск замечательных ходов в «{db}»: {i} из {n}. Остановить — в библиотеке",
"Recherche de très bons coups dans « {db} » : {i} sur {n}. Arrêtez-la dans la bibliothèque",
"Suche nach starken Zügen in «{db}»: {i} von {n}. Anhalten in der Bibliothek",
"Buscando jugadas notables en «{db}»: {i} de {n}. Deténgala en la biblioteca",
"Ricerca di mosse notevoli in «{db}»: {i} di {n}. Fermala nella libreria",
"A procurar lances notáveis em «{db}»: {i} de {n}. Pare-a na biblioteca",
"«{db}» da ajoyib yurishlar qidirilmoqda: {n} dan {i}. To‘xtatish — kutubxonada",
"«{db}» ішінде тамаша жүрістер ізделуде: {n} ішінен {i}. Тоқтату — кітапханада",
],
[
"The engine failed: {reason}. {i} of {n} reviewed",
"Движок остановился с ошибкой: {reason}. Разобрано {i} из {n}",
"Le moteur a échoué : {reason}. {i} sur {n} analysées",
"Die Engine ist ausgefallen: {reason}. {i} von {n} analysiert",
"El motor falló: {reason}. Analizadas {i} de {n}",
"Il motore si è fermato con un errore: {reason}. Analizzate {i} di {n}",
"O motor falhou: {reason}. Analisadas {i} de {n}",
"Dvigatel xato bilan to‘xtadi: {reason}. {n} dan {i} tasi tahlil qilindi",
"Қозғалтқыш қатемен тоқтады: {reason}. {n} ішінен {i} талданды",
],
[
"«{db}» changed; the search stopped. {i} of {n} reviewed",
"База «{db}» изменилась — поиск остановлен. Разобрано {i} из {n}",
"« {db} » a changé ; la recherche s’est arrêtée. {i} sur {n} analysées",
"«{db}» hat sich geändert; die Suche wurde angehalten. {i} von {n} analysiert",
"«{db}» cambió; la búsqueda se detuvo. Analizadas {i} de {n}",
"«{db}» è cambiato; la ricerca si è fermata. Analizzate {i} di {n}",
"«{db}» mudou; a pesquisa parou. Analisadas {i} de {n}",
"«{db}» bazasi o‘zgardi — qidiruv to‘xtatildi. {n} dan {i} tasi tahlil qilindi",
"«{db}» базасы өзгерді — іздеу тоқтатылды. {n} ішінен {i} талданды",
],
[
"Wait: the games are still being filtered",
"Подождите — партии ещё отбираются",
"Patientez : les parties sont encore en cours de filtrage",
"Bitte warten: die Partien werden noch gefiltert",
"Espere: las partidas todavía se están filtrando",
"Attendi: le partite sono ancora in fase di filtro",
"Aguarde: as partidas ainda estão a ser filtradas",
"Kuting — partiyalar hali tanlanmoqda",
"Күтіңіз — партиялар әлі іріктелуде",
],
[
"No games match these conditions",
"Нет партий по этим условиям",
"Aucune partie ne correspond à ces conditions",
"Keine Partien passen zu diesen Bedingungen",
"Ninguna partida cumple estas condiciones",
"Nessuna partita corrisponde a queste condizioni",
"Nenhuma partida corresponde a estas condições",
"Bu shartlar bo‘yicha partiya yo‘q",
"Бұл шарттар бойынша партия жоқ",
],
[
"Filter the games down to 100 or fewer",
"Отфильтруйте партии, чтобы их было не больше 100",
"Filtrez les parties pour en avoir 100 au plus",
"Filtern Sie auf höchstens 100 Partien",
"Filtre las partidas hasta 100 como máximo",
"Filtra le partite fino a non più di 100",
"Filtre as partidas até no máximo 100",
"Partiyalar 100 tadan ko‘p bo‘lmasin — filtrlang",
"Партиялар 100-ден аспайтындай сүзіңіз",
],
[
"!! Find moves",
"!! Найти ходы",
"!! Trouver des coups",
"!! Züge finden",
"!! Buscar jugadas",
"!! Trova mosse",
"!! Procurar lances",
"!! Yurishlarni topish",
"!! Жүрістерді табу",
],
[
"!! Find great moves",
"!! Найти замечательные ходы",
"!! Trouver de très bons coups",
"!! Starke Züge finden",
"!! Buscar jugadas notables",
"!! Trova mosse notevoli",
"!! Procurar lances notáveis",
"!! Ajoyib yurishlarni topish",
"!! Тамаша жүрістерді табу",
],
[
"Stopping…",
"Останавливаю…",
"Arrêt…",
"Wird angehalten…",
"Deteniendo…",
"Arresto…",
"A parar…",
"To‘xtatilmoqda…",
"Тоқтатылуда…",
],
[
"Stop the search; the reviewed games are kept",
"Остановить поиск; разобранные партии сохранятся",
"Arrêter la recherche ; les parties analysées sont conservées",
"Suche anhalten; analysierte Partien bleiben erhalten",
"Detener la búsqueda; las partidas analizadas se conservan",
"Ferma la ricerca; le partite analizzate restano",
"Parar a pesquisa; as partidas analisadas são guardadas",
"Qidiruvni to‘xtatish; tahlil qilingan partiyalar saqlanadi",
"Іздеуді тоқтату; талданған партиялар сақталады",
],
[
"Brilliant and great moves found by the engine: sort by them",
"Блестящие и замечательные ходы, найденные движком: сортировать по ним",
"Coups brillants et très bons trouvés par le moteur : trier par eux",
"Von der Engine gefundene brillante und starke Züge: danach sortieren",
"Jugadas brillantes y notables halladas por el motor: ordenar por ellas",
"Mosse brillanti e notevoli trovate dal motore: ordina per esse",
"Lances brilhantes e notáveis encontrados pelo motor: ordenar por eles",
"Dvigatel topgan ajoyib va zo‘r yurishlar: ular bo‘yicha saralash",
"Қозғалтқыш тапқан керемет және тамаша жүрістер: солар бойынша сұрыптау",
],
[
"Being reviewed…",
"Разбирается…",
"En cours d’analyse…",
"Wird analysiert…",
"Analizándose…",
"In analisi…",
"A ser analisada…",
"Tahlil qilinmoqda…",
"Талдануда…",
],
[
"Reviewed: no brilliant or great moves",
"Разобрана: блестящих и замечательных ходов нет",
"Analysée : aucun coup brillant ou très bon",
"Analysiert: keine brillanten oder starken Züge",
"Analizada: sin jugadas brillantes ni notables",
"Analizzata: nessuna mossa brillante o notevole",
"Analisada: sem lances brilhantes ou notáveis",
"Tahlil qilingan: ajoyib va zo‘r yurishlar yo‘q",
"Талданды: керемет және тамаша жүрістер жоқ",
],
[
"Reviewed with the previous engine settings",
"Разбор прежними настройками движка",
"Analysée avec les anciens réglages du moteur",
"Mit den früheren Engine-Einstellungen analysiert",
"Analizada con los ajustes anteriores del motor",
"Analizzata con le impostazioni precedenti del motore",
"Analisada com as definições anteriores do motor",
"Dvigatelning avvalgi sozlamalari bilan tahlil",
"Қозғалтқыштың бұрынғы баптауларымен талданған",
],
[
"Searching in «{db}»: {i} of {n}; stop it there",
"Идёт поиск в «{db}»: {i} из {n} — остановите его там",
"Recherche dans « {db} » : {i} sur {n} ; arrêtez-la là-bas",
"Suche in «{db}»: {i} von {n}; dort anhalten",
"Buscando en «{db}»: {i} de {n}; deténgala allí",
"Ricerca in «{db}»: {i} di {n}; fermala lì",
"A pesquisar em «{db}»: {i} de {n}; pare-a lá",
"«{db}» da qidiruv: {n} dan {i} — uni o‘sha yerda to‘xtating",
"«{db}» ішінде іздеу: {n} ішінен {i} — оны сонда тоқтатыңыз",
],
[
"Now: {n}",
"Сейчас: {n}",
"Actuellement : {n}",
"Jetzt: {n}",
"Ahora: {n}",
"Ora: {n}",
"Agora: {n}",
"Hozir: {n}",
"Қазір: {n}",
],
[
"Analysed {i} of {n} · ≈ {time} left",
"Проанализировано {i} из {n} · осталось ≈ {time}",
"Analysées {i} sur {n} · encore ≈ {time}",
"Analysiert {i} von {n} · noch ≈ {time}",
"Analizadas {i} de {n} · quedan ≈ {time}",
"Analizzate {i} di {n} · restano ≈ {time}",
"Analisadas {i} de {n} · faltam ≈ {time}",
"{n} dan {i} tasi tahlil qilindi · qoldi ≈ {time}",
"{n} ішінен {i} талданды · қалды ≈ {time}",
],
[
"{i} of {n}",
"{i} из {n}",
"{i} sur {n}",
"{i} von {n}",
"{i} de {n}",
"{i} di {n}",
"{i} de {n}",
"{n} dan {i}",
"{n} ішінен {i}",
],
[
"In «{db}»: {i} of {n}",
"В «{db}»: {i} из {n}",
"Dans « {db} » : {i} sur {n}",
"In «{db}»: {i} von {n}",
"En «{db}»: {i} de {n}",
"In «{db}»: {i} di {n}",
"Em «{db}»: {i} de {n}",
"«{db}» da: {n} dan {i}",
"«{db}» ішінде: {n} ішінен {i}",
],
[
"Review {games} with the engine and mark the !! and ! moves found (Shift+A)",
"Разобрать движком {games} и отметить найденные !! и ! (Shift+A)",
"Analyser {games} avec le moteur et marquer les !! et ! trouvés (Maj+A)",
"{games} mit der Engine analysieren und gefundene !! und ! markieren (Umschalt+A)",
"Analizar {games} con el motor y marcar los !! y ! hallados (Mayús+A)",
"Analizza {games} con il motore e segna i !! e ! trovati (Maiusc+A)",
"Analisar {games} com o motor e marcar os !! e ! encontrados (Shift+A)",
"{games}ni dvigatel bilan tahlil qilib, topilgan !! va ! ni belgilash (Shift+A)",
"{games} қозғалтқышпен талдап, табылған !! және ! белгілеу (Shift+A)",
],
[
"Open at {move}",
"Открыть на ходе {move}",
"Ouvrir au coup {move}",
"Bei {move} öffnen",
"Abrir en {move}",
"Apri alla mossa {move}",
"Abrir no lance {move}",
"{move} yurishida ochish",
"{move} жүрісінде ашу",
],
[
"Cannot be reviewed: {reason}",
"Не разбирается: {reason}",
"Analyse impossible : {reason}",
"Kann nicht analysiert werden: {reason}",
"No se puede analizar: {reason}",
"Non analizzabile: {reason}",
"Não pode ser analisada: {reason}",
"Tahlil qilinmaydi: {reason}",
"Талданбайды: {reason}",
],
[
"Brilliant moves: {n}: {moves}",
"Блестящих ходов: {n} — {moves}",
"Coups brillants : {n} — {moves}",
"Brillante Züge: {n} — {moves}",
"Jugadas brillantes: {n} — {moves}",
"Mosse brillanti: {n} — {moves}",
"Lances brilhantes: {n} — {moves}",
"Ajoyib yurishlar: {n} — {moves}",
"Керемет жүрістер: {n} — {moves}",
],
[
"Great moves: {n}: {moves}",
"Замечательных: {n} — {moves}",
"Très bons coups : {n} — {moves}",
"Starke Züge: {n} — {moves}",
"Jugadas notables: {n} — {moves}",
"Mosse notevoli: {n} — {moves}",
"Lances notáveis: {n} — {moves}",
"Zo‘r yurishlar: {n} — {moves}",
"Тамаша жүрістер: {n} — {moves}",
],
[
"the engine is no longer the Stockfish 19 that was checked",
"движок уже не тот Stockfish 19, что был проверен",
"le moteur n’est plus le Stockfish 19 vérifié",
"die Engine ist nicht mehr der geprüfte Stockfish 19",
"el motor ya no es el Stockfish 19 comprobado",
"il motore non è più lo Stockfish 19 verificato",
"o motor já não é o Stockfish 19 verificado",
"dvigatel endi tekshirilgan Stockfish 19 emas",
"қозғалтқыш енді тексерілген Stockfish 19 емес",
],
[
"Chess960", "Chess960", "Chess960", "Chess960", "Chess960", "Chess960", "Chess960",
"Chess960", "Chess960",
],
[
"a null move in the main line",
"пустой ход в основной линии",
"un coup nul dans la ligne principale",
"ein Nullzug in der Hauptvariante",
"una jugada nula en la línea principal",
"una mossa nulla nella linea principale",
"um lance nulo na linha principal",
"asosiy liniyada bo‘sh yurish",
"негізгі линияда бос жүріс",
],
[
"the game cannot be read",
"партию не удалось прочитать",
"la partie est illisible",
"die Partie ist nicht lesbar",
"la partida no se puede leer",
"la partita non è leggibile",
"a partida não pode ser lida",
"partiyani o‘qib bo‘lmadi",
"партия оқылмады",
],
[
"Find great moves",
"Найти замечательные ходы",
"Trouver de très bons coups",
"Starke Züge finden",
"Buscar jugadas notables",
"Trova mosse notevoli",
"Procurar lances notáveis",
"Ajoyib yurishlarni topish",
"Тамаша жүрістерді табу",
],
[
"Counting the games already reviewed…",
"Считаю, сколько партий уже разобрано…",
"Décompte des parties déjà analysées…",
"Zähle bereits analysierte Partien…",
"Contando las partidas ya analizadas…",
"Conto le partite già analizzate…",
"A contar as partidas já analisadas…",
"Allaqachon tahlil qilingan partiyalar sanalmoqda…",
"Талданып қойған партиялар саналуда…",
],
[
"The engine will review {games}: about {time}.",
"Движок разберёт {games} — примерно {time}.",
"Le moteur analysera {games} : environ {time}.",
"Die Engine analysiert {games}: etwa {time}.",
"El motor analizará {games}: unos {time}.",
"Il motore analizzerà {games}: circa {time}.",
"O motor vai analisar {games}: cerca de {time}.",
"Dvigatel {games}ni tahlil qiladi — taxminan {time}.",
"Қозғалтқыш {games} талдайды — шамамен {time}.",
],
[
"{k} are already reviewed: their marks come from the saved review.",
"{k} уже разобраны: их отметки возьмутся из сохранённого разбора.",
"{k} sont déjà analysées : leurs marques viennent de l’analyse enregistrée.",
"{k} sind bereits analysiert: ihre Markierungen kommen aus der gespeicherten Analyse.",
"{k} ya están analizadas: sus marcas salen del análisis guardado.",
"{k} sono già analizzate: i loro segni vengono dall’analisi salvata.",
"{k} já estão analisadas: as suas marcas vêm da análise guardada.",
"{k} tasi allaqachon tahlil qilingan: belgilari saqlangan tahlildan olinadi.",
"{k} талданып қойған: белгілері сақталған талдаудан алынады.",
],
[
"The computer will be busy (up to {p} Stockfish 19 processes). You can keep working and stop at any time; the reviewed games are kept.",
"Компьютер будет загружен (до {p} процессов Stockfish 19). Работать с программой можно; остановить — в любой момент, разобранные партии сохранятся.",
"L’ordinateur sera occupé (jusqu’à {p} processus Stockfish 19). Vous pouvez continuer à travailler et arrêter à tout moment ; les parties analysées sont conservées.",
"Der Computer wird ausgelastet (bis zu {p} Stockfish-19-Prozesse). Sie können weiterarbeiten und jederzeit anhalten; analysierte Partien bleiben erhalten.",
"El ordenador estará ocupado (hasta {p} procesos de Stockfish 19). Puede seguir trabajando y detenerlo en cualquier momento; las partidas analizadas se conservan.",
"Il computer sarà occupato (fino a {p} processi Stockfish 19). Puoi continuare a lavorare e fermare in qualsiasi momento; le partite analizzate restano.",
"O computador ficará ocupado (até {p} processos Stockfish 19). Pode continuar a trabalhar e parar a qualquer momento; as partidas analisadas são guardadas.",
"Kompyuter band bo‘ladi ({p} tagacha Stockfish 19 jarayoni). Dastur bilan ishlash mumkin; istalgan payt to‘xtatish mumkin, tahlil qilinganlar saqlanadi.",
"Компьютер жүктеледі ({p} дейін Stockfish 19 процесі). Бағдарламамен жұмыс істеуге болады; кез келген уақытта тоқтатуға болады, талданғандар сақталады.",
],
[
"Start",
"Начать",
"Commencer",
"Starten",
"Empezar",
"Avvia",
"Começar",
"Boshlash",
"Бастау",
],
[
"Summary of the reviewed ({k})",
"Итог по разобранным ({k})",
"Bilan des analysées ({k})",
"Übersicht der analysierten ({k})",
"Resumen de las analizadas ({k})",
"Riepilogo delle analizzate ({k})",
"Resumo das analisadas ({k})",
"Tahlil qilinganlar yakuni ({k})",
"Талданғандар қорытындысы ({k})",
],
[
"Search stopped · reviewed: {i} of {n}",
"Поиск остановлен · разобрано: {i} из {n}",
"Recherche arrêtée · analysées : {i} sur {n}",
"Suche angehalten · analysiert: {i} von {n}",
"Búsqueda detenida · analizadas: {i} de {n}",
"Ricerca fermata · analizzate: {i} di {n}",
"Pesquisa parada · analisadas: {i} de {n}",
"Qidiruv to‘xtatildi · tahlil qilindi: {n} dan {i}",
"Іздеу тоқтатылды · талданды: {n} ішінен {i}",
],
[
"Summary · reviewed: {games}",
"Итог · разобрано: {games}",
"Bilan · analysées : {games}",
"Übersicht · analysiert: {games}",
"Resumen · analizadas: {games}",
"Riepilogo · analizzate: {games}",
"Resumo · analisadas: {games}",
"Yakun · tahlil qilindi: {games}",
"Қорытынды · талданды: {games}",
],
[
"Only the moves of «{name}» count: as White {w}, as Black {b}",
"Считаются только ходы игрока «{name}»: белыми {w}, чёрными {b}",
"Seuls les coups de « {name} » comptent : avec les Blancs {w}, avec les Noirs {b}",
"Nur die Züge von «{name}» zählen: mit Weiß {w}, mit Schwarz {b}",
"Solo cuentan las jugadas de «{name}»: con blancas {w}, con negras {b}",
"Contano solo le mosse di «{name}»: col Bianco {w}, col Nero {b}",
"Só contam os lances de «{name}»: de brancas {w}, de pretas {b}",
"Faqat «{name}» yurishlari hisoblanadi: oq bilan {w}, qora bilan {b}",
"Тек «{name}» жүрістері есептеледі: ақпен {w}, қарамен {b}",
],
[
"Not reviewed: {k} ({reason})",
"Не разобраны: {k} ({reason})",
"Non analysées : {k} ({reason})",
"Nicht analysiert: {k} ({reason})",
"No analizadas: {k} ({reason})",
"Non analizzate: {k} ({reason})",
"Não analisadas: {k} ({reason})",
"Tahlil qilinmagan: {k} ({reason})",
"Талданбаған: {k} ({reason})",
],
[
"{k} of them were reviewed with the previous engine settings",
"{k} из них разобраны прежними настройками движка",
"{k} d’entre elles ont été analysées avec les anciens réglages du moteur",
"{k} davon wurden mit den früheren Engine-Einstellungen analysiert",
"{k} de ellas se analizaron con los ajustes anteriores del motor",
"{k} di esse sono state analizzate con le impostazioni precedenti",
"{k} delas foram analisadas com as definições anteriores do motor",
"Ulardan {k} tasi dvigatelning avvalgi sozlamalari bilan tahlil qilingan",
"Олардың {k} қозғалтқыштың бұрынғы баптауларымен талданған",
],
[
"In {k} games the player was not found by name: their moves did not count",
"В {k} партиях игрок не найден по имени — их ходы не считались",
"Dans {k} parties le joueur n’a pas été trouvé par son nom : leurs coups ne comptent pas",
"In {k} Partien wurde der Spieler nicht am Namen erkannt: ihre Züge zählen nicht",
"En {k} partidas no se encontró al jugador por el nombre: sus jugadas no cuentan",
"In {k} partite il giocatore non è stato trovato per nome: le loro mosse non contano",
"Em {k} partidas o jogador não foi encontrado pelo nome: os seus lances não contam",
"{k} ta partiyada o‘yinchi nomi bo‘yicha topilmadi — ularning yurishlari hisoblanmadi",
"{k} партияда ойыншы аты бойынша табылмады — олардың жүрістері есептелмеді",
],
[
"{k} games are not reviewed: «Continue» reviews only them",
"{k} партий не разобраны — «Продолжить» разберёт только их",
"{k} parties ne sont pas analysées : « Continuer » n’analyse qu’elles",
"{k} Partien sind nicht analysiert: «Fortsetzen» analysiert nur sie",
"{k} partidas sin analizar: «Continuar» analiza solo esas",
"{k} partite non analizzate: «Continua» analizza solo quelle",
"{k} partidas não analisadas: «Continuar» analisa só essas",
"{k} ta partiya tahlil qilinmagan — «Davom etish» faqat ularni tahlil qiladi",
"{k} партия талданбаған — «Жалғастыру» тек соларды талдайды",
],
[
"Average accuracy",
"Средняя точность",
"Précision moyenne",
"Durchschnittliche Genauigkeit",
"Precisión media",
"Precisione media",
"Precisão média",
"O‘rtacha aniqlik",
"Орташа дәлдік",
],
[
"Average over {k}: from {min}% to {max}%",
"Среднее по {k}: от {min}% до {max}%",
"Moyenne sur {k} : de {min} % à {max} %",
"Durchschnitt über {k}: von {min} % bis {max} %",
"Media de {k}: del {min} % al {max} %",
"Media su {k}: dal {min}% al {max}%",
"Média de {k}: de {min}% a {max}%",
"{k} bo‘yicha o‘rtacha: {min}% dan {max}% gacha",
"{k} бойынша орташа: {min}%-дан {max}%-ға дейін",
],
[
"No brilliant moves. Games with ! — sort by the «!!» column",
"Блестящих ходов нет. Партии с ! — сортировка по колонке «!!»",
"Aucun coup brillant. Parties avec ! — tri par la colonne « !! »",
"Keine brillanten Züge. Partien mit ! — nach der Spalte «!!» sortieren",
"Sin jugadas brillantes. Partidas con ! — ordenar por la columna «!!»",
"Nessuna mossa brillante. Partite con ! — ordina per la colonna «!!»",
"Sem lances brilhantes. Partidas com ! — ordenar pela coluna «!!»",
"Ajoyib yurishlar yo‘q. ! li partiyalar — «!!» ustuni bo‘yicha saralash",
"Керемет жүрістер жоқ. ! бар партиялар — «!!» бағаны бойынша сұрыптау",
],
[
"Sort",
"Отсортировать",
"Trier",
"Sortieren",
"Ordenar",
"Ordina",
"Ordenar",
"Saralash",
"Сұрыптау",
],
[
"No brilliant or great moves",
"Блестящих и замечательных ходов нет",
"Aucun coup brillant ou très bon",
"Keine brillanten oder starken Züge",
"Sin jugadas brillantes ni notables",
"Nessuna mossa brillante o notevole",
"Sem lances brilhantes ou notáveis",
"Ajoyib va zo‘r yurishlar yo‘q",
"Керемет және тамаша жүрістер жоқ",
],
[
"Games with !! ({n})",
"Партии с !! ({n})",
"Parties avec !! ({n})",
"Partien mit !! ({n})",
"Partidas con !! ({n})",
"Partite con !! ({n})",
"Partidas com !! ({n})",
"!! li partiyalar ({n})",
"!! бар партиялар ({n})",
],
[
"Click: choose the row in the table; double click: open at this move",
"Щелчок — выбрать строку в таблице, двойной щелчок — открыть на этом ходе",
"Clic : choisir la ligne dans le tableau ; double clic : ouvrir à ce coup",
"Klick: Zeile in der Tabelle wählen; Doppelklick: bei diesem Zug öffnen",
"Clic: elegir la fila en la tabla; doble clic: abrir en esta jugada",
"Clic: scegli la riga nella tabella; doppio clic: apri a questa mossa",
"Clique: escolher a linha na tabela; duplo clique: abrir neste lance",
"Bosish — jadvalda qatorni tanlash, ikki marta bosish — shu yurishda ochish",
"Шерту — кестеде жолды таңдау, екі рет шерту — осы жүрісте ашу",
],
[
"Open game",
"Открыть партию",
"Ouvrir la partie",
"Partie öffnen",
"Abrir partida",
"Apri partita",
"Abrir partida",
"Partiyani ochish",
"Партияны ашу",
],
];
#[cfg(test)]
@ -20089,6 +20698,8 @@ mod tests {
include_str!("opening_session.rs"),
include_str!("repertoire_ui.rs"),
include_str!("batch_copy.rs"),
include_str!("brilliant.rs"),
include_str!("brilliant_ui.rs"),
];
let mut chars = std::collections::BTreeSet::new();
for row in ROWS.iter() {

View file

@ -278,6 +278,20 @@ struct Suggestions {
highlighted: Option<usize>,
}
/// The search for great moves under way, as the conditions line shows it.
#[derive(Clone, Debug, PartialEq)]
pub struct PassStatus {
/// In this database (else in `name`).
pub here: bool,
pub name: String,
pub done: usize,
pub total: usize,
/// The record being analysed.
pub current: Option<u32>,
pub left_secs: f64,
pub stopping: bool,
}
/// A copy of chosen records being written, as the conditions line shows it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BatchStatus {
@ -338,6 +352,23 @@ pub struct LargeView {
marked_before: Option<Vec<(u32, u64)>>,
/// Said once (a toast), taken by the library.
pub notice: Option<String>,
/// The marks of the records found by the search for great moves (task 27), set by
/// the library; what the table shows of them, checked against each record's main
/// line, by record, for the index's generation.
pub marks: Option<Arc<std::sync::Mutex<crate::brilliant::Index>>>,
shown_marks: std::cell::RefCell<(u64, HashMap<u32, Option<crate::brilliant::Entry>>)>,
/// The table sorted by the «!!» column.
marks_sort: bool,
/// The search under way (here or in another database), set by the library.
pub pass: Option<PassStatus>,
/// Why the search cannot start now (the engine is busy), set by the app.
pub engine_busy: Option<String>,
/// Why the last search stopped with an error, in red where its progress was.
pub pass_error: Option<String>,
/// «Stop» of the search was clicked.
pub stop_pass: bool,
/// «!! Find great moves» was clicked (taken by `table`, which has the path).
find_clicked: bool,
scroll_to_selected: bool,
scroll_to_top: bool,
focus_player: bool,
@ -465,6 +496,14 @@ impl LargeView {
batch_error: None,
marked_before: None,
notice: None,
marks: None,
shown_marks: std::cell::RefCell::new((u64::MAX, HashMap::new())),
marks_sort: false,
pass: None,
engine_busy: None,
pass_error: None,
stop_pass: false,
find_clicked: false,
scroll_to_selected: false,
scroll_to_top: false,
focus_player: false,
@ -508,6 +547,7 @@ impl LargeView {
self.cache.clear();
self.blocked = None;
self.books = db.books();
self.shown_marks.borrow_mut().1.clear();
// Several chosen: kept only if each is still the same record (a game added at
// the end keeps them; one deleted or put back moves the numbers). Otherwise let
// go, and said: the choice never moves to other games unnoticed.
@ -631,6 +671,87 @@ impl LargeView {
self.selected = Some(index);
}
/// The table sorted by its «!!» column (the summary's «Sort»).
pub fn sort_marks_on(&mut self) {
self.marks_sort = true;
self.sort_by_marks();
}
/// The list by its marks (!! first), each group in the order of its numbers.
fn sort_by_marks(&mut self) {
let Some(index) = self.marks.clone() else {
return;
};
let Ok(index) = index.lock() else {
return;
};
self.view.sort_by_key(|&r| (index.rank(r), r));
self.view_gen += 1;
}
/// The marks of record `index` to show: those of the index if the record still has
/// the main line they were found in (checked once per record and index change).
fn shown_mark(
marks: &Option<Arc<std::sync::Mutex<crate::brilliant::Index>>>,
shown: &std::cell::RefCell<(u64, HashMap<u32, Option<crate::brilliant::Entry>>)>,
db: &Database,
record: u32,
) -> Option<crate::brilliant::Entry> {
let index = marks.as_ref()?.lock().ok()?;
let mut shown = shown.borrow_mut();
if index.generation != shown.0 {
shown.1.clear();
shown.0 = index.generation;
}
let entry = index.get(record)?.clone();
drop(index);
shown
.1
.entry(record)
.or_insert_with(|| {
let game = db.load_game(record as usize)?.game;
let line = game_review::GameAnalysis::new(&game, None).cache_key();
(entry.line == line).then_some(entry)
})
.clone()
}
/// «!! Find great moves» (the button, Shift+A): the library asks first.
fn ask_search(&mut self, path: &Path, actions: &mut Vec<LibraryAction>) {
actions.push(LibraryAction::FindGreatMoves {
path: path.to_path_buf(),
records: self.view.clone(),
filter: self.form.filter(),
});
}
/// Why the search cannot start on the list shown, if it cannot.
fn search_blocked(&self) -> Option<String> {
if let Some(why) = &self.engine_busy {
return Some(why.clone());
}
if let Some(p) = self.pass.as_ref().filter(|p| !p.here) {
return Some(trf(
"Searching in «{db}»: {i} of {n}; stop it there",
&[("db", &p.name), ("i", &p.done), ("n", &p.total)],
));
}
if self.job.is_some() || self.shown.is_none() {
return Some(tr("Wait: the games are still being filtered").to_owned());
}
match crate::brilliant::can_start(self.view.len()) {
Ok(()) => None,
Err(crate::brilliant::Blocked::NoGames) => {
Some(tr("No games match these conditions").to_owned())
}
Err(crate::brilliant::Blocked::TooMany) => Some(format!(
"{}\n{}",
tr("Filter the games down to 100 or fewer"),
trf("Now: {n}", &[("n", &grouped(self.view.len()))])
)),
}
}
/// Every row of the list chosen (Ctrl+A): the list's records only.
fn select_all(&mut self) {
let view = std::mem::take(&mut self.view);
@ -832,6 +953,9 @@ impl LargeView {
}
self.view = answer.view;
self.view_gen += 1;
if self.marks_sort {
self.sort_by_marks();
}
self.outcome = answer.outcome;
self.in_order = answer.in_order;
self.blocked = answer.blocked;
@ -1389,7 +1513,7 @@ impl LargeView {
// the slot of the far right, the move order, the choice or its copy, the
// conditions. The far right slot keeps one width whatever it shows, so what
// stands left of it does not move when it changes.
Self::right_slot(ui, RIGHT_SLOT_W);
self.right_slot(ui);
if let Some((same, all)) = self.in_order
&& self.board.is_set()
&& (same < all || self.only_order)
@ -1543,12 +1667,162 @@ impl LargeView {
}
}
/// The far right slot of the conditions line, `width` wide (none yet: task 27 puts
/// its search there).
fn right_slot(ui: &mut Ui, width: f32) {
if width > 0.0 {
ui.allocate_exact_size(vec2(width, 22.0), Sense::hover());
ui.add_space(SLOT_GAP);
/// The far right slot of the conditions line: «!! Find great moves», or the search
/// under way with «Stop», or why it stopped (task 27 §4.1–4.2). Its width is that of
/// its longest form for the line's width, whatever it shows: what stands left of it
/// never moves.
fn right_slot(&mut self, ui: &mut Ui) {
let line = ui.available_width();
let form = if line >= 1100.0 {
2
} else if line >= 800.0 {
1
} else {
0
};
let body = egui::TextStyle::Body.resolve(ui.style());
let width = |text: &str| {
ui.fonts_mut(|f| {
f.layout_no_wrap(text.to_owned(), body.clone(), Color32::WHITE)
.size()
.x
})
};
let progress_text = |i: usize, n: usize, left: &str| match form {
2 => format!(
"!! {}",
trf(
"Analysed {i} of {n} · ≈ {time} left",
&[("i", &i), ("n", &n), ("time", &left)]
)
),
1 => format!(
"!! {} · ≈ {left}",
trf("{i} of {n}", &[("i", &i), ("n", &n)])
),
_ => format!("!! {}", trf("{i} of {n}", &[("i", &i), ("n", &n)])),
};
let bar = if form == 2 { 90.0 } else { 60.0 };
let pad = 2.0 * ui.spacing().button_padding.x;
let gap = ui.spacing().item_spacing.x;
let button_text = if form == 0 {
tr("!! Find moves")
} else {
tr("!! Find great moves")
};
let longest = width(&progress_text(
100,
100,
&crate::review::format_duration(59.0 * 60.0),
)) + gap
+ bar
+ gap
+ width(tr("Stop"))
+ pad;
let slot = longest.max(width(button_text) + pad);
let pass = self.pass.clone();
let blocked = self.search_blocked();
let error = self.pass_error.clone();
let mut find = false;
let mut stop = false;
let mut close_error = false;
ui.allocate_ui_with_layout(
vec2(slot, 22.0),
egui::Layout::right_to_left(egui::Align::Center),
|ui| {
ui.set_min_width(slot);
match (&pass, &error) {
(Some(p), _) => {
if p.stopping {
ui.spinner();
ui.label(RichText::new(tr("Stopping…")).weak());
} else {
if ui
.small_button(tr("Stop"))
.on_hover_text(tr("Stop the search; the reviewed games are kept"))
.clicked()
{
stop = true;
}
ui.add(
egui::ProgressBar::new(p.done as f32 / p.total.max(1) as f32)
.desired_width(bar)
.desired_height(8.0),
);
let left = crate::review::format_duration(p.left_secs);
let text = if p.here {
progress_text(p.done, p.total, &left)
} else {
format!(
"!! {}",
trf(
"In «{db}»: {i} of {n}",
&[("db", &p.name), ("i", &p.done), ("n", &p.total)]
)
)
};
ui.add(egui::Label::new(RichText::new(text).weak()).truncate())
.on_hover_text(trf(
"Analysed {i} of {n} · ≈ {time} left",
&[("i", &p.done), ("n", &p.total), ("time", &left)],
));
}
}
(None, Some(e)) => {
if crate::widgets::small_close_button(ui).clicked() {
close_error = true;
}
ui.add(
egui::Label::new(RichText::new(e).color(ui.visuals().error_fg_color))
.truncate(),
)
.on_hover_text(e);
}
(None, None) => {
let teal = crate::notation::assessment_text_color(
chess_core::Nag(3),
ui.visuals().dark_mode,
)
.unwrap_or(Color32::WHITE);
let mut job = egui::text::LayoutJob::default();
let rest = button_text.strip_prefix("!! ").unwrap_or(button_text);
let bold = egui::FontId::new(13.0, egui::FontFamily::Name("bold".into()));
let bold = if ui.fonts_mut(|f| f.families().contains(&bold.family)) {
bold
} else {
body.clone()
};
job.append("!! ", 0.0, egui::TextFormat::simple(bold, teal));
job.append(
rest,
0.0,
egui::TextFormat::simple(body.clone(), ui.visuals().text_color()),
);
let enabled = blocked.is_none();
let r = ui.add_enabled(enabled, egui::Button::new(job).small());
let r = match &blocked {
Some(why) => r.on_disabled_hover_text(why),
None => r.on_hover_text(trf(
"Review {games} with the engine and mark the !! and ! moves found (Shift+A)",
&[("games", &crate::i18n::games(self.view.len()))],
)),
};
if r.clicked() {
find = true;
}
}
}
},
);
ui.add_space(SLOT_GAP);
if find {
self.find_clicked = true;
}
if stop {
self.stop_pass = true;
}
if close_error {
self.pass_error = None;
}
}
@ -2339,6 +2613,41 @@ impl LargeView {
return open_notes;
}
// «!! Find great moves»: the button, or Shift+A outside a field (a disabled button
// says why).
let typing = ui.ctx().egui_wants_keyboard_input();
let shift_a = !typing
&& !crate::app::overlay_open_besides(ui.ctx(), &[egui::Id::new("filters_drawer")])
&& ui.input_mut(|i| i.consume_key(egui::Modifiers::SHIFT, egui::Key::A));
if std::mem::take(&mut self.find_clicked) || shift_a {
match (self.pass.is_some(), self.search_blocked()) {
(false, None) => self.ask_search(path, actions),
(false, Some(why)) => actions.push(LibraryAction::Notice(why)),
(true, _) => {}
}
}
// `CP_MARKS_DEMO=1`: made-up marks for the first rows (screenshots of the column).
if std::env::var_os("CP_MARKS_DEMO").is_some()
&& self.shown.is_some()
&& self.job.is_none()
&& let Some(marks) = self.marks.clone()
{
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| demo_marks(db, &self.view, &marks));
}
// `CP_BRILLIANT_RUN=1`: the search asked for once the list is there.
if std::env::var_os("CP_BRILLIANT_RUN").is_some()
&& self.shown.is_some()
&& self.job.is_none()
&& self.search_blocked().is_none()
{
static ONCE: std::sync::Once = std::sync::Once::new();
let mut first = false;
ONCE.call_once(|| first = true);
if first {
self.ask_search(path, actions);
}
}
// Records the database does not have (`CP_SELECT` on a short one) are not chosen.
if self.marked.last().is_some_and(|r| r >= db.len()) {
let len = db.len();
@ -2398,6 +2707,8 @@ impl LargeView {
(tr("Black"), Some(SortKey::Black), name),
("Elo", Some(SortKey::BlackElo), Column::exact(ELO_COL)),
(tr("Res."), Some(SortKey::Result), Column::exact(RESULT_COL)),
// The marks of the search for great moves: in every layout (task 27 §4.3).
("!!", None, Column::exact(MARKS_COL)),
]);
if show_moves {
columns.push((tr("Length"), Some(SortKey::Moves), Column::exact(56.0)));
@ -2459,6 +2770,14 @@ impl LargeView {
let mut opened = None;
let mut toggle_viewed = None;
let mut hovered = None;
let marks_sorted = self.marks_sort;
let mut marks_click = false;
let pass_current = self
.pass
.as_ref()
.filter(|p| p.here)
.and_then(|p| p.current);
let (marks_ref, shown_ref) = (&self.marks, &self.shown_marks);
let view = &self.view;
let selected = self.selected;
let marked = &self.marked;
@ -2490,7 +2809,15 @@ impl LargeView {
.header(26.0, |mut header| {
for (label, key, _) in &columns {
header.col(|ui| {
let active = key.filter(|k| sort.0 == *k).map(|_| sort.1);
if *label == "!!" {
let r = crate::widgets::sort_header(ui, label, marks_sorted.then_some(true))
.on_hover_text(tr("Brilliant and great moves found by the engine: sort by them"));
if r.clicked() {
marks_click = true;
}
return;
}
let active = key.filter(|k| sort.0 == *k && !marks_sorted).map(|_| sort.1);
let r = crate::widgets::sort_header(ui, label, active);
if let Some(k) = key
&& r.clicked()
@ -2559,6 +2886,10 @@ impl LargeView {
(_, Some(SortKey::Black)) => RichText::new(r.black.as_str()),
(_, Some(SortKey::BlackElo)) => RichText::new(elo(r.black_elo)),
(_, Some(SortKey::Result)) => RichText::new(result),
("!!", None) => {
marks_cell(ui, Self::shown_mark(marks_ref, shown_ref, db, index as u32), pass_current == Some(index as u32), is_marked);
return;
}
(_, Some(SortKey::Moves)) => RichText::new(match r.moves {
0 => String::new(),
255 => "255+".into(),
@ -2625,6 +2956,27 @@ impl LargeView {
opened = Some(index);
ui.close();
}
// The first !! (else !) the search found: the game at it.
if let Some(f) = Self::shown_mark(marks_ref, shown_ref, db, index as u32)
.and_then(|e| {
let first = e.found.iter().find(|f| f.brilliant).or(e.found.first());
first.cloned()
})
&& ui
.button(trf("Open at {move}", &[("move", &f.label())]))
.clicked()
{
let at = db.load_game(index).and_then(|p| {
let node = *p.game.mainline().get(f.ply as usize)?;
Some(p.game.node(node)?.position().clone())
});
actions.push(LibraryAction::OpenGame {
path: path.to_path_buf(),
index,
at,
});
ui.close();
}
// The game's page, when its tags have one (read once per menu).
if self.menu_link.as_ref().is_none_or(|(i, _)| *i != index) {
let link = db.load_game(index).and_then(|p| {
@ -2707,7 +3059,17 @@ impl LargeView {
if let Some((k, v)) = toggle_viewed {
viewed.set(k, v);
}
if marks_click {
self.marks_sort = !self.marks_sort;
if self.marks_sort {
self.sort_by_marks();
} else {
// The list comes again in the sort of its columns.
self.shown = None;
}
}
if let Some(k) = sort_click {
self.marks_sort = false;
let current = self.effective_sort();
self.sort = if current.0 == k {
(k, !current.1)
@ -2897,11 +3259,10 @@ fn record_hash(db: &Database, index: usize) -> u64 {
h.finish()
}
/// The width of the far right slot of the conditions line (task 27 sets it; until
/// then nothing is there).
const RIGHT_SLOT_W: f32 = 0.0;
/// Space between the slots of the conditions line (`item_spacing.x` + 4).
const SLOT_GAP: f32 = 4.0;
/// The «!!» column.
const MARKS_COL: f32 = 28.0;
/// An item of the menus about the chosen records.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@ -2941,6 +3302,164 @@ fn batch_items(ui: &mut Ui, n: usize, writing: Option<&str>) -> Option<BatchItem
out
}
/// Made-up marks for the first rows of `view` (`CP_MARKS_DEMO`): !!, !, none, not
/// analysable, in turn; not saved.
fn demo_marks(db: &Database, view: &[u32], marks: &std::sync::Mutex<crate::brilliant::Index>) {
use crate::brilliant::{Counts, Entry, Found, SideMarks, Skip};
let Ok(mut index) = marks.lock() else {
return;
};
for (n, &r) in view.iter().take(8).enumerate() {
let Some(game) = db.load_game(r as usize).map(|p| p.game) else {
continue;
};
let line = game_review::GameAnalysis::new(&game, None).cache_key();
let side = |brilliant, great| SideMarks {
counts: Counts {
brilliant,
great,
..Counts::default()
},
acpl: Some(30),
accuracy: Some(85.0),
};
let found = |brilliant| Found {
ply: 20,
white: true,
number: 11,
san: "Rxf7".into(),
brilliant,
};
let entry = match n % 4 {
0 => Entry {
line,
white: side(1, 0),
black: side(0, 0),
found: vec![found(true)],
stale: false,
skip: None,
},
1 => Entry {
line,
white: side(0, 2),
black: side(0, 0),
found: vec![found(false)],
stale: true,
skip: None,
},
2 => Entry {
line,
white: side(0, 0),
black: side(0, 0),
found: Vec::new(),
stale: false,
skip: None,
},
_ => Entry {
line,
white: SideMarks::default(),
black: SideMarks::default(),
found: Vec::new(),
stale: false,
skip: Some(Skip::NullMove),
},
};
index.set(r, entry);
}
}
/// The «!!» cell of a record (task 27 §4.3): !!, !, «·» analysed without them, «—» not
/// analysable, a spinner while analysed, nothing when not analysed. Signs, not colours
/// alone; on a chosen row in the text colour of the selection.
fn marks_cell(ui: &mut Ui, entry: Option<crate::brilliant::Entry>, running: bool, chosen: bool) {
ui.with_layout(
egui::Layout::centered_and_justified(egui::Direction::LeftToRight),
|ui| {
if running {
ui.add(egui::Spinner::new().size(12.0))
.on_hover_text(tr("Being reviewed…"));
return;
}
let Some(e) = entry else {
return;
};
let dark = ui.visuals().dark_mode;
let tint = |nag: u8| {
if chosen {
ui.visuals().selection.stroke.color
} else {
crate::notation::assessment_text_color(chess_core::Nag(nag), dark)
.unwrap_or(ui.visuals().text_color())
}
};
let moves = |brilliant: bool| {
let list: Vec<String> = e
.found
.iter()
.filter(|f| f.brilliant == brilliant)
.map(|f| f.label())
.collect();
let shown = list.iter().take(3).cloned().collect::<Vec<_>>().join(", ");
if list.len() > 3 {
format!(
"{shown} {}",
trf("and {n} more", &[("n", &(list.len() - 3))])
)
} else {
shown
}
};
let c = e.of_sides(true, true);
let (text, color, mut hint) = if let Some(skip) = e.skip {
(
"—",
ui.visuals().weak_text_color(),
trf(
"Cannot be reviewed: {reason}",
&[("reason", &skip.reason())],
),
)
} else if c.brilliant > 0 || c.great > 0 {
let mut hint = Vec::new();
if c.brilliant > 0 {
hint.push(trf(
"Brilliant moves: {n}: {moves}",
&[("n", &c.brilliant), ("moves", &moves(true))],
));
}
if c.great > 0 {
hint.push(trf(
"Great moves: {n}: {moves}",
&[("n", &c.great), ("moves", &moves(false))],
));
}
if c.brilliant > 0 {
("!!", tint(3), hint.join("\n"))
} else {
("!", tint(1), hint.join("\n"))
}
} else {
(
"·",
ui.visuals().weak_text_color(),
tr("Reviewed: no brilliant or great moves").to_owned(),
)
};
if e.stale {
hint.push('\n');
hint.push_str(tr("Reviewed with the previous engine settings"));
}
let color = if chosen {
ui.visuals().selection.stroke.color
} else {
color
};
ui.add(egui::Label::new(RichText::new(text).strong().color(color)).selectable(false))
.on_hover_text(hint);
},
);
}
/// The keyboard cursor's frame: 1 px inside the row.
fn ui_painter_frame(row: &egui::Response, rect: egui::Rect, color: Color32, clip: egui::Rect) {
let stroke = Stroke::new(1.0, color);

View file

@ -18,6 +18,8 @@ mod assets;
mod batch_copy;
mod board;
mod board_search;
mod brilliant;
mod brilliant_ui;
mod chatgpt;
mod db_counts;
mod engine_download;

View file

@ -94,6 +94,13 @@ pub enum LibraryAction {
},
/// A short message (a toast).
Notice(String),
/// «!! Find great moves» over the list `records` of `path` (in the table's order),
/// found by `filter` (task 27).
FindGreatMoves {
path: PathBuf,
records: Vec<u32>,
filter: chess_import::chessbase::base::Filter,
},
EditGameData {
path: PathBuf,
index: usize,
@ -279,6 +286,10 @@ pub struct Library {
counts: crate::db_counts::Counts,
/// Chosen records being copied into a new database (one copy at a time).
batch: Option<BatchJob>,
/// The marks of great moves of each database (task 27), read once per session.
marks: HashMap<PathBuf, Arc<Mutex<crate::brilliant::Index>>>,
/// The search for great moves under way (one engine job in the program).
pub pass: Option<crate::brilliant::PassJob>,
}
/// A copy of chosen records into a new database, written in the background.
@ -327,6 +338,68 @@ impl Library {
aside: None,
counts: crate::db_counts::Counts::new(ctx),
batch: None,
marks: HashMap::new(),
pass: None,
}
}
/// The marks of great moves of the database at `path`.
pub fn marks(&mut self, path: &Path) -> Arc<Mutex<crate::brilliant::Index>> {
self.marks
.entry(path.to_path_buf())
.or_insert_with(|| Arc::new(Mutex::new(crate::brilliant::Index::of(path))))
.clone()
}
/// The search under way, as each database's conditions line shows it; «Stop» of
/// any of them stops it. Called every frame.
pub fn show_pass(&mut self, estimate: impl Fn(&[u32]) -> f64) {
let status = self.pass.as_ref().map(|job| {
(
job.source.clone(),
crate::own_db::base_name(&job.source),
job.done(),
job.records.len(),
job.current(),
job.left_secs(&estimate),
job.stopping,
)
});
let mut stop = false;
for (path, view) in self.large.iter_mut() {
view.pass =
status
.as_ref()
.map(|(source, name, done, total, current, left, stopping)| {
large_db::PassStatus {
here: source == path,
name: name.clone(),
done: *done,
total: *total,
current: *current,
left_secs: *left,
stopping: *stopping,
}
});
stop |= std::mem::take(&mut view.stop_pass);
}
if stop && let Some(job) = self.pass.as_mut() {
job.stop();
}
}
/// Why the search may not start now (the engine is busy elsewhere), for every
/// database's button.
pub fn set_engine_busy(&mut self, why: Option<String>) {
for view in self.large.values_mut() {
view.engine_busy = why.clone();
}
}
/// Why the last search in `path` stopped with an error, where its progress was.
pub fn set_pass_error(&mut self, path: &Path, text: Option<String>) {
if let Some(view) = self.large.get_mut(path) {
view.pass_error = text;
}
}
@ -516,6 +589,21 @@ impl Library {
}
}
/// Chooses the row of `index` alone (any choice of several let go) and scrolls to it.
pub fn choose_only(&mut self, path: &Path, index: usize) {
if let Some(view) = self.large.get_mut(path) {
view.clear_marks();
view.reveal(index);
}
}
/// Sorts the table of `path` by its «!!» column.
pub fn sort_by_marks(&mut self, path: &Path) {
if let Some(view) = self.large.get_mut(path) {
view.sort_marks_on();
}
}
/// Selects (and scrolls to) a game row, e.g. when returning from a game.
pub fn reveal(&mut self, path: &Path, index: usize) {
if let Some(view) = self.large.get_mut(path) {
@ -1625,6 +1713,14 @@ impl Library {
.entry(path.clone())
.or_insert_with(|| LargeView::for_database(&db, online));
let notes = self.info.get(&path).map_or(0, |i| i.notes.len());
if view.marks.is_none() {
let marks = self
.marks
.entry(path.clone())
.or_insert_with(|| Arc::new(Mutex::new(crate::brilliant::Index::of(&path))))
.clone();
view.marks = Some(marks);
}
if view.table(
ui,
&path,

View file

@ -1301,6 +1301,9 @@ fn cache_dir() -> Option<PathBuf> {
pub struct PrepScreen {
/// This screen's own number (`engine_offer::next_serial`).
pub serial: u64,
/// The engine is taken by another job (the search for great moves, task 27): the
/// search for opening errors does not start, and says why.
pub engine_blocked: Option<String>,
pub path: PathBuf,
db: Arc<Database>,
db_name: String,
@ -1676,6 +1679,7 @@ impl PrepScreen {
});
let mut screen = PrepScreen {
serial: crate::engine_offer::next_serial(),
engine_blocked: None,
db_name: base_name(&start.path),
path: start.path,
db,
@ -2186,6 +2190,10 @@ impl PrepScreen {
if self.job.is_some() {
return;
}
if let Some(why) = &self.engine_blocked {
self.error = Some(why.clone());
return;
}
self.error = None;
// A start by hand (or by the new report) clears the manual Stop of this one.
if let Some(report) = self.report.as_mut()