Position search fixes from QA report 3
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run

- The result cache keys on the board's move order too, so "in this move
  order" is not reused from another order of the same position.
- While a search runs, the hover arrow and the position a game opens at
  belong to the rows shown; small databases keep the last result dimmed.
- PGN: a game ending in its chosen occurrence has no next move (it was
  taken from a variation); Collector::add_match_with_next.
- Average rating of a continuation only from games with both ratings.
- Narrow windows: the pane switch stays visible, chips that do not fit
  become "+N more", columns hide by priority, the date becomes the year.
- Ctrl+Shift+Backspace clears all conditions with the position; × for the
  position in small databases; the outcome cache is bounded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-19 09:03:26 +03:00
parent b9eab389c7
commit 131e4b62fb
9 changed files with 289 additions and 104 deletions

View file

@ -271,7 +271,8 @@ impl SearchBoard {
let now = ctx.input(|i| i.time);
let mut changed = false;
ctx.input_mut(|i| {
if i.consume_key(Modifiers::COMMAND, Key::Backspace) {
// Ctrl+Backspace (not with Shift: that clears all conditions).
if !i.modifiers.shift && i.consume_key(Modifiers::COMMAND, Key::Backspace) {
self.reset(now);
changed = true;
}

View file

@ -80,6 +80,15 @@ pub fn trf(key: &'static str, args: &[(&str, &dyn Display)]) -> String {
// [English, Русский, Français, Deutsch, Español, Italiano]
const ROWS: &[[&str; 6]] = &[
// --- position search ---
["Year", "Год", "Année", "Jahr", "Año", "Anno"],
[
"+{n} more",
"ещё {n}",
"+{n} autres",
"+{n} weitere",
"+{n} más",
"+{n} altri",
],
[
"Clear",
"Очистить",

View file

@ -181,9 +181,27 @@ pub enum Pane {
Board,
}
/// Search outcomes of the session, by filter and position.
/// Search outcomes of the session, by filter and position with the board's move order
/// (it decides "in this move order").
type OutcomeCache = HashMap<(u64, u64), Arc<PositionOutcome>>;
/// Matching games kept in the cache at most (16 bytes each).
const CACHE_MATCHES: usize = 20_000_000;
/// Identity of a searched position with the board's move order.
fn position_id((key, query): &(u64, PositionQuery)) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
key.hash(&mut h);
if let Some(line) = &query.line {
for m in line {
chess_import::position::uci(m).to_string().hash(&mut h);
}
} else {
"no line".hash(&mut h);
}
h.finish()
}
fn filter_hash(f: &Filter) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
f.hash(&mut h);
@ -347,12 +365,15 @@ impl LargeView {
&& s.position.as_ref().map(|p| p.0)
!= job.request.position.as_ref().map(|p| p.0))
});
if let (Some(out), Some((key, _))) = (&answer.outcome, &job.request.position) {
if self.cache.len() > 256 {
if let (Some(out), Some(pos)) = (&answer.outcome, &job.request.position) {
let kept: usize = self.cache.values().map(|o| o.matches.len()).sum();
if kept + out.matches.len() > CACHE_MATCHES {
self.cache.clear();
}
self.cache
.insert((filter_hash(&job.request.filter), *key), out.clone());
self.cache.insert(
(filter_hash(&job.request.filter), position_id(pos)),
out.clone(),
);
}
self.view = answer.view;
self.outcome = answer.outcome;
@ -408,7 +429,10 @@ impl LargeView {
let cached = request
.position
.as_ref()
.and_then(|(key, _)| self.cache.get(&(filter_hash(&request.filter), *key)))
.and_then(|pos| {
self.cache
.get(&(filter_hash(&request.filter), position_id(pos)))
})
.cloned();
let (db, req) = (db.clone(), request.clone());
let work = Background::spawn(ctx, now, move |progress, cancel| {
@ -718,23 +742,12 @@ impl LargeView {
let mut toggle_order = false;
ui.horizontal(|ui| {
ui.set_min_height(22.0);
if conditions.is_empty() {
ui.label(RichText::new(tr("No conditions: all games are shown")).weak());
}
for c in &conditions {
let (open, remove) = chip(ui, c);
if open {
goto = Some(c.pane);
}
if remove {
clear = Some(c.clear);
}
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if let Some((same, all)) = self.in_order
&& self.board.is_set()
&& (same < all || self.only_order)
{
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
{
let link = if self.only_order {
tr("all move orders")
} else {
@ -755,8 +768,36 @@ impl LargeView {
.weak()
.size(12.0),
);
});
}
}
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
if conditions.is_empty() {
ui.label(RichText::new(tr("No conditions: all games are shown")).weak());
}
for (n, c) in conditions.iter().enumerate() {
// No room for another chip: the rest in a tooltip.
if ui.available_width() < 140.0 && n + 1 < conditions.len() {
let rest: Vec<&str> =
conditions[n..].iter().map(|c| c.text.as_str()).collect();
if ui
.link(trf("+{n} more", &[("n", &rest.len())]))
.on_hover_text(rest.join("\n"))
.clicked()
{
goto = Some(Pane::Filters);
}
break;
}
let (open, remove) = chip(ui, c);
if open {
goto = Some(c.pane);
}
if remove {
clear = Some(c.clear);
}
}
});
});
});
if toggle_order {
self.only_order = !self.only_order;
@ -803,14 +844,6 @@ impl LargeView {
ui.add_space(4.0);
self.annotations_group(ui);
});
if ui.input_mut(|i| {
i.consume_key(
egui::Modifiers::COMMAND | egui::Modifiers::SHIFT,
egui::Key::Backspace,
)
}) {
self.reset();
}
}
fn reset(&mut self) {
@ -1164,19 +1197,31 @@ impl LargeView {
let progress = self.slow_progress(now, base.records());
let total = base.games() + base.texts();
// The pane switch comes first (right): it stays visible in a narrow window,
// the rest of the line is shortened.
ui.horizontal(|ui| {
ui.label(
RichText::new(
path.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default(),
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
// The switch packs its segments; the rest keeps the usual spacing.
ui.scope(|ui| self.pane_switch(ui));
ui.add_space(8.0);
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
ui.add(
egui::Label::new(
RichText::new(
path.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default(),
)
.strong(),
)
.strong(),
.truncate(),
);
ui.label(RichText::new(tr("· ChessBase, read-only")).weak())
.on_hover_text(tr(
"Read in place; the original files are not changed. Save a game to keep your edits.",
));
if ui.available_width() > 520.0 {
ui.label(RichText::new(tr("· ChessBase, read-only")).weak())
.on_hover_text(tr(
"Read in place; the original files are not changed. Save a game to keep your edits.",
));
}
let counter = match &self.shown {
Some(s)
if s.use_position
@ -1198,7 +1243,7 @@ impl LargeView {
if progress.is_some() {
counter = counter.weak();
}
ui.label(counter);
ui.add(egui::Label::new(counter).truncate());
if let Some(p) = progress {
ui.add(egui::Spinner::new().size(14.0));
ui.label(RichText::new(format!("{:.0} %", p * 100.0)).weak());
@ -1211,9 +1256,8 @@ impl LargeView {
{
open_notes = true;
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
self.pane_switch(ui);
});
});
});
self.chips(ui, settings);
ui.add_space(2.0);
@ -1225,8 +1269,26 @@ impl LargeView {
if ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::B)) {
self.pane = Pane::Board;
}
// Ctrl+Shift+Backspace: all conditions, the position included.
if ui.input_mut(|i| {
i.consume_key(
egui::Modifiers::COMMAND | egui::Modifiers::SHIFT,
egui::Key::Backspace,
)
}) {
self.reset();
self.board = SearchBoard::new();
self.only_order = false;
}
let use_position = self.shown.as_ref().is_some_and(|s| s.use_position);
// The position the shown rows were found for (the board may be ahead of it).
let shown_position = self
.shown
.as_ref()
.filter(|s| s.use_position)
.and_then(|s| s.position.as_ref())
.map(|(_, q)| q.position.clone());
if self.shown.is_some() && self.view.is_empty() && self.job.is_none() {
ui.vertical_centered(|ui| {
ui.add_space(40.0);
@ -1262,46 +1324,60 @@ impl LargeView {
None
};
// Narrow windows drop the least needed columns first.
// Narrow windows drop the least needed columns first (round, number, marks,
// length, ECO, event); the date becomes the year.
let width = ui.available_width();
let show_round = width >= 1000.0;
let show_moves = width >= 760.0;
let show_marks = width >= 720.0;
let show_round = width >= 1100.0;
let show_number = !use_position || width >= 1100.0;
let show_moves = width >= 1000.0;
let show_marks = width >= 1000.0;
let show_eco = width >= 860.0;
let show_event = width >= 720.0;
let year_only = width < 1000.0;
let mut columns: Vec<(&str, Option<SortKey>, Column)> = Vec::new();
if use_position {
columns.push((tr("Move"), None, Column::exact(52.0)));
}
if show_number {
columns.push(("№", Some(SortKey::Number), Column::exact(84.0)));
}
// Without the event the names share the rest of the width.
let name = if show_event {
Column::initial(170.0).at_least(60.0).clip(true)
} else {
Column::remainder().at_least(60.0).clip(true)
};
columns.extend([
("№", Some(SortKey::Number), Column::exact(84.0)),
(
tr("White"),
Some(SortKey::White),
Column::initial(170.0).at_least(60.0).clip(true),
),
(tr("White"), Some(SortKey::White), name),
("Elo", Some(SortKey::WhiteElo), Column::exact(44.0)),
(
tr("Black"),
Some(SortKey::Black),
Column::initial(170.0).at_least(60.0).clip(true),
),
(tr("Black"), Some(SortKey::Black), name),
("Elo", Some(SortKey::BlackElo), Column::exact(44.0)),
(tr("Result"), Some(SortKey::Result), Column::exact(56.0)),
]);
if show_moves {
columns.push((tr("Length"), Some(SortKey::Moves), Column::exact(56.0)));
}
columns.push(("ECO", Some(SortKey::Eco), Column::exact(44.0)));
if show_eco {
columns.push(("ECO", Some(SortKey::Eco), Column::exact(44.0)));
}
if show_marks {
columns.push(("💬", None, Column::exact(40.0)));
}
columns.push((
tr("Event"),
Some(SortKey::Event),
Column::remainder().at_least(80.0).clip(true),
));
if show_event {
columns.push((
tr("Event"),
Some(SortKey::Event),
Column::remainder().at_least(80.0).clip(true),
));
}
if show_round {
columns.push((tr("Round"), None, Column::exact(48.0)));
}
columns.push((tr("Date"), Some(SortKey::Date), Column::exact(88.0)));
if year_only {
columns.push((tr("Year"), Some(SortKey::Date), Column::exact(48.0)));
} else {
columns.push((tr("Date"), Some(SortKey::Date), Column::exact(88.0)));
}
if progress.is_some() {
ui.set_opacity(0.6);
@ -1432,6 +1508,9 @@ impl LargeView {
RichText::new(marks).weak()
}
(_, Some(SortKey::Event)) => RichText::new(r.event.as_str()).italics(),
(_, Some(SortKey::Date)) if year_only => {
RichText::new(r.date.get(..4).filter(|y| !y.contains('?')).unwrap_or(""))
}
(_, Some(SortKey::Date)) => RichText::new(crate::library::display_date(&r.date)),
_ => RichText::new(if r.round == "?" { "" } else { r.round.as_str() }).weak(),
};
@ -1439,7 +1518,7 @@ impl LargeView {
});
}
let resp = row.response();
let resp = if show_round {
let resp = if show_round && show_event {
resp
} else {
resp.on_hover_text(format!("{} · {}", r.event, r.round))
@ -1466,7 +1545,10 @@ impl LargeView {
}
});
});
// The shown rows belong to the shown position: no arrow on another one.
let shown_here = shown_position.as_ref() == Some(&self.board.position());
self.table_hover = hovered
.filter(|_| shown_here)
.zip(self.outcome.as_deref().filter(|_| use_position))
.and_then(|(i, out)| board_search::next_move_of(out, i));
if let Some((k, v)) = toggle_viewed {
@ -1490,7 +1572,7 @@ impl LargeView {
actions.push(LibraryAction::OpenGame {
path: path.to_path_buf(),
index,
at: use_position.then(|| self.board.position()),
at: shown_position.clone(),
});
}
open_notes
@ -1534,7 +1616,12 @@ impl LargeView {
actions.push(LibraryAction::OpenGame {
path: path.to_path_buf(),
index,
at: self.board.is_set().then(|| self.board.position()),
at: self
.shown
.as_ref()
.filter(|s| s.use_position)
.and_then(|s| s.position.as_ref())
.map(|(_, q)| q.position.clone()),
});
}
}

View file

@ -75,8 +75,9 @@ struct SmallRequest {
struct SmallBoard {
board: SearchBoard,
open: bool,
job: Option<(SmallRequest, Background<PositionOutcome>)>,
shown: Option<(SmallRequest, Arc<PositionOutcome>)>,
job: Option<(SmallRequest, shakmaty::Chess, Background<PositionOutcome>)>,
/// The last result, the request and the position it answers.
shown: Option<(SmallRequest, shakmaty::Chess, Arc<PositionOutcome>)>,
table_hover: Option<UciMove>,
/// Most games have no result: a book; continuations count chapters.
books: bool,
@ -111,13 +112,13 @@ impl SmallBoard {
/// Collects a finished search and starts the one the board and search text ask for.
fn update(&mut self, db: &Arc<Database>, search: &str, ctx: &egui::Context) {
if let Some((req, job)) = &self.job
if let Some((req, pos, job)) = &self.job
&& let Some(result) = job.poll()
{
let req = req.clone();
let (req, pos) = (req.clone(), pos.clone());
self.job = None;
if let Some(out) = result {
self.shown = Some((req, Arc::new(out)));
self.shown = Some((req, pos, Arc::new(out)));
}
}
if !self.open && !self.board.is_set() {
@ -127,10 +128,11 @@ impl SmallBoard {
let current = self
.job
.as_ref()
.map(|(r, _)| r)
.or(self.shown.as_ref().map(|(r, _)| r));
.map(|(r, ..)| r)
.or(self.shown.as_ref().map(|(r, ..)| r));
if current != Some(&wanted) {
let (db, query, text) = (db.clone(), self.board.query(), wanted.search.clone());
let pos = query.position.clone();
let now = ctx.input(|i| i.time);
self.job = Background::spawn(ctx, now, move |progress, cancel| {
let pgn = db.as_pgn()?;
@ -145,7 +147,7 @@ impl SmallBoard {
});
db.search_position(candidates.as_deref(), &query, progress, cancel)
})
.map(|j| (wanted, j));
.map(|j| (wanted, pos, j));
}
if self.job.is_some() {
ctx.request_repaint_after(std::time::Duration::from_millis(50));
@ -154,7 +156,7 @@ impl SmallBoard {
/// The outcome for the current board and search text, if ready.
fn outcome(&self, search: &str) -> Option<&PositionOutcome> {
let (req, out) = self.shown.as_ref()?;
let (req, _, out) = self.shown.as_ref()?;
(*req == self.request(search)).then_some(out.as_ref())
}
}
@ -867,17 +869,22 @@ impl Library {
// With a position on the board: only the games that reach it.
let small = self.small.get(&path);
let position = small.filter(|s| s.board.is_set());
let outcome: Option<Arc<PositionOutcome>> = position.and_then(|s| {
s.outcome(&self.search)
.map(|_| s.shown.as_ref().expect("shown").1.clone())
});
let searching = position.is_some() && outcome.is_none();
let ordered = position.is_some_and(|s| s.board.query().line.is_some());
let at = position.map(|s| s.board.position());
// While a new search runs the last result stays (dimmed): its rows, arrows and
// the position a game opens at all belong to the position it was found for.
let last = position.and_then(|s| s.shown.as_ref());
let outcome: Option<Arc<PositionOutcome>> = last.map(|(_, _, out)| out.clone());
let current = position.is_some_and(|s| s.outcome(&self.search).is_some());
let searching = position.is_some() && !current;
let ordered = last.is_some_and(|(req, ..)| req.line.is_some());
let at = last.map(|(_, pos, _)| pos.clone());
let mut clear_position = false;
if let Some(s) = position {
ui.horizontal(|ui| {
let text = trf("Position: {line}", &[("line", &s.board.chip_text())]);
ui.label(RichText::new(text).size(13.0));
clear_position = crate::widgets::small_close_button(ui)
.on_hover_text(tr("Remove the condition"))
.clicked();
if searching {
ui.add(egui::Spinner::new().size(14.0));
} else if let Some(out) = &outcome {
@ -1122,10 +1129,14 @@ impl Library {
});
});
let next = hovered
.filter(|_| current)
.zip(outcome.as_deref())
.and_then(|(i, out)| board_search::next_move_of(out, i));
if let Some(small) = self.small.get_mut(&path) {
small.table_hover = next;
if clear_position {
small.board = SearchBoard::new();
}
}
if let Some((k, v)) = toggle_viewed {
self.viewed.set(k, v);