desktop: analyse manually selected games in batches

This commit is contained in:
vrubelroman 2026-11-28 00:27:41 +03:00
parent 1782569e1c
commit 064e929d2c
17 changed files with 1852 additions and 78 deletions

View file

@ -2002,6 +2002,7 @@ impl App {
records: Vec<u32>,
filter: chess_import::chessbase::base::Filter,
about: String,
selected: Option<crate::brilliant::SelectedGames>,
) {
if self.library.pass.is_some() {
return;
@ -2016,7 +2017,7 @@ impl App {
};
let index = self.library.marks(&path);
let mut dialog = crate::brilliant_ui::StartDialog::new(
ctx, path, db, records, filter, about, cache, index,
ctx, path, db, records, filter, about, selected, cache, index,
);
// `CP_BRILLIANT_RUN=1`: no question.
if std::env::var_os("CP_BRILLIANT_RUN").is_some() {
@ -2112,6 +2113,7 @@ impl App {
db,
list,
dialog.filter.clone(),
dialog.selected,
index,
cache,
engine,
@ -2119,8 +2121,12 @@ impl App {
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));
self.brilliant_pass = Some((
dialog.filter.clone(),
dialog.about.clone(),
dialog.selected,
counted.skipped,
));
}
Err(e) => self.toast(ctx, e.to_string()),
}
@ -2135,6 +2141,7 @@ impl App {
sides: &crate::brilliant::Sides,
filter: &chess_import::chessbase::base::Filter,
about: String,
selected: Option<crate::brilliant::SelectedGames>,
stopped: Option<(usize, usize)>,
skipped: Vec<(u32, crate::brilliant::Skip)>,
) {
@ -2146,7 +2153,7 @@ impl App {
return;
};
self.brilliant_summary = Some(crate::brilliant_ui::Summary::new(
source, &db, &index, records, sides, filter, about, stopped, skipped,
source, &db, &index, records, sides, filter, about, selected, stopped, skipped,
));
}
@ -2181,7 +2188,8 @@ impl App {
&& 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();
let (filter, about, selected, mut skipped) =
self.brilliant_pass.take().unwrap_or_default();
skipped.extend(end.skipped.iter().copied());
skipped.sort_unstable_by_key(|(r, _)| *r);
skipped.dedup();
@ -2194,6 +2202,7 @@ impl App {
&sides,
&filter,
about,
selected,
None,
skipped,
),
@ -2206,6 +2215,7 @@ impl App {
&sides,
&filter,
about,
selected,
Some((reviewed, total)),
skipped,
),
@ -2245,6 +2255,7 @@ impl App {
&c.sides,
&dialog.filter,
dialog.about.clone(),
dialog.selected,
None,
c.skipped.clone(),
);
@ -2258,6 +2269,7 @@ impl App {
{
let source = summary.source.clone();
let summary_about = summary.about.clone();
let summary_selected = summary.selected_games;
use crate::brilliant_ui::SummaryAction;
match action {
SummaryAction::Close => self.brilliant_summary = None,
@ -2268,7 +2280,7 @@ impl App {
SummaryAction::Continue { records, filter } => {
self.brilliant_summary = None;
let about = summary_about.clone();
self.ask_great_moves(ctx, source, records, *filter, about);
self.ask_great_moves(ctx, source, records, *filter, about, summary_selected);
}
SummaryAction::Open { record, ply } => {
self.brilliant_summary = None;
@ -4818,7 +4830,8 @@ impl eframe::App for App {
records,
filter,
about,
} => self.ask_great_moves(&ctx, path, records, filter, about),
selected,
} => self.ask_great_moves(&ctx, path, records, filter, about, selected),
LibraryAction::EditGameData { path, index } => {
self.open_game(&ctx, path, index, None);
self.edit_game_data();

View file

@ -1,5 +1,5 @@
//! The search for brilliant and great moves (!!, !) in the games of a filtered list
//! (task 27, docs/design/task-27-brilliant-search-2026-11-27.md): a background pass of
//! or a manual selection (tasks 27 and 42): a background pass of
//! the game analysis's engine over at most [`LIMIT`] games, the index of what each
//! analysed record holds (kept beside the analysis cache, one file per database), and
//! the totals of a pass by category. Games already analysed come from the analysis
@ -35,6 +35,14 @@ pub fn can_start(n: usize) -> Result<(), Blocked> {
}
}
/// The manual source of a pass: its size before cached or unsupported games are taken
/// out, and how many of those records the current filter hid when the request was made.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SelectedGames {
pub games: usize,
pub hidden: usize,
}
/// Engine judgements of one side of a game.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Counts {
@ -667,8 +675,9 @@ pub fn totals(index: &Index, db: &Database, records: &[u32], sides: &Sides) -> T
t
}
/// The records of `view` (a pass's list) where the filter's player has White and Black:
/// the same filter with the side fixed, for `Sides`.
/// The records where the filter's player has White and Black: the player condition
/// with the side fixed, without the other conditions. A selected game hidden by those
/// other conditions still keeps its player's side; a game of another player has neither.
pub fn player_sides(
db: &Database,
filter: &chess_import::chessbase::base::Filter,
@ -678,10 +687,15 @@ pub fn player_sides(
if !filter.player.is_set() {
return Sides::default();
}
let player = chess_import::chessbase::base::Filter {
player: filter.player.clone(),
side: filter.side,
..Default::default()
};
let side = |s: Side| {
let f = chess_import::chessbase::base::Filter {
side: s,
..filter.clone()
..player.clone()
};
let mut v = db
.query(&f, SortKey::Number, true, &AtomicUsize::new(0), cancel)
@ -700,10 +714,11 @@ pub fn player_sides(
}
/// What the app keeps of a pass for its summary: the filter, the words for its
/// conditions, and the games that could not be analysed.
/// conditions (or the manual source), and the games that could not be analysed.
pub type PassMeta = (
chess_import::chessbase::base::Filter,
String,
Option<SelectedGames>,
Vec<(u32, Skip)>,
);
@ -712,6 +727,7 @@ pub type PassMeta = (
pub struct PassJob {
pub source: PathBuf,
pub records: Vec<u32>,
pub selected: Option<SelectedGames>,
progress: std::sync::Arc<Progress>,
cancel: std::sync::Arc<AtomicBool>,
rx: std::sync::mpsc::Receiver<(PassEnd, Sides)>,
@ -729,6 +745,7 @@ impl PassJob {
db: std::sync::Arc<Database>,
records: Vec<u32>,
filter: chess_import::chessbase::base::Filter,
selected: Option<SelectedGames>,
index: std::sync::Arc<Mutex<Index>>,
cache: PathBuf,
engine: Engine,
@ -754,6 +771,7 @@ impl PassJob {
Ok(PassJob {
source,
records,
selected,
progress,
cancel,
rx,

View file

@ -360,6 +360,49 @@ fn the_players_sides_come_from_the_filter() {
.player
.is_none()
);
let quick_search = chess_import::chessbase::base::Filter {
text: "carlsen".into(),
..Default::default()
};
assert!(
player_sides(&db, &quick_search, &AtomicBool::new(false))
.player
.is_none()
);
}
#[test]
fn a_selected_game_hidden_by_another_condition_keeps_its_players_side() {
let dir = Dir::new("hidden-sides");
let (_, db) = source(&dir);
let filter = chess_import::chessbase::base::Filter {
player: chess_import::chessbase::base::NameFilter {
text: "carlsen".into(),
exact: None,
},
// None of the sample games has a year, so the filtered table is empty. The
// manually selected Carlsen games nevertheless retain White and Black.
year_from: Some(2020),
..Default::default()
};
let sides = player_sides(&db, &filter, &AtomicBool::new(false));
assert_eq!(sides.player, Some((vec![0], vec![1])));
assert_eq!(sides.of(0), (true, false));
assert_eq!(sides.of(1), (false, true));
assert_eq!(sides.of(2), (false, false));
let mut white = filter.clone();
white.side = chess_import::chessbase::base::Side::White;
assert_eq!(
player_sides(&db, &white, &AtomicBool::new(false)).player,
Some((vec![0], Vec::new()))
);
let mut black = filter;
black.side = chess_import::chessbase::base::Side::Black;
assert_eq!(
player_sides(&db, &black, &AtomicBool::new(false)).player,
Some((Vec::new(), vec![1]))
);
}
/// White found a !! and Black a !: the row of a filter on the Black player shows !.
@ -411,7 +454,7 @@ fn the_column_counts_only_the_filters_players_moves() {
}
#[test]
fn the_summary_keeps_the_player_for_continue() {
fn the_summary_keeps_the_original_snapshot_and_player_for_continue() {
let dir = Dir::new("summary");
let (path, db) = source(&dir);
let filter = chess_import::chessbase::base::Filter {
@ -424,20 +467,31 @@ fn the_summary_keeps_the_player_for_continue() {
let sides = player_sides(&db, &filter, &AtomicBool::new(false));
let mut index = two_sided();
fit(&mut index, &db);
let mut original = vec![0, 1, 2];
let selected = Some(SelectedGames {
games: 3,
hidden: 1,
});
// Record 0: Carlsen has White (its !!); record 1: Carlsen has Black (a !).
let summary = crate::brilliant_ui::Summary::new(
&path,
&db,
&index,
&[0, 1, 2],
&original,
&sides,
&filter,
String::new(),
selected,
Some((2, 3)),
Vec::new(),
);
// A later live selection has new records: neither the new record nor the changed
// order can enter the continuation held by this summary.
original.clear();
original.push(3);
assert_eq!(summary.filter, filter);
assert_eq!(summary.rest, vec![2]);
assert_eq!(summary.selected_games, selected);
assert_eq!(
(summary.totals.counts.brilliant, summary.totals.counts.great),
(1, 1)

View file

@ -12,7 +12,7 @@ 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::brilliant::{Found, Index, SelectedGames, Sides, Skip, Totals};
use crate::i18n::{tr, trf};
/// What a list holds before a pass: the records already analysed, those to analyse with
@ -90,6 +90,7 @@ pub struct StartDialog {
pub records: Vec<u32>,
pub filter: Filter,
pub about: String,
pub selected: Option<SelectedGames>,
rx: Receiver<Counted>,
cancel: Arc<AtomicBool>,
pub counted: Option<Counted>,
@ -102,6 +103,19 @@ pub enum StartOutcome {
Cancel,
}
/// One of the three fixed-height source rows: empty rows keep their place.
fn source_line(ui: &mut egui::Ui, text: &str, weak: bool, hover: Option<&str>) {
if text.is_empty() {
return;
}
let text = RichText::new(text).size(12.0);
let text = if weak { text.weak() } else { text };
let response = ui.add(egui::Label::new(text).truncate());
if let Some(hover) = hover {
response.on_hover_text(hover);
}
}
impl StartDialog {
#[allow(clippy::too_many_arguments)]
pub fn new(
@ -111,6 +125,7 @@ impl StartDialog {
records: Vec<u32>,
filter: Filter,
about: String,
selected: Option<SelectedGames>,
cache: PathBuf,
index: Arc<std::sync::Mutex<Index>>,
) -> StartDialog {
@ -128,6 +143,7 @@ impl StartDialog {
records,
filter,
about,
selected,
rx,
cancel,
counted: None,
@ -155,13 +171,59 @@ impl StartDialog {
.default_width(520.0)
.show(ctx, |ui| {
ui.set_width(520.0);
let about = format!(
"{name} · {} · {}",
crate::i18n::games(self.records.len()),
self.about
);
ui.add(egui::Label::new(RichText::new(&about).weak().size(12.0)).truncate())
.on_hover_text(&about);
let (source, hidden) = match self.selected {
Some(selected) => (
trf(
"Selected: {games}",
&[("games", &crate::i18n::games(selected.games))],
),
(selected.hidden > 0).then(|| {
trf(
"{k} hidden by the current filter",
&[("k", &crate::large_db::grouped(selected.hidden))],
)
}),
),
None => (
format!(
"{} · {}",
crate::i18n::games(self.records.len()),
self.about
),
None,
),
};
let player = (self.selected.is_some() && self.filter.player.is_set()).then(|| {
let name = self.filter.player.text.trim();
match self.filter.side {
chess_import::chessbase::base::Side::White => trf(
"Only the moves of «{name}» as White count.",
&[("name", &name)],
),
chess_import::chessbase::base::Side::Black => trf(
"Only the moves of «{name}» as Black count.",
&[("name", &name)],
),
_ => trf("Only the moves of «{name}» count.", &[("name", &name)]),
}
});
for (text, weak, hover) in [
(format!("{name} · {source}"), true, None),
(hidden.unwrap_or_default(), true, None),
(
player.unwrap_or_default(),
false,
self.filter.player.is_set().then(|| {
tr(
"The player condition limits the moves counted, but does not exclude selected games from review.",
)
}),
),
] {
ui.allocate_ui(egui::vec2(520.0, 18.0), |ui| {
source_line(ui, &text, weak, hover);
});
}
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, 60.0), |ui| match &self.counted {
@ -263,6 +325,7 @@ pub struct BrilliantRow {
pub struct Summary {
pub source: PathBuf,
pub about: String,
pub selected_games: Option<SelectedGames>,
pub totals: Totals,
/// The filter's player and the games counted for each colour.
pub player: Option<(String, usize, usize)>,
@ -305,6 +368,7 @@ impl Summary {
sides: &Sides,
filter: &Filter,
about: String,
selected: Option<SelectedGames>,
stopped: Option<(usize, usize)>,
skipped: Vec<(u32, Skip)>,
) -> Summary {
@ -347,6 +411,7 @@ impl Summary {
Summary {
source: source.to_path_buf(),
about,
selected_games: selected,
totals,
player,
stopped,
@ -414,12 +479,27 @@ impl Summary {
.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());
ui.add(egui::Label::new(RichText::new(text).weak().size(12.0)).truncate())
};
weak(
let about = match self.selected_games {
Some(selected) => trf(
"Selected: {games}",
&[("games", &crate::i18n::games(selected.games))],
),
None => self.about.clone(),
};
let subtitle = weak(
ui,
format!("{} · {}", crate::own_db::base_name(&self.source), self.about),
format!("{} · {about}", crate::own_db::base_name(&self.source)),
);
if let Some(selected) = self.selected_games
&& selected.hidden > 0
{
subtitle.on_hover_text(trf(
"Hidden by the filter at start: {k}",
&[("k", &crate::large_db::grouped(selected.hidden))],
));
}
if let Some((name, w, b)) = &self.player {
weak(
ui,

View file

@ -20767,6 +20767,182 @@ const ROWS: &[[&str; 9]] = &[
"{k} tasini tahlil qilib bo‘lmaydi ({reason})",
"{k} талдауға болмайды ({reason})",
],
[
"Wait: counting how many selected games are hidden by the current filter",
"Подождите — считаю, сколько выделенных партий скрыто текущим фильтром",
"Patientez : comptage des parties sélectionnées masquées par le filtre actuel",
"Bitte warten: ausgewählte, vom aktuellen Filter verborgene Partien werden gezählt",
"Espere: contando las partidas seleccionadas ocultas por el filtro actual",
"Attendi: conteggio delle partite selezionate nascoste dal filtro attuale",
"Aguarde: contando as partidas selecionadas ocultas pelo filtro atual",
"Kuting — joriy filtr yashirgan tanlangan partiyalar soni hisoblanmoqda",
"Күтіңіз — ағымдағы сүзгі жасырған таңдалған партиялар саны есептелуде",
],
[
"Selected: {games}. Review them with the engine and mark !! and ! (Shift+A)",
"Выбрано: {games}. Разобрать их движком и отметить !! и ! (Shift+A)",
"Sélection : {games}. Analysez-les avec le moteur et marquez les !! et ! (Maj+A)",
"Ausgewählt: {games}. Mit der Engine analysieren und !! und ! markieren (Umschalt+A)",
"Seleccionadas: {games}. Analízalas con el motor y marca !! y ! (Mayús+A)",
"Selezionate: {games}. Analizzale con il motore e segna !! e ! (Maiusc+A)",
"Selecionadas: {games}. Analise-as com o motor e marque !! e ! (Shift+A)",
"Tanlangan: {games}. Ularni dvigatel bilan tahlil qilib, !! va ! ni belgilang (Shift+A)",
"Таңдалды: {games}. Оларды қозғалтқышпен талдап, !! және ! белгілеңіз (Shift+A)",
],
[
"{k} hidden by the current filter; these games are included too.",
"Скрыто текущим фильтром: {k}; эти партии тоже входят.",
"{k} masquées par le filtre actuel ; ces parties sont incluses aussi.",
"{k} vom aktuellen Filter verborgen; diese Partien sind ebenfalls enthalten.",
"{k} ocultas por el filtro actual; estas partidas también se incluyen.",
"{k} nascoste dal filtro attuale; anche queste partite sono incluse.",
"{k} ocultas pelo filtro atual; estas partidas também estão incluídas.",
"Joriy filtr {k} tasini yashirdi; bu partiyalar ham kiradi.",
"Ағымдағы сүзгі {k} партияны жасырды; олар да кіреді.",
],
[
"The filter does not change this run's games.",
"Фильтр не меняет состав этого запуска.",
"Le filtre ne change pas les parties de ce lancement.",
"Der Filter ändert die Partien dieses Laufs nicht.",
"El filtro no cambia las partidas de este análisis.",
"Il filtro non cambia le partite di questa analisi.",
"O filtro não altera as partidas desta análise.",
"Filtr bu ishga tushirishdagi partiyalarni o‘zgartirmaydi.",
"Сүзгі бұл іске қосудғы партияларды өзгертпейді.",
],
[
"Selected: {games} — more than 100.",
"Выбрано: {games} — больше 100.",
"Sélection : {games} — plus de 100.",
"Ausgewählt: {games} — mehr als 100.",
"Seleccionadas: {games} — más de 100.",
"Selezionate: {games} — più di 100.",
"Selecionadas: {games} — mais de 100.",
"Tanlangan: {games} — 100 tadan ko‘p.",
"Таңдалды: {games} — 100-ден астам.",
],
[
"Keep no more than 100 selected; the filter is not used.",
"Оставьте не больше 100 выделенных; фильтр не используется.",
"Gardez au plus 100 parties sélectionnées ; le filtre n’est pas utilisé.",
"Behalten Sie höchstens 100 ausgewählte Partien; der Filter wird nicht verwendet.",
"Deje no más de 100 seleccionadas; el filtro no se usa.",
"Mantieni non più di 100 selezionate; il filtro non viene usato.",
"Mantenha no máximo 100 selecionadas; o filtro não é usado.",
"100 tadan oshiq tanlangan partiya qoldirmang; filtr ishlatilmaydi.",
"100-ден артық таңдалған партия қалдырмаңыз; сүзгі қолданылмайды.",
],
[
"Source: selected {games}; hidden by the filter at start: {k}.",
"Источник: выбранные {games}; скрыто фильтром при запуске: {k}.",
"Source : {games} sélectionnées ; masquées par le filtre au lancement : {k}.",
"Quelle: {games} ausgewählt; beim Start vom Filter verborgen: {k}.",
"Origen: {games} seleccionadas; ocultas por el filtro al iniciar: {k}.",
"Origine: {games} selezionate; nascoste dal filtro all'avvio: {k}.",
"Origem: {games} selecionadas; ocultas pelo filtro no início: {k}.",
"Manba: tanlangan {games}; boshlang‘ichda filtr yashirganni: {k}.",
"Көз: таңдалған {games}; басында сүзгі жасырғаны: {k}.",
],
[
"Source: selected {games}.",
"Источник: выбранные {games}.",
"Source : {games} sélectionnées.",
"Quelle: {games} ausgewählt.",
"Origen: {games} seleccionadas.",
"Origine: {games} selezionate.",
"Origem: {games} selecionadas.",
"Manba: tanlangan {games}.",
"Көз: таңдалған {games}.",
],
[
"Selection and filter changes do not change this pass.",
"Изменения выделения и фильтра не меняют этот проход.",
"Les changements de sélection et de filtre ne modifient pas ce passage.",
"Änderungen an Auswahl und Filter ändern diesen Durchlauf nicht.",
"Los cambios de selección y filtro no cambian este recorrido.",
"Le modifiche a selezione e filtro non cambiano questa analisi.",
"As alterações de seleção e filtro não mudam esta passagem.",
"Tanlov va filtr o‘zgarishlari bu o‘tishni o‘zgartirmaydi.",
"Таңдау мен сүзгі өзгерістері бұл өтуді өзгертпейді.",
],
[
"Selected: {games}",
"Выбрано: {games}",
"Sélection : {games}",
"Ausgewählt: {games}",
"Seleccionadas: {games}",
"Selezionate: {games}",
"Selecionadas: {games}",
"Tanlangan: {games}",
"Таңдалды: {games}",
],
[
"{k} hidden by the current filter",
"{k} скрыто текущим фильтром",
"{k} masquées par le filtre actuel",
"{k} vom aktuellen Filter verborgen",
"{k} ocultas por el filtro actual",
"{k} nascoste dal filtro attuale",
"{k} ocultas pelo filtro atual",
"Joriy filtr {k} tasini yashirdi",
"Ағымдағы сүзгі {k} партияны жасырды",
],
[
"Only the moves of «{name}» count.",
"Считаются только ходы игрока «{name}».",
"Seuls les coups de « {name} » comptent.",
"Nur die Züge von «{name}» zählen.",
"Solo cuentan las jugadas de «{name}».",
"Contano solo le mosse di «{name}».",
"Só contam os lances de «{name}».",
"Faqat «{name}» yurishlari hisoblanadi.",
"Тек «{name}» жүрістері есептеледі.",
],
[
"Only the moves of «{name}» as White count.",
"Считаются только ходы игрока «{name}» белыми.",
"Seuls les coups de « {name} » avec les Blancs comptent.",
"Nur die Züge von «{name}» mit Weiß zählen.",
"Solo cuentan las jugadas de «{name}» con blancas.",
"Contano solo le mosse di «{name}» col Bianco.",
"Só contam os lances de «{name}» de brancas.",
"Faqat «{name}» ning oq bilan yurishlari hisoblanadi.",
"Тек «{name}» ақпен жүрген жүрістері есептеледі.",
],
[
"Only the moves of «{name}» as Black count.",
"Считаются только ходы игрока «{name}» чёрными.",
"Seuls les coups de « {name} » avec les Noirs comptent.",
"Nur die Züge von «{name}» mit Schwarz zählen.",
"Solo cuentan las jugadas de «{name}» con negras.",
"Contano solo le mosse di «{name}» col Nero.",
"Só contam os lances de «{name}» de pretas.",
"Faqat «{name}» ning qora bilan yurishlari hisoblanadi.",
"Тек «{name}» қарамен жүрген жүрістері есептеледі.",
],
[
"The player condition limits the moves counted, but does not exclude selected games from review.",
"Условие игрока ограничивает считаемые ходы, но не исключает выбранные партии из разбора.",
"La condition du joueur limite les coups comptés, mais n’exclut pas les parties sélectionnées de l’analyse.",
"Die Spielerbedingung begrenzt die gezählten Züge, schließt ausgewählte Partien aber nicht aus der Analyse aus.",
"La condición del jugador limita las jugadas contadas, pero no excluye las partidas seleccionadas del análisis.",
"La condizione del giocatore limita le mosse contate, ma non esclude le partite selezionate dall'analisi.",
"A condição do jogador limita os lances contados, mas não exclui as partidas selecionadas da análise.",
"O‘yinchi sharti hisoblanadigan yurishlarni cheklaydi, ammo tanlangan partiyalarni tahlildan chiqarmaydi.",
"Ойыншы шарты есептелетін жүрістерді шектейді, бірақ таңдалған партияларды талдаудан шығармайды.",
],
[
"Hidden by the filter at start: {k}",
"Скрыто фильтром при запуске: {k}",
"Masquées par le filtre au lancement : {k}",
"Beim Start vom Filter verborgen: {k}",
"Ocultas por el filtro al iniciar: {k}",
"Nascoste dal filtro all'avvio: {k}",
"Ocultas pelo filtro no início: {k}",
"Boshlang‘ichda filtr yashirganni: {k}",
"Басында сүзгі жасырғаны: {k}",
],
];
#[cfg(test)]
@ -20909,6 +21085,8 @@ mod tests {
include_str!("opening_lines.rs"),
include_str!("opening_session.rs"),
include_str!("repertoire_ui.rs"),
include_str!("brilliant.rs"),
include_str!("brilliant_ui.rs"),
];
let mut missing = Vec::new();
let mut found = 0;

View file

@ -284,6 +284,7 @@ pub struct PassStatus {
/// In this database (else in `name`).
pub here: bool,
pub name: String,
pub selected: Option<crate::brilliant::SelectedGames>,
pub done: usize,
pub total: usize,
/// The record being analysed.
@ -648,6 +649,17 @@ impl LargeView {
self.view.iter().position(|&i| i as usize == record)
}
/// The cursor cannot stay on a record hidden by a new filter. Its mark can: marked
/// records are a separate selection, including a single hidden record.
fn clear_hidden_cursor(&mut self) {
if self
.selected
.is_some_and(|sel| !self.view.contains(&(sel as u32)))
{
self.selected = None;
}
}
/// A click on the row of `index` with `mods` (§42.5).
fn click(&mut self, index: usize, mods: egui::Modifiers) {
// An anchor hidden by the filter: the cursor, when it is seen, starts the range.
@ -794,27 +806,49 @@ impl LargeView {
})
}
/// «!! Find great moves» (the button, Shift+A): the library asks first.
fn ask_search(&mut self, path: &Path, actions: &mut Vec<LibraryAction>) {
let about = if self.last_conditions.is_empty() {
tr("all games").to_owned()
/// «!! Find great moves» (the button, Shift+A): a choice of records takes priority
/// over the filtered list. Both are owned snapshots: later changes in the table do
/// not change the request already sent to the library.
fn ask_search(&mut self, path: &Path, db: &Database, actions: &mut Vec<LibraryAction>) {
let selected = self.selected_games();
let (records, about) = if selected.is_none() {
let about = if self.last_conditions.is_empty() {
tr("all games").to_owned()
} else {
trf(
"matching: {list}",
&[("list", &self.last_conditions.join(" · "))],
)
};
(self.view.clone(), about)
} else {
trf(
"matching: {list}",
&[("list", &self.last_conditions.join(" · "))],
)
let mut records = self.marked.records();
let (sort, ascending) = if self.blocked.is_some() {
self.sort
} else {
self.effective_sort()
};
db.sort_records(&mut records, sort, ascending);
(records, String::new())
};
actions.push(LibraryAction::FindGreatMoves {
path: path.to_path_buf(),
records: self.view.clone(),
records,
filter: self.form.filter(),
about,
selected,
});
}
/// «!! Find great moves»: the button, or Shift+A outside a field (a disabled button
/// says why, also over an empty list).
fn handle_find(&mut self, ui: &mut Ui, path: &Path, actions: &mut Vec<LibraryAction>) {
fn handle_find(
&mut self,
ui: &mut Ui,
path: &Path,
db: &Database,
actions: &mut Vec<LibraryAction>,
) {
if !crate::platform::CAPS.great_moves {
return;
}
@ -824,14 +858,34 @@ impl LargeView {
&& 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, None) => self.ask_search(path, db, actions),
(false, Some(why)) => actions.push(LibraryAction::Notice(why)),
(true, _) => {}
}
}
}
/// Why the search cannot start on the list shown, if it cannot.
/// How many games a search asked for now would take: the whole choice when there
/// is one, otherwise the filtered list.
fn search_len(&self) -> usize {
if self.marked.is_empty() {
self.view.len()
} else {
self.marked.len()
}
}
/// The manual source and its hidden count, captured from the finished current view.
fn selected_games(&mut self) -> Option<crate::brilliant::SelectedGames> {
if self.marked.is_empty() {
return None;
}
let games = self.marked.len();
let hidden = self.hidden_marked();
Some(crate::brilliant::SelectedGames { games, hidden })
}
/// Why the search cannot start on the choice or the list shown, if it cannot.
fn search_blocked(&self) -> Option<String> {
if let Some(why) = &self.engine_busy {
return Some(why.clone());
@ -842,14 +896,29 @@ impl LargeView {
&[("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());
// Overflow is known without k and takes priority over a filter still running.
if self.marked.len() > crate::brilliant::LIMIT {
return Some(selected_limit_hint(self.marked.len()));
}
match crate::brilliant::can_start(self.view.len()) {
// A valid choice also waits: its hidden count is not known before this view.
if self.job.is_some() || self.shown.is_none() {
return Some(
tr(if self.marked.is_empty() {
"Wait: the games are still being filtered"
} else {
"Wait: counting how many selected games are hidden by the current filter"
})
.to_owned(),
);
}
match crate::brilliant::can_start(self.search_len()) {
Ok(()) => None,
Err(crate::brilliant::Blocked::NoGames) => {
Some(tr("No games match these conditions").to_owned())
}
Err(crate::brilliant::Blocked::TooMany) if !self.marked.is_empty() => {
Some(selected_limit_hint(self.marked.len()))
}
Err(crate::brilliant::Blocked::TooMany) => Some(format!(
"{}\n{}",
tr("Filter the games down to 100 or fewer"),
@ -1066,18 +1135,11 @@ impl LargeView {
self.in_order = answer.in_order;
self.blocked = answer.blocked;
self.shown = Some(job.request);
// A selected game that left the list is no longer selected, so Enter
// cannot open a game the user does not see.
// A choice of several records stays: it is built from several searches,
// and its hidden part is counted.
if let Some(sel) = self.selected
&& new_filter
&& !self.view.contains(&(sel as u32))
{
self.selected = None;
if self.marked.len() <= 1 {
self.mark(|m| m.clear());
}
// A cursor that left the list is cleared, so Enter cannot open a game
// the user does not see. The marked record itself stays, also when it
// is the only one: the search and copy include hidden chosen records.
if new_filter {
self.clear_hidden_cursor();
}
if new_filter {
// The user looks at the result of the new filter from its top.
@ -1831,6 +1893,11 @@ impl LargeView {
+ pad;
let slot = longest.max(width(button_text) + pad);
let pass = self.pass.clone();
let selected = if self.job.is_none() && self.shown.is_some() {
self.selected_games()
} else {
None
};
let blocked = self.search_blocked();
let error = self.pass_error.clone();
let mut find = false;
@ -1871,11 +1938,34 @@ impl LargeView {
)
)
};
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)],
let mut hint = String::new();
if let Some(selected) = p.selected {
if selected.hidden > 0 {
hint.push_str(&trf(
"Source: selected {games}; hidden by the filter at start: {k}.",
&[
("games", &crate::i18n::games(selected.games)),
("k", &grouped(selected.hidden)),
],
));
} else {
hint.push_str(&trf(
"Source: selected {games}.",
&[("games", &crate::i18n::games(selected.games))],
));
}
hint.push('\n');
hint.push_str(tr(
"Selection and filter changes do not change this pass.",
));
hint.push('\n');
}
hint.push_str(&trf(
"Analysed {i} of {n} · ≈ {time} left",
&[("i", &p.done), ("n", &p.total), ("time", &left)],
));
ui.add(egui::Label::new(RichText::new(text).weak()).truncate())
.on_hover_text(hint);
}
}
(None, Some(e)) => {
@ -1913,10 +2003,13 @@ impl LargeView {
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()))],
)),
None => r.on_hover_text(match selected {
Some(selected) => selected_search_hint(selected),
None => trf(
"Review {games} with the engine and mark the !! and ! moves found (Shift+A)",
&[("games", &crate::i18n::games(self.search_len()))],
),
}),
};
if r.clicked() {
find = true;
@ -2722,11 +2815,11 @@ impl LargeView {
}
});
// Shift+A on an empty list still says why nothing can be searched.
self.handle_find(ui, path, actions);
self.handle_find(ui, path, db, actions);
return open_notes;
}
self.handle_find(ui, path, actions);
self.handle_find(ui, path, db, actions);
self.update_marks_sides(db, ui.ctx());
// `CP_MARKS_DEMO=1`: made-up marks for the first rows (screenshots of the column).
if std::env::var_os("CP_MARKS_DEMO").is_some()
@ -2747,7 +2840,7 @@ impl LargeView {
let mut first = false;
ONCE.call_once(|| first = true);
if first {
self.ask_search(path, actions);
self.ask_search(path, db, actions);
}
}
// Records the database does not have (`CP_SELECT` on a short one) are not chosen.
@ -3776,6 +3869,36 @@ fn check_mark(ui: &mut Ui) {
.line_segment([c + vec2(-1.0, 3.5), c + vec2(5.0, -4.0)], stroke);
}
/// The active button's explanation of a manual source, including its hidden records.
fn selected_search_hint(selected: crate::brilliant::SelectedGames) -> String {
let mut hint = trf(
"Selected: {games}. Review them with the engine and mark !! and ! (Shift+A)",
&[("games", &crate::i18n::games(selected.games))],
);
hint.push('\n');
if selected.hidden > 0 {
hint.push_str(&trf(
"{k} hidden by the current filter; these games are included too.",
&[("k", &grouped(selected.hidden))],
));
} else {
hint.push_str(tr("The filter does not change this run's games."));
}
hint
}
/// More than 100 selected records: never fall back to a small enough filtered list.
fn selected_limit_hint(games: usize) -> String {
format!(
"{}\n{}",
trf(
"Selected: {games} — more than 100.",
&[("games", &crate::i18n::games(games))]
),
tr("Keep no more than 100 selected; the filter is not used.")
)
}
/// "11 741 260": thousands separated by a narrow space.
pub fn grouped(n: usize) -> String {
let digits = n.to_string();
@ -3833,6 +3956,29 @@ mod tests {
v
}
/// A table whose filter has finished, so its search button can be evaluated.
fn ready_table() -> LargeView {
let mut v = table();
let shown = v.request();
v.shown = Some(shown);
v
}
/// The owned request that the search button sends to the existing analysis path.
fn find_request(
v: &mut LargeView,
db: &Database,
) -> (Vec<u32>, Option<crate::brilliant::SelectedGames>) {
let mut actions = Vec::new();
v.ask_search(Path::new("/games.pgn"), db, &mut actions);
match actions.pop() {
Some(LibraryAction::FindGreatMoves {
records, selected, ..
}) => (records, selected),
_ => panic!("one great-moves request"),
}
}
#[test]
fn clicks_choose_one_toggle_and_ranges_in_the_tables_order() {
let mut v = table();
@ -3966,6 +4112,188 @@ mod tests {
assert!(actions.is_empty());
}
#[test]
fn the_search_limit_follows_the_choice_independently_of_the_filter() {
let mut v = ready_table();
v.view = (0..101).collect();
assert!(
v.search_blocked()
.is_some_and(|s| s.contains(tr("Filter the games down to 100 or fewer")))
);
// One and one hundred selected games may start even when the filter has 101.
v.marked.only(0);
assert_eq!(v.search_len(), 1);
assert_eq!(v.search_blocked(), None);
v.marked.clear();
for r in 0..100 {
v.marked.insert(r);
}
assert_eq!(v.search_len(), 100);
assert_eq!(v.search_blocked(), None);
v.marked.insert(100);
assert!(v.search_blocked().is_some_and(|s| s.contains(tr(
"Keep no more than 100 selected; the filter is not used."
))));
// The inverse: a small filtered list does not enable 101 selected games, and
// clearing that choice brings back the old filter behaviour.
v.clear_marks();
v.view = vec![0];
assert_eq!(v.search_blocked(), None);
for r in 0..101 {
v.marked.insert(r);
}
assert!(v.search_blocked().is_some_and(|s| s.contains(tr(
"Keep no more than 100 selected; the filter is not used."
))));
v.clear_marks();
assert_eq!(v.search_blocked(), None);
// A selected game hidden by an empty filtered result is still a valid source.
v.view.clear();
assert!(
v.search_blocked()
.is_some_and(|s| s.contains(tr("No games match these conditions")))
);
v.marked.only(0);
assert_eq!(v.search_blocked(), None);
v.marked.clear();
for r in 0..100 {
v.marked.insert(r);
}
assert_eq!(v.search_len(), 100);
assert_eq!(v.search_blocked(), None);
// Until the current view is ready, k is unknown for either source. Overflow is
// already known and takes priority over that wait.
v.shown = None;
v.marked.insert(100);
assert!(v.search_blocked().is_some_and(|s| s.contains(tr(
"Keep no more than 100 selected; the filter is not used."
))));
v.marked.remove(100);
assert!(v.search_blocked().is_some_and(|s| s.contains(tr(
"Wait: counting how many selected games are hidden by the current filter"
))));
v.clear_marks();
assert!(
v.search_blocked()
.is_some_and(|s| s.contains(tr("Wait: the games are still being filtered")))
);
}
#[test]
fn the_search_request_snapshots_exactly_the_selected_ids_including_hidden_ones() {
let db = database("search-source", &["a", "b", "c", "d"]);
let mut v = ready_table();
v.view = vec![0, 2];
// No choice: the previous source, the filtered table, is unchanged.
let (filtered, selected) = find_request(&mut v, &db);
assert_eq!(filtered, vec![0, 2]);
assert_eq!(selected, None);
// Inserting the same ID twice cannot duplicate it. Records 1 and 3 are hidden
// by the current table, but belong to the request just like visible record 0.
for r in [0, 1, 3, 1] {
v.marked.insert(r);
}
let (snapshot, selected) = find_request(&mut v, &db);
assert_eq!(snapshot, vec![0, 1, 3]);
assert_eq!(
selected,
Some(crate::brilliant::SelectedGames {
games: 3,
hidden: 2,
})
);
// Later selection, filter and sort changes do not mutate the sent Vec. A new
// request after clearing the selection uses the new filtered table again.
v.sort = (SortKey::Date, false);
v.marked.only(2);
v.view = vec![2];
assert_eq!(snapshot, vec![0, 1, 3]);
assert_eq!(
selected,
Some(crate::brilliant::SelectedGames {
games: 3,
hidden: 2,
})
);
v.clear_marks();
let (next, _) = find_request(&mut v, &db);
assert_eq!(next, vec![2]);
}
#[test]
fn a_single_hidden_mark_survives_the_cursor_reset() {
let mut v = ready_table();
v.marked.only(0);
v.selected = Some(0);
v.view.clear();
v.clear_hidden_cursor();
assert_eq!(v.selected, None);
assert_eq!(v.marked.records(), vec![0]);
assert_eq!(v.search_blocked(), None);
}
#[test]
fn escape_keeps_one_selected_game_as_the_search_source() {
let db = database("search-escape", &["a", "b", "c"]);
let mut v = ready_table();
v.view = vec![0, 1, 2];
v.click(0, egui::Modifiers::NONE);
v.click(1, ctrl());
v.click(2, ctrl());
assert!(v.escape());
assert_eq!(v.marked.len(), 1);
let (one, _) = find_request(&mut v, &db);
assert_eq!(one, vec![2]);
// The existing Ctrl+Space gesture can clear that last mark; only then does the
// command return to the filtered table.
v.marked.toggle(2);
assert!(v.marked.is_empty());
let (filtered, _) = find_request(&mut v, &db);
assert_eq!(filtered, vec![0, 1, 2]);
}
#[test]
fn selection_hints_explain_hidden_games_and_the_independent_limit() {
let selected = crate::brilliant::SelectedGames {
games: 3,
hidden: 2,
};
assert_eq!(
selected_search_hint(selected),
format!(
"{}\n{}",
trf(
"Selected: {games}. Review them with the engine and mark !! and ! (Shift+A)",
&[("games", &crate::i18n::games(3))]
),
trf(
"{k} hidden by the current filter; these games are included too.",
&[("k", &grouped(2))]
)
)
);
assert!(
selected_search_hint(crate::brilliant::SelectedGames {
games: 1,
hidden: 0,
})
.contains(tr("The filter does not change this run's games."))
);
let limit = selected_limit_hint(101);
assert!(limit.contains(&crate::i18n::games(101)));
assert!(limit.contains(tr(
"Keep no more than 100 selected; the filter is not used."
)));
}
#[test]
fn numbers_group_and_shorten() {
assert_eq!(grouped(11_741_260), "11\u{202f}741\u{202f}260");

View file

@ -107,8 +107,10 @@ pub enum LibraryAction {
path: PathBuf,
records: Vec<u32>,
filter: chess_import::chessbase::base::Filter,
/// The conditions in words, for the question and the summary.
/// The conditions in words, for a filtered question and summary.
about: String,
/// The manual source and its hidden count, fixed with `records`.
selected: Option<crate::brilliant::SelectedGames>,
},
EditGameData {
path: PathBuf,
@ -367,6 +369,7 @@ impl Library {
(
job.source.clone(),
crate::own_db::base_name(&job.source),
job.selected,
job.done(),
job.records.len(),
job.current(),
@ -376,20 +379,20 @@ impl Library {
});
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,
}
});
view.pass = status.as_ref().map(
|(source, name, selected, done, total, current, left, stopping)| {
large_db::PassStatus {
here: source == path,
name: name.clone(),
selected: *selected,
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() {