From 29ffff3de914e672cbdec495189c63546529a351 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 23 Oct 2026 23:39:31 +0300 Subject: [PATCH] Desktop: the filters and position search of ChessBase for every database MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - chess-import pgn_catalog: the tags of a PGN as ChessBase's filters, sorting and name suggestions (tournament «Event (place) year», dates with any separator, rating, ECO, length counted when there is no PlyCount, comments without clock marks); the quick search (Filter::text) for PGN and ChessBase, ё folded as е; which fields a database has. The PGN scan counts main-line and all moves and real comments; the position table's memory is reckoned from the moves. - Desktop: one view for all databases (large_db.rs): the PGN table and its small board are gone; the quick search in the header with its chip, Ctrl+F twice to the filters; downloaded databases sorted newest first by date; texts' checkbox only where there are texts; an empty result says which field no game has; position search without memory says so on the board and its chip; a reread keeps the conditions. - Bench: the quick search on a large base. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 20 + apps/desktop/src/board_search.rs | 17 +- apps/desktop/src/i18n.rs | 112 +++ apps/desktop/src/large_db.rs | 445 +++++++++--- apps/desktop/src/library.rs | 831 +++------------------- crates/chess-core/src/pgn/scan.rs | 65 ++ crates/chess-import/src/bench.rs | 13 + crates/chess-import/src/chessbase/base.rs | 81 ++- crates/chess-import/src/lib.rs | 145 +++- crates/chess-import/src/pgn_catalog.rs | 827 +++++++++++++++++++++ docs/design/board-search.md | 6 +- docs/design/large-databases.md | 151 +++- docs/dev/import.md | 10 + 13 files changed, 1855 insertions(+), 868 deletions(-) create mode 100644 crates/chess-import/src/pgn_catalog.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 27e81fb..be2ea3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,26 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). +## [Unreleased] + +- Desktop: **every database gets the filters and the position search of a ChessBase + database** — PGN files of any size, downloads from Lichess and Chess.com, archives and + small ChessBase databases. Player and opponent (with the colour), tournament or place, + annotator, years, rating, result, ECO, length, «with comments» (clock and evaluation + marks such as `[%clk]` do not count) and «with variations»; names suggested as you + type; the table sorts by any column. Fields a file does not have stay in the panel, + and an empty result says when no game of the database has that field. Dates are read + with dots, dashes or slashes (`2026-10-18`), the length of a game is counted when the + file has no `PlyCount`. +- Desktop: the quick search is in the header of every database (Mega too); each word may + be found in a different field ("carlsen 2024"). Ctrl+F goes there, again to the filters. +- Desktop: games downloaded from Lichess and Chess.com are shown newest first (by the + date and time they were played); on Android the count over a downloaded database's + games grows during its download. +- Names are found with «е» for «ё» («Артем» finds «Артём»). +- The memory a PGN's position search needs is reckoned from its moves, not from the size + of the file (a file with clock comments was thought to need 14 times too much). + ## [0.15.0] — 2026-10-23 - Android: **the app updates itself.** Once a day (a switch in About turns it off; «Check diff --git a/apps/desktop/src/board_search.rs b/apps/desktop/src/board_search.rs index 792b86b..56aad87 100644 --- a/apps/desktop/src/board_search.rs +++ b/apps/desktop/src/board_search.rs @@ -60,6 +60,11 @@ pub struct SearchBoard { undo: Option, /// Continuation under the pointer (its arrow is drawn). hover: Option, + /// The first search of the database also prepares its position table (a PGN's, + /// once per session): the waiting line says so. + pub preparing: bool, + /// The position cannot be searched now (no memory for the table): no continuations. + pub unavailable: bool, } impl SearchBoard { @@ -73,6 +78,8 @@ impl SearchBoard { board: BoardState::default(), undo: None, hover: None, + preparing: false, + unavailable: false, } } @@ -598,12 +605,18 @@ impl SearchBoard { let Some(out) = outcome else { ui.label(RichText::new(title).strong()); ui.add_space(8.0); + if self.unavailable { + ui.label(RichText::new("—").weak()); + return; + } ui.horizontal(|ui| { ui.add(egui::Spinner::new().size(14.0)); + let p = format!("{:.0}", counting.unwrap_or(0.0) * 100.0); let text = match counting { - Some(p) if p > 0.0 => { - trf("Counting… {p} %", &[("p", &format!("{:.0}", p * 100.0))]) + _ if self.preparing => { + trf("Preparing the position search (once)… {p} %", &[("p", &p)]) } + Some(c) if c > 0.0 => trf("Counting… {p} %", &[("p", &p)]), _ => tr("Counting…").to_string(), }; ui.label(RichText::new(text).weak()); diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 7cc1c5a..301b44f 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -2648,6 +2648,118 @@ const ROWS: &[[&str; 6]] = &[ "Exactamente este nombre; edite el texto para volver a buscar por palabras", "Esattamente questo nome; modifica il testo per cercare di nuovo per parole", ], + [ + "ChessBase, read-only", + "ChessBase, только чтение", + "ChessBase, lecture seule", + "ChessBase, schreibgeschützt", + "ChessBase, solo lectura", + "ChessBase, sola lettura", + ], + [ + "{format}, read-only", + "{format}, только чтение", + "{format}, lecture seule", + "{format}, schreibgeschützt", + "{format}, solo lectura", + "{format}, sola lettura", + ], + [ + "PGN, encoding {enc}", + "PGN, кодировка {enc}", + "PGN, encodage {enc}", + "PGN, Kodierung {enc}", + "PGN, codificación {enc}", + "PGN, codifica {enc}", + ], + [ + "Ctrl+F; again — the filters", + "Ctrl+F; ещё раз — фильтры", + "Ctrl+F ; encore une fois — les filtres", + "Strg+F; noch einmal — die Filter", + "Ctrl+F; otra vez — los filtros", + "Ctrl+F; di nuovo — i filtri", + ], + [ + "Filters: players, tournament, years, rating… (Ctrl+F twice)", + "Фильтры: игроки, турнир, годы, рейтинг… (Ctrl+F дважды)", + "Filtres : joueurs, tournoi, années, classement… (Ctrl+F deux fois)", + "Filter: Spieler, Turnier, Jahre, Wertung… (zweimal Strg+F)", + "Filtros: jugadores, torneo, años, Elo… (Ctrl+F dos veces)", + "Filtri: giocatori, torneo, anni, Elo… (Ctrl+F due volte)", + ], + [ + "Not applied: not enough memory for position search", + "Не применена: не хватает памяти для поиска по позициям", + "Non appliquée : pas assez de mémoire pour la recherche de position", + "Nicht angewendet: zu wenig Speicher für die Stellungssuche", + "No aplicada: no hay memoria suficiente para buscar por posición", + "Non applicata: memoria insufficiente per la ricerca per posizione", + ], + [ + "Search", + "Поиск", + "Recherche", + "Suche", + "Búsqueda", + "Ricerca", + ], + [ + "No game of this database has an ECO code", + "Ни у одной партии этой базы нет кода ECO", + "Aucune partie de cette base n'a de code ECO", + "Keine Partie dieser Datenbank hat einen ECO-Code", + "Ninguna partida de esta base tiene código ECO", + "Nessuna partita di questo database ha un codice ECO", + ], + [ + "No game of this database has an annotator", + "Ни у одной партии этой базы нет комментатора", + "Aucune partie de cette base n'a d'annotateur", + "Keine Partie dieser Datenbank hat einen Kommentator", + "Ninguna partida de esta base tiene comentarista", + "Nessuna partita di questo database ha un commentatore", + ], + [ + "No game of this database has a rating", + "Ни у одной партии этой базы нет рейтинга", + "Aucune partie de cette base n'a de classement", + "Keine Partie dieser Datenbank hat eine Wertung", + "Ninguna partida de esta base tiene Elo", + "Nessuna partita di questo database ha un Elo", + ], + [ + "No game of this database has a year", + "Ни у одной партии этой базы нет года", + "Aucune partie de cette base n'a d'année", + "Keine Partie dieser Datenbank hat ein Jahr", + "Ninguna partida de esta base tiene año", + "Nessuna partita di questo database ha un anno", + ], + [ + "Reset filters and search", + "Сбросить фильтры и поиск", + "Réinitialiser les filtres et la recherche", + "Filter und Suche zurücksetzen", + "Restablecer filtros y búsqueda", + "Azzera filtri e ricerca", + ], + [ + "{n} moves", + "{n} ходов", + "{n} coups", + "{n} Züge", + "{n} jugadas", + "{n} mosse", + ], + [ + "Preparing the position search (once)… {p} %", + "Готовлю поиск по позициям (один раз)… {p} %", + "Préparation de la recherche de position (une fois)… {p} %", + "Stellungssuche wird vorbereitet (einmalig)… {p} %", + "Preparando la búsqueda por posición (una vez)… {p} %", + "Preparo la ricerca per posizione (una volta)… {p} %", + ], [ "· ChessBase, read-only", "· ChessBase, только чтение", diff --git a/apps/desktop/src/large_db.rs b/apps/desktop/src/large_db.rs index 5f8150c..6026e3e 100644 --- a/apps/desktop/src/large_db.rs +++ b/apps/desktop/src/large_db.rs @@ -60,6 +60,8 @@ struct Form { hide_texts: bool, /// The result buttons are relative to the player (win / loss). relative_outcomes: bool, + /// The quick search of the header (not a condition of the panel). + search: String, } /// Number in a field: `Ok(None)` when empty, `Err` when not a number in `range`. @@ -114,6 +116,7 @@ impl Form { with_comments: self.with_comments, with_variations: self.with_variations, games_only: self.hide_texts, + text: self.search.trim().to_string(), } } @@ -166,6 +169,8 @@ struct Answer { outcome: Option>, /// Games that reached the position in the board's move order, of all found. in_order: Option<(usize, usize)>, + /// The position was not searched: the memory its table needs (bytes) is not there. + blocked: Option, } struct Job { @@ -173,7 +178,24 @@ struct Job { work: Background, } -/// What the right side of the library shows for a large database. +/// What the header line says about a database (the library knows it). +pub struct Header { + /// "ChessBase, read-only", "PGN, encoding UTF-8"… + pub format: String, + pub format_hint: String, + /// A database downloaded from Lichess and Chess.com: its "⟳ New games". + pub online: Option, +} + +pub struct OnlineButton { + /// A download into it runs. + pub busy: bool, + /// The sites answered at start. + pub enabled: bool, + pub hint: String, +} + +/// What the right side of the library shows for a database. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Pane { Hidden, @@ -260,6 +282,15 @@ pub struct LargeView { pane: Pane, /// Last text of each name field, to notice typing. typed: [String; 3], + /// Most games have no result: the continuations count chapters (a book). + books: bool, + /// The position of the shown list could not be searched for lack of memory + /// (the memory its table needs, bytes). + blocked: Option, + /// Ctrl+F asked for the quick search. + focus_search: bool, + /// The quick search has the keyboard (arrows and Enter go to the table). + search_focused: bool, } impl LargeView { @@ -325,9 +356,36 @@ impl LargeView { focus_player: false, pane, typed: Default::default(), + books: false, + blocked: None, + focus_search: false, + search_focused: false, } } + /// The view of a database just opened: a book's continuations count chapters, and + /// games downloaded from Lichess and Chess.com come newest first (§9.6). + pub fn for_database(db: &Database, online: bool) -> LargeView { + let mut view = LargeView::new(); + view.books = db.books(); + if online && view.sort == (SortKey::Number, true) { + view.sort = (SortKey::Date, false); + } + view + } + + /// The database was read again (it grew): the list is found anew, the conditions, + /// the position, the sort and the selection stay (§9.7). + pub fn reread(&mut self, db: &Database) { + self.job = None; + self.shown = None; + self.outcome = None; + self.in_order = None; + self.cache.clear(); + self.blocked = None; + self.books = db.books(); + } + /// Selects a record and scrolls to it (returning from a game). pub fn reveal(&mut self, index: usize) { self.selected = Some(index); @@ -413,6 +471,7 @@ impl LargeView { self.view = answer.view; self.outcome = answer.outcome; 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. @@ -502,9 +561,23 @@ impl LargeView { .get(&(filter_hash(&request.filter), position_id(pos))) }) .cloned(); + // A PGN database without the memory for its position table: the list by the + // filters only, and the board says why (checked once per request). + let blocked = request + .position + .as_ref() + .filter(|_| cached.is_none()) + .and_then(|_| db.positions_blocked()); let (db, req) = (db.clone(), request.clone()); let work = Background::spawn(ctx, now, move |progress, cancel| { - let base = db.as_chessbase()?; + if blocked.is_some() { + return Some(Answer { + view: db.query(&req.filter, req.sort, req.ascending, progress, cancel)?, + outcome: None, + in_order: None, + blocked, + }); + } let mut outcome = cached; if let Some((_, query)) = &req.position && outcome.is_none() @@ -513,7 +586,7 @@ impl LargeView { None } else { let ignore = AtomicUsize::new(0); - Some(base.query(&req.filter, SortKey::Number, true, &ignore, cancel)?) + Some(db.query(&req.filter, SortKey::Number, true, &ignore, cancel)?) }; let found = db.search_position(candidates.as_deref(), query, progress, cancel)?; outcome = Some(Arc::new(found)); @@ -532,15 +605,16 @@ impl LargeView { .filter(|m| !req.only_order || m.same_order) .map(|m| m.index) .collect(); - base.sort_records(&mut v, req.sort, req.ascending); + db.sort_records(&mut v, req.sort, req.ascending); v } else { - base.query(&req.filter, req.sort, req.ascending, progress, cancel)? + db.query(&req.filter, req.sort, req.ascending, progress, cancel)? }; Some(Answer { view, outcome, in_order, + blocked: None, }) }); if let Some(work) = work { @@ -559,13 +633,11 @@ impl LargeView { let spawned = std::thread::Builder::new() .name("db-suggest".into()) .spawn(move || { - if let Some(b) = db.as_chessbase() { - let r = match field { - NameField::Event => b.suggest_events(&q, SUGGESTIONS), - _ => b.suggest_players(&q, SUGGESTIONS), - }; - let _ = tx.send(r); - } + let r = match field { + NameField::Event => db.suggest_events(&q, SUGGESTIONS), + _ => db.suggest_players(&q, SUGGESTIONS), + }; + let _ = tx.send(r); }); if spawned.is_ok() { self.suggest_job = Some(SuggestJob { field, query, rx }); @@ -588,7 +660,10 @@ impl LargeView { actions: &mut Vec, ) { self.update(db, ui.ctx()); - let total = db.as_chessbase().map_or(1, |b| b.records()); + let total = db.len(); + // A PGN's first search builds its position table: the progress counts its games. + self.board.preparing = !db.positions_ready(); + self.board.unavailable = self.blocked.is_some(); let counting = self .job .as_ref() @@ -609,6 +684,22 @@ impl LargeView { )); }); } + if let Some(need) = self.blocked { + let free = chess_import::memory::available().unwrap_or(0); + let missing = (need + (256 << 20)).saturating_sub(free) / 1_000_000; + ui.label( + RichText::new(trf( + "Not enough memory for position search in this database: about {n} MB more is needed. Close other programs and try again.", + &[("n", &missing.max(1))], + )) + .color(ui.visuals().warn_fg_color), + ); + if ui.button(tr("Retry")).clicked() { + // The list is found anew; the memory is looked at again. + self.shown = None; + self.blocked = None; + } + } let outcome = self.board_outcome().cloned(); let mut events = Vec::new(); self.board.keys(ui.ctx(), outcome.as_ref(), &mut events); @@ -618,7 +709,7 @@ impl LargeView { outcome.as_ref(), counting, self.table_hover, - false, + self.books, )); for e in events { match e { @@ -634,6 +725,57 @@ impl LargeView { } } + /// The quick search of the header (§9.2): words found in a player, the tournament, + /// the annotator, the ECO code or the date; with the panel and the position. + fn search_field(&mut self, ui: &mut Ui, now: f64) { + if !self.form.search.is_empty() + && crate::widgets::small_close_button(ui) + .on_hover_text(tr("Clear")) + .clicked() + { + self.form.search.clear(); + self.typed_at = f64::NEG_INFINITY; + } + let width = if ui.available_width() > 700.0 { + 220.0 + } else { + 140.0 + }; + let resp = ui + .add( + egui::TextEdit::singleline(&mut self.form.search) + .hint_text(tr("🔍 Search: player, event, ECO, year")) + .desired_width(width), + ) + .on_hover_text(tr("Ctrl+F; again — the filters")); + if resp.changed() { + self.typed_at = now; + } + // Escape in a non-empty field clears it (egui has just taken the focus away); + // in an empty one it leaves the field for the table. + if resp.lost_focus() + && ui.input(|i| i.key_pressed(egui::Key::Escape)) + && !self.form.search.is_empty() + { + self.form.search.clear(); + self.typed_at = f64::NEG_INFINITY; + resp.request_focus(); + } + if std::mem::take(&mut self.focus_search) { + resp.request_focus(); + // The text selected: typing replaces it. + if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), resp.id) { + let range = egui::text::CCursorRange::two( + egui::text::CCursor::new(0), + egui::text::CCursor::new(self.form.search.chars().count()), + ); + state.cursor.set_char_range(Some(range)); + state.store(ui.ctx(), resp.id); + } + } + self.search_focused = resp.has_focus(); + } + /// The pane switch `[Filters | Board]`; a click on the shown pane hides it. fn pane_switch(&mut self, ui: &mut Ui) { let active = self.form.active(); @@ -658,7 +800,7 @@ impl LargeView { ( Pane::Filters, filters, - tr("Filters: players, tournament, years, rating… (Ctrl+F)"), + tr("Filters: players, tournament, years, rating… (Ctrl+F twice)"), ), ] { let on = self.pane == pane; @@ -682,10 +824,13 @@ impl LargeView { } else { trf("Position: {line}", &[("line", &self.board.chip_text())]) }; + let blocked = self.blocked.is_some(); out.push(Condition { - text, + text: if blocked { format!("{text} ⚠") } else { text }, pane: Pane::Board, clear: Clear::Position, + hint: blocked + .then(|| tr("Not applied: not enough memory for position search").to_string()), mini: Some(( self.board.position(), self.board.flipped, @@ -694,6 +839,15 @@ impl LargeView { )), }); } + if !f.search.trim().is_empty() { + out.push(Condition { + text: format!("{}: {}", tr("Search"), f.search.trim()), + pane: self.pane, + clear: Clear::Search, + hint: None, + mini: None, + }); + } let side = match f.side { Side::White => format!(" · {}", tr("as White")), Side::Black => format!(" · {}", tr("as Black")), @@ -705,6 +859,7 @@ impl LargeView { text, pane: Pane::Filters, clear, + hint: None, mini: None, }); } @@ -785,6 +940,7 @@ impl LargeView { self.board = SearchBoard::new(); self.only_order = false; } + Clear::Search => f.search.clear(), Clear::Player => { f.player = NameFilter::default(); f.side = Side::Any; @@ -873,7 +1029,9 @@ impl LargeView { break; } let (open, remove) = chip(ui, c); - if open { + if open && c.clear == Clear::Search { + self.focus_search = true; + } else if open { goto = Some(c.pane); } if remove { @@ -926,12 +1084,16 @@ impl LargeView { ui.add_space(4.0); self.game_group(ui); ui.add_space(4.0); - self.annotations_group(ui); + self.annotations_group(ui, db.texts() > 0); }); } + /// Clears the conditions of the panel; the quick search and the position stay. fn reset(&mut self) { - self.form = Form::default(); + self.form = Form { + search: std::mem::take(&mut self.form.search), + ..Form::default() + }; self.suggestions = None; self.typed = Default::default(); } @@ -1109,7 +1271,7 @@ impl LargeView { } } - fn annotations_group(&mut self, ui: &mut Ui) { + fn annotations_group(&mut self, ui: &mut Ui, texts: bool) { let f = &self.form; let count = usize::from(f.with_comments) + usize::from(f.with_variations) @@ -1117,10 +1279,13 @@ impl LargeView { Self::group_header(ui, tr("Annotations"), count); ui.checkbox(&mut self.form.with_comments, tr("with comments")); ui.checkbox(&mut self.form.with_variations, tr("with variations")); - let mut show_texts = !self.form.hide_texts; - ui.checkbox(&mut show_texts, tr("show texts")) - .on_hover_text(tr("Guiding texts of the database; left out by any condition on players, dates, ratings, results or moves")); - self.form.hide_texts = !show_texts; + // Only a database with guiding texts has the choice (§9.4). + if texts { + let mut show_texts = !self.form.hide_texts; + ui.checkbox(&mut show_texts, tr("show texts")) + .on_hover_text(tr("Guiding texts of the database; left out by any condition on players, dates, ratings, results or moves")); + self.form.hide_texts = !show_texts; + } } /// A name field with suggestions; picking one filters by exactly that name. @@ -1267,88 +1432,108 @@ impl LargeView { ui: &mut Ui, path: &Path, db: &Arc, + header: &Header, viewed: &mut Viewed, notes: usize, settings: &Settings, actions: &mut Vec, ) -> bool { let mut open_notes = false; - let Some(base) = db.as_chessbase() else { - return false; - }; self.update(db, ui.ctx()); let now = ui.input(|i| i.time); - let progress = self.slow_progress(now, base.records()); - let total = base.games() + base.texts(); + let progress = self.slow_progress(now, db.len()); + let total = db.games() + db.texts(); // The pane switch comes first (right): it stays visible in a narrow window, - // the rest of the line is shortened. + // then the quick search; the rest of the line is shortened. ui.horizontal(|ui| { - 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(), - ) - .truncate(), - ); - 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 - || s.filter != Filter::default() - || self.form.active() > 0 => - { - trf( - "· found {n} of {total}", - &[("n", &grouped(self.view.len())), ("total", &grouped(total))], - ) - } - _ if base.texts() > 0 => trf( - "· {n} games · {t} texts", - &[("n", &grouped(base.games())), ("t", &grouped(base.texts()))], - ), - _ => trf("· {n} games", &[("n", &grouped(base.games()))]), - }; - let mut counter = RichText::new(counter); - if progress.is_some() { - counter = counter.weak(); - } - 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()); - } - if notes > 0 && crate::widgets::notes_button(ui, notes).clicked() { - open_notes = true; - } + 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); + self.search_field(ui, now); + 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(), + ) + .truncate(), + ); + if ui.available_width() > 520.0 { + ui.label(RichText::new(format!("· {}", header.format)).weak()) + .on_hover_text(&header.format_hint); + } + let counter = match &self.shown { + Some(s) + if s.use_position + || s.filter != Filter::default() + || self.form.active() > 0 => + { + trf( + "· found {n} of {total}", + &[("n", &grouped(self.view.len())), ("total", &grouped(total))], + ) + } + _ if db.texts() > 0 => trf( + "· {n} games · {t} texts", + &[("n", &grouped(db.games())), ("t", &grouped(db.texts()))], + ), + _ => trf("· {n} games", &[("n", &grouped(db.games()))]), + }; + let mut counter = RichText::new(counter); + if progress.is_some() { + counter = counter.weak(); + } + 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()); + } + if notes > 0 && crate::widgets::notes_button(ui, notes).clicked() { + open_notes = true; + } + // A database from Lichess and Chess.com: its new games. + if let Some(online) = &header.online { + if online.busy { + ui.add(egui::Spinner::new().size(14.0)); + ui.label(RichText::new(tr("updating…")).weak()); + } else if ui + .add_enabled( + online.enabled, + egui::Button::new(tr("⟳ New games")).small(), + ) + .on_hover_text(&online.hint) + .on_disabled_hover_text(&online.hint) + .clicked() + { + actions.push(LibraryAction::UpdateOnline(path.to_path_buf())); + } + } + }); }); - }); }); self.chips(ui, settings); ui.add_space(2.0); + // Ctrl+F: the quick search; once more, the filters' first field (§9.10). if ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::F)) { - self.pane = Pane::Filters; - self.focus_player = true; + if self.search_focused { + self.pane = Pane::Filters; + self.focus_player = true; + } else { + self.focus_search = true; + } } 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. + // Ctrl+Shift+Backspace: all conditions, the quick search and the position included. if ui.input_mut(|i| { i.consume_key( egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, @@ -1356,19 +1541,23 @@ impl LargeView { ) }) { self.reset(); + self.form.search.clear(); self.board = SearchBoard::new(); self.only_order = false; } - let use_position = self.shown.as_ref().is_some_and(|s| s.use_position); + // A position that could not be searched (no memory) does not filter the list. + let use_position = + self.shown.as_ref().is_some_and(|s| s.use_position) && self.blocked.is_none(); // 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) + .filter(|s| s.use_position && self.blocked.is_none()) .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() { + let searched = !self.form.search.trim().is_empty(); ui.vertical_centered(|ui| { ui.add_space(40.0); if use_position { @@ -1376,16 +1565,52 @@ impl LargeView { RichText::new(tr("The position does not occur in these games")).size(16.0), ); ui.add_space(6.0); - if self.form.active() > 0 + if (self.form.active() > 0 || searched) && ui.button(tr("Search the whole database")).clicked() { self.reset(); + self.form.search.clear(); } } else { ui.label(RichText::new(tr("Nothing found")).size(16.0)); + // A condition on a field no game of the database has (§9.8). + let filled = db.filled(); + let f = &self.form; + for (asked, has, text) in [ + ( + !f.eco.trim().is_empty(), + filled.eco, + tr("No game of this database has an ECO code"), + ), + ( + !f.annotator.trim().is_empty(), + filled.annotator, + tr("No game of this database has an annotator"), + ), + ( + !f.elo_min.trim().is_empty(), + filled.elo, + tr("No game of this database has a rating"), + ), + ( + !f.year_from.trim().is_empty() || !f.year_to.trim().is_empty(), + filled.year, + tr("No game of this database has a year"), + ), + ] { + if asked && !has { + ui.label(RichText::new(text).weak()); + } + } ui.add_space(6.0); - if ui.button(tr("Reset filters")).clicked() { + let label = if searched { + tr("Reset filters and search") + } else { + tr("Reset filters") + }; + if ui.button(label).clicked() { self.reset(); + self.form.search.clear(); } } }); @@ -1418,7 +1643,13 @@ impl LargeView { columns.push((tr("Move"), None, Column::exact(52.0))); } if show_number { - columns.push(("№", Some(SortKey::Number), Column::exact(84.0))); + // As wide as the largest number (a check mark before it). + let digits = grouped(db.len()).chars().count() as f32; + columns.push(( + "№", + Some(SortKey::Number), + Column::exact((digits * 8.0 + 24.0).clamp(52.0, 84.0)), + )); } // Without the event the names share the rest of the width. let name = if show_event { @@ -1522,7 +1753,7 @@ impl LargeView { return; }; let index = index as usize; - let r = base.row(index); + let r = db.row(index); row.set_selected(selected == Some(index)); let key = viewed::key(db.identity(index)); let seen = viewed.contains(key); @@ -1555,7 +1786,13 @@ impl LargeView { check_mark(ui); } ui.add_space(14.0); - RichText::new(grouped(index + 1)).weak() + let n = RichText::new(grouped(index + 1)).weak(); + // A game that could not be read cleanly: its number is orange. + if db.damaged(index) { + n.color(Color32::from_rgb(0xe6, 0x8f, 0x00)) + } else { + n + } } (_, Some(SortKey::White)) if is_text => { RichText::new(format!("📄 {}", r.title)).italics() @@ -1596,12 +1833,14 @@ impl LargeView { ui.add(egui::Label::new(cell).selectable(false).truncate()); }); } + // Tournament · place · round · length · annotator, those it has. + let moves = if r.moves > 0 { trf("{n} moves", &[("n", &r.moves)]) } else { String::new() }; + let about: Vec<&str> = [r.event.as_str(), r.site.as_str(), r.round.as_str(), moves.as_str(), r.annotator.as_str()] + .into_iter() + .filter(|t| !t.trim().is_empty() && *t != "?" && !t.contains("://")) + .collect(); let resp = row.response(); - let resp = if show_round && show_event { - resp - } else { - resp.on_hover_text(format!("{} · {}", r.event, r.round)) - }; + let resp = if about.is_empty() { resp } else { resp.on_hover_text(about.join(" · ")) }; resp.context_menu(|ui| { let label = if seen { tr("Mark as not viewed") @@ -1674,7 +1913,8 @@ impl LargeView { i.key_pressed(egui::Key::Enter), ) }); - let enter = enter && !typing; + // Enter belongs to a filter field, but in the quick search it opens the game. + let enter = enter && (!typing || self.search_focused); let step = if page_up || page_down { 20 } else { 1 }; if up || down || page_up || page_down { let pos = self @@ -1711,6 +1951,8 @@ struct Condition { text: String, pane: Pane, clear: Clear, + /// Said under the pointer (a condition not applied, and why). + hint: Option, /// Position (and how to draw it) for the tooltip of the position chip. mini: Option<( shakmaty::Chess, @@ -1721,9 +1963,10 @@ struct Condition { } /// What removing a chip clears. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq, Eq)] enum Clear { Position, + Search, Player, Opponent, Event, @@ -1775,6 +2018,10 @@ fn chip(ui: &mut Ui, c: &Condition) -> (bool, bool) { }), None => r, }; + let r = match &c.hint { + Some(h) => r.on_hover_text(h), + None => r, + }; out.0 = r.clicked(); out.1 = crate::widgets::small_close_button(ui) .on_hover_text(tr("Remove the condition")) diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index de715c0..bbb8a33 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -1,5 +1,5 @@ -//! Library screen: shelf of databases (PGN, ChessBase, archives) + searchable, -//! sortable game table. +//! Library screen: shelf of databases (PGN, ChessBase, archives) and, for the chosen +//! one, the game table with its filters and position search (`large_db.rs`). use crate::i18n::{tr, trf}; use std::collections::HashMap; @@ -8,17 +8,13 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Receiver, channel}; use std::sync::{Arc, Mutex}; -use chess_core::{GameEntry, ScanProgress}; +use chess_core::ScanProgress; use chess_import::{Database, Format, ImportError, Opened, Unsupported}; -use egui::{Color32, RichText, Sense, Stroke, Ui, vec2}; +use egui::{RichText, Sense, Ui, vec2}; -use crate::board_search::{self, Background, BoardEvent, SearchBoard}; -use crate::large_db::{self, LargeView, Pane}; +use crate::large_db::{self, Header, LargeView, OnlineButton, Pane}; use crate::settings::Settings; use crate::viewed::{self, Viewed}; -use chess_import::position::PositionOutcome; -use egui_extras::{Column, TableBuilder}; -use shakmaty::uci::UciMove; enum Slot { Loading { @@ -30,20 +26,6 @@ enum Slot { Failed(String), } -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum SortKey { - Index, - White, - WhiteElo, - Black, - BlackElo, - Result, - Date, - Event, - Eco, - Moves, -} - pub enum LibraryAction { /// Open a game; `at`: show the first position equal to this one. OpenGame { @@ -68,114 +50,6 @@ pub enum LibraryAction { OpenSettings, } -/// What a small database's position search answers: the search text and the position. -#[derive(Clone, PartialEq)] -struct SmallRequest { - search: String, - key: u64, - line: Option>, -} - -/// The search board of a small database (PGN, books): positions of all games, -/// variations included, are searched in memory. -struct SmallBoard { - board: SearchBoard, - open: bool, - job: Option<(SmallRequest, shakmaty::Chess, Background)>, - /// The last result, the request and the position it answers. - shown: Option<(SmallRequest, shakmaty::Chess, Arc)>, - table_hover: Option, - /// Most games have no result: a book; continuations count chapters. - books: bool, - /// The position table cannot be built: memory it would need (bytes). - blocked: Option, -} - -impl SmallBoard { - fn new(db: &chess_core::PgnDatabase) -> SmallBoard { - let decided = db - .entries() - .iter() - .filter(|e| matches!(e.result(), Some("1-0" | "0-1" | "1/2-1/2"))) - .count(); - let dev = SearchBoard::from_env(); - SmallBoard { - open: dev.is_some(), - board: dev.unwrap_or_else(SearchBoard::new), - job: None, - shown: None, - table_hover: None, - books: decided * 2 < db.len(), - blocked: None, - } - } - - fn request(&self, search: &str) -> SmallRequest { - let q = self.board.query(); - SmallRequest { - search: search.trim().to_string(), - key: self.board.key(), - line: q.line, - } - } - - /// Collects a finished search and starts the one the board and search text ask for. - fn update(&mut self, db: &Arc, search: &str, ctx: &egui::Context) { - if let Some((req, pos, job)) = &self.job - && let Some(result) = job.poll() - { - let (req, pos) = (req.clone(), pos.clone()); - self.job = None; - if let Some(out) = result { - self.shown = Some((req, pos, Arc::new(out))); - } - } - if !self.open && !self.board.is_set() { - return; - } - let wanted = self.request(search); - let current = self - .job - .as_ref() - .map(|(r, ..)| r) - .or(self.shown.as_ref().map(|(r, ..)| r)); - if current != Some(&wanted) { - // No memory for the table: say so instead of starting a search that - // cannot answer. - self.blocked = db.positions_blocked(); - if self.blocked.is_some() { - return; - } - 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()?; - let candidates: Option> = (!text.is_empty()).then(|| { - let mut v: Vec = - filtered_sorted(pgn.entries(), &text, (SortKey::Index, true), false) - .into_iter() - .map(|i| i as u32) - .collect(); - v.sort_unstable(); - v - }); - db.search_position(candidates.as_deref(), &query, progress, cancel) - }) - .map(|j| (wanted, pos, j)); - } - if self.job.is_some() { - ctx.request_repaint_after(std::time::Duration::from_millis(50)); - } - } - - /// 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()?; - (*req == self.request(search)).then_some(out.as_ref()) - } -} - /// How a database was imported, and what is worth knowing about it. struct ImportInfo { format: Format, @@ -186,23 +60,14 @@ pub struct Library { slots: HashMap, /// Games the user has opened (by content). viewed: Viewed, - /// Filters and game list of each large ChessBase database (for the session). + /// Filters, quick search, position and game list of each database (for the session). large: HashMap, - /// Search board of each small database (for the session). - small: HashMap, /// A position from a game to show once its database is open. pending_position: Option<(PathBuf, shakmaty::Chess, Vec, bool)>, info: HashMap, /// Database whose import notes are shown. notes_open: Option, pub selected_db: Option, - search: String, - selected_row: Option, - sort: (SortKey, bool), - /// Cached filtered+sorted entry indices for (db, search, sort). - view: Vec, - view_key: Option<(PathBuf, String, SortKey, bool)>, - scroll_to_selected: bool, /// Lichess or Chess.com answered at start (the online games are offered). pub online: bool, /// Online databases being downloaded or updated. @@ -221,17 +86,10 @@ impl Library { slots: HashMap::new(), viewed: Viewed::load(), large: HashMap::new(), - small: HashMap::new(), pending_position: None, info: HashMap::new(), notes_open: None, selected_db: None, - search: String::new(), - selected_row: None, - sort: (SortKey::Index, true), - view: Vec::new(), - view_key: None, - scroll_to_selected: false, online: false, online_busy: Vec::new(), online_running: None, @@ -292,9 +150,6 @@ impl Library { self.load(path, ctx); if self.selected_db.as_deref() != Some(path) { self.selected_db = Some(path.to_path_buf()); - self.selected_row = None; - self.search.clear(); - self.view_key = None; } } @@ -303,17 +158,18 @@ impl Library { if let Some(view) = self.large.get_mut(path) { view.reveal(index); } - if self.selected_db.as_deref() == Some(path) { - self.selected_row = Some(index); - self.scroll_to_selected = true; - } } /// Reads a database again (its file changed), keeping it selected if it was. pub fn reload(&mut self, path: &Path, ctx: &egui::Context) { let selected = self.selected_db.as_deref() == Some(path); + // The conditions, the position, the sort and the selection stay (§9.7): the view + // finds its list anew once the file is read. + let view = self.large.remove(path); self.forget(path); - self.small.remove(path); + if let Some(v) = view { + self.large.insert(path.to_path_buf(), v); + } if selected { self.select_db(path, ctx); } else { @@ -329,7 +185,6 @@ impl Library { } if self.selected_db.as_deref() == Some(path) { self.selected_db = None; - self.view_key = None; } } @@ -371,10 +226,14 @@ impl Library { { *slot = match res { Ok(o) => { - if matches!(o.db, Database::ChessBase(_)) { - self.large - .entry(path.clone()) - .or_insert_with(LargeView::new); + // Every database has the filters and the position search. + match self.large.get_mut(path) { + Some(view) => view.reread(&o.db), + None => { + let online = crate::online::is_online(path); + self.large + .insert(path.clone(), LargeView::for_database(&o.db, online)); + } } self.info.insert( path.clone(), @@ -394,7 +253,6 @@ impl Library { } Err(e) => Slot::Failed(import_error(&e)), }; - self.view_key = None; } } self.apply_pending_position(); @@ -426,20 +284,12 @@ impl Library { }; let db = db.clone(); let (path, start, line, flipped) = self.pending_position.take().expect("pending"); - match db.as_ref() { - Database::ChessBase(_) => { - let view = self.large.entry(path).or_insert_with(LargeView::new); - view.show_position(start, line, flipped); - } - Database::Pgn(pgn) => { - let small = self - .small - .entry(path) - .or_insert_with(|| SmallBoard::new(pgn)); - small.board.set(start, line, flipped); - small.open = true; - } - } + let online = crate::online::is_online(&path); + let view = self + .large + .entry(path) + .or_insert_with(|| LargeView::for_database(&db, online)); + view.show_position(start, line, flipped); } pub fn show( @@ -452,10 +302,10 @@ impl Library { let mut actions = Vec::new(); // With the search board open in a low window the shelf folds into one line, // leaving the height to the board. - let board_open = self.selected_db.as_ref().is_some_and(|p| { - self.large.get(p).is_some_and(|v| v.pane() == Pane::Board) - || self.small.get(p).is_some_and(|s| s.open) - }); + let board_open = self + .selected_db + .as_ref() + .is_some_and(|p| self.large.get(p).is_some_and(|v| v.pane() == Pane::Board)); let low = ui.ctx().content_rect().height() < 760.0; if board_open && low { egui::Panel::top("shelf_compact") @@ -463,10 +313,9 @@ impl Library { } else { egui::Panel::top("shelf").show(ui, |ui| self.shelf(ui, databases, &mut actions)); } - // A large database has its filter panel or its search board on the right. + // A database has its filter panel or its search board on the right. if let Some(path) = self.selected_db.clone() && let Some(Slot::Ready(db)) = self.slots.get(&path) - && db.as_chessbase().is_some() && let Some(view) = self.large.get_mut(&path) { let db = db.clone(); @@ -489,59 +338,6 @@ impl Library { Pane::Hidden => {} } } - // A small database has its search board on the right when it is open. - if let Some(path) = self.selected_db.clone() - && let Some(Slot::Ready(db)) = self.slots.get(&path) - && db.as_pgn().is_some() - && let Some(small) = self.small.get_mut(&path) - && small.open - { - let db = db.clone(); - let search = self.search.clone(); - let width = ui.available_width(); - egui::Panel::right("search_board") - .resizable(true) - .default_size((width * 0.5).max(340.0)) - .size_range(340.0..=(width - 420.0).max(340.0)) - .show(ui, |ui| { - small.update(&db, &search, ui.ctx()); - let outcome = small.outcome(&search).cloned(); - let counting = small.job.as_ref().map(|_| 0.0); - let mut events = Vec::new(); - small.board.keys(ui.ctx(), outcome.as_ref(), &mut events); - if let Some(need) = small.blocked { - let free = chess_import::memory::available().unwrap_or(0); - let missing = (need + (256 << 20)).saturating_sub(free) / 1_000_000; - ui.label( - egui::RichText::new(trf( - "Not enough memory for position search in this database: about {n} MB more is needed. Close other programs and try again.", - &[("n", &missing.max(1))], - )) - .color(ui.visuals().warn_fg_color), - ); - } - events.extend(small.board.panel( - ui, - settings, - outcome.as_ref(), - counting, - small.table_hover, - small.books, - )); - for e in events { - match e { - BoardEvent::Changed => self.scroll_to_selected = false, - BoardEvent::Sound(s) => actions.push(LibraryAction::Sound(s)), - BoardEvent::CopyText(t, m) => { - actions.push(LibraryAction::CopyText(t, m)) - } - BoardEvent::OpenAsGame(pgn) => { - actions.push(LibraryAction::OpenPgn(pgn)) - } - } - } - }); - } egui::CentralPanel::default().show(ui, |ui| self.table_area(ui, settings, &mut actions)); self.notes_window(ui.ctx()); actions @@ -819,7 +615,6 @@ impl Library { } if ui.button(tr("Reload file")).clicked() { self.slots.remove(path); - self.view_key = None; self.load(path, ui.ctx()); ui.close(); } @@ -892,427 +687,75 @@ impl Library { } }; - if db.as_chessbase().is_some() { - let view = self - .large - .entry(path.clone()) - .or_insert_with(LargeView::new); - let notes = self.info.get(&path).map_or(0, |i| i.notes.len()); - if view.table(ui, &path, &db, &mut self.viewed, notes, settings, actions) { - self.notes_open = Some(path.clone()); - } - return; + let online = crate::online::is_online(&path); + let header = self.header(&path, &db, online); + let view = self + .large + .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.table( + ui, + &path, + &db, + &header, + &mut self.viewed, + notes, + settings, + actions, + ) { + self.notes_open = Some(path.clone()); } - let Some(pgn) = db.as_pgn() else { - return; - }; + } - let mut search_focused = false; - ui.horizontal(|ui| { - ui.label( - RichText::new( - path.file_name() - .map(|s| s.to_string_lossy().into_owned()) - .unwrap_or_default(), + /// What the header says about a database: its format, and for one downloaded from + /// Lichess and Chess.com, its "⟳ New games". + fn header(&self, path: &Path, db: &Database, online: bool) -> Header { + let (format, format_hint) = match (db, self.info.get(path)) { + (Database::ChessBase(_), _) => ( + tr("ChessBase, read-only").to_string(), + tr("Read in place; the original files are not changed. Save a game to keep your edits.").to_string(), + ), + (Database::Pgn(_), Some(info)) if info.format != Format::Pgn => ( + trf("{format}, read-only", &[("format", &info.format.label())]), + tr("Converted to PGN when opened; the original files are not changed. Save a game to keep your edits.").to_string(), + ), + (Database::Pgn(pgn), _) => ( + trf("PGN, encoding {enc}", &[("enc", &pgn.encoding().label())]), + String::new(), + ), + }; + let online = online.then(|| { + let when = crate::online::State::load(path) + .and_then(|s| s.updated) + .map(crate::online::ago); + let hint = if !self.online { + tr("No connection to Lichess and Chess.com").to_owned() + } else if let Some(w) = when { + trf( + "Fetch the games played since the last download ({when})", + &[("when", &w)], ) - .strong(), - ); - match self.info.get(&path) { - Some(info) if info.format != Format::Pgn => { - ui.label( - RichText::new(trf( - "· {n} games · {format}, read-only", - &[("n", &db.len()), ("format", &info.format.label())], - )) - .weak(), - ) - .on_hover_text(tr( - "Converted to PGN when opened; the original files are not changed. Save a game to keep your edits.", - )); - } - _ => { - let enc = pgn.encoding(); - ui.label( - RichText::new(trf( - "· {n} games · encoding {enc}", - &[("n", &db.len()), ("enc", &enc.label())], - )) - .weak(), - ); - } - } - let notes = self.info.get(&path).map_or(0, |i| i.notes.len()); - if notes > 0 && crate::widgets::notes_button(ui, notes).clicked() { - self.notes_open = Some(path.clone()); - } - if crate::online::is_online(&path) { - if self.online_busy.contains(&path) { - ui.add(egui::Spinner::new().size(14.0)); - ui.label(RichText::new(tr("updating…")).weak()); - } else { - let when = crate::online::State::load(&path) - .and_then(|s| s.updated) - .map(crate::online::ago); - let hint = if !self.online { - tr("No connection to Lichess and Chess.com").to_owned() - } else if let Some(w) = when { - trf( - "Fetch the games played since the last download ({when})", - &[("when", &w)], - ) - } else { - tr("Fetch the games played since the last download").to_owned() - }; - if ui - .add_enabled(self.online, egui::Button::new(tr("⟳ New games")).small()) - .on_hover_text(&hint) - .on_disabled_hover_text(&hint) - .clicked() - { - actions.push(LibraryAction::UpdateOnline(path.clone())); - } - } - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let small = self - .small - .entry(path.clone()) - .or_insert_with(|| SmallBoard::new(pgn)); - let label = if small.board.is_set() && !small.open { - format!("{} •", tr("Board")) - } else { - tr("Board").to_string() - }; - if ui - .selectable_label(small.open, label) - .on_hover_text(tr("Find games by position: play moves on the board (Ctrl+B)")) - .clicked() - || ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::B)) - { - small.open = !small.open; - } - if !self.search.is_empty() - && crate::widgets::small_close_button(ui) - .on_hover_text(tr("Clear")) - .clicked() - { - self.search.clear(); - } - let resp = ui.add( - egui::TextEdit::singleline(&mut self.search) - .hint_text(tr("🔍 Search: player, event, ECO, year")) - .desired_width(280.0), - ); - if ui.input(|i| i.modifiers.command && i.key_pressed(egui::Key::F)) { - resp.request_focus(); - } - search_focused = resp.has_focus(); - }); - }); - ui.add_space(4.0); - - let key = (path.clone(), self.search.clone(), self.sort.0, self.sort.1); - if self.view_key.as_ref() != Some(&key) { - // Games from Lichess and Chess.com: by default the most recent first. - let newest = crate::online::is_online(&path); - self.view = filtered_sorted(pgn.entries(), &self.search, self.sort, newest); - self.view_key = Some(key); - } - // 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()); - // 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> = 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 { - let n = large_db::grouped(out.matches.len()); - ui.label( - RichText::new(trf( - "· found {n} of {total}", - &[("n", &n), ("total", &large_db::grouped(pgn.len()))], - )) - .weak(), - ); - } - }); - } - let filtered: Vec; - let view: &Vec = match &outcome { - Some(out) => { - filtered = self - .view - .iter() - .copied() - .filter(|&i| { - out.matches - .binary_search_by_key(&(i as u32), |m| m.index) - .is_ok() - }) - .collect(); - &filtered - } - None => &self.view, - }; - let find = |index: usize| { - let out = outcome.as_ref()?; - let i = out - .matches - .binary_search_by_key(&(index as u32), |m| m.index) - .ok()?; - out.matches.get(i).copied() - }; - - // Keyboard: Up/Down move the selection, Enter opens. - if !ui.ctx().egui_wants_keyboard_input() || search_focused { - let pos = self - .selected_row - .and_then(|r| view.iter().position(|&i| i == r)); - let (up, down, enter) = ui.input(|i| { - ( - i.key_pressed(egui::Key::ArrowUp), - i.key_pressed(egui::Key::ArrowDown), - i.key_pressed(egui::Key::Enter), - ) - }); - if down || up { - let next = match (pos, down) { - (None, _) => 0, - (Some(p), true) => (p + 1).min(view.len().saturating_sub(1)), - (Some(p), false) => p.saturating_sub(1), - }; - if let Some(&i) = view.get(next) { - self.selected_row = Some(i); - self.scroll_to_selected = true; - } - } - if enter && let Some(index) = self.selected_row { - actions.push(LibraryAction::OpenGame { - path: path.clone(), - index, - at: at.clone(), - }); - } - } - - let scroll_row = if std::mem::take(&mut self.scroll_to_selected) { - self.selected_row - .and_then(|r| view.iter().position(|&i| i == r)) - } else { - None - }; - let headers: [(&str, SortKey); 10] = [ - ("№", SortKey::Index), - (tr("White"), SortKey::White), - ("Elo", SortKey::WhiteElo), - (tr("Black"), SortKey::Black), - ("Elo", SortKey::BlackElo), - (tr("Result"), SortKey::Result), - (tr("Length"), SortKey::Moves), - ("ECO", SortKey::Eco), - (tr("Event"), SortKey::Event), - (tr("Date"), SortKey::Date), - ]; - if searching { - ui.set_opacity(0.6); - } - let mut table = TableBuilder::new(ui) - .striped(true) - .resizable(true) - .sense(Sense::click()) - .cell_layout(egui::Layout::left_to_right(egui::Align::Center)); - if outcome.is_some() { - table = table.column(Column::exact(52.0)); - } - let mut table = table - .column(Column::exact(52.0)) - .column(Column::initial(170.0).at_least(60.0).clip(true)) - .column(Column::exact(48.0)) - .column(Column::initial(170.0).at_least(60.0).clip(true)) - .column(Column::exact(48.0)) - .column(Column::exact(80.0)) - .column(Column::exact(52.0)) - .column(Column::exact(48.0)) - .column(Column::remainder().at_least(80.0).clip(true)) - .column(Column::exact(96.0)); - if let Some(r) = scroll_row { - table = table.scroll_to_row(r, Some(egui::Align::Center)); - } - let entries = pgn.entries(); - let mut hovered = None; - let viewed = &self.viewed; - let mut toggle_viewed = None; - let mut clicked = None; - let mut opened = None; - let mut sort_click = None; - table - .header(26.0, |mut header| { - if outcome.is_some() { - header.col(|ui| { - ui.label(RichText::new(tr("Move")).strong()); - }); - } - for (label, key) in headers { - header.col(|ui| { - let arrow = if self.sort.0 == key { - if self.sort.1 { " ⏶" } else { " ⏷" } - } else { - "" - }; - if ui - .add( - egui::Button::new( - RichText::new(format!("{label}{arrow}")).strong(), - ) - .frame(false), - ) - .clicked() - { - sort_click = Some(key); - } - }); - } - }) - .body(|body| { - body.rows(24.0, view.len(), |mut row| { - let Some(e) = view.get(row.index()).and_then(|&i| entries.get(i)) else { - return; - }; - row.set_selected(self.selected_row == Some(e.index)); - let key = Some(viewed::key(pgn.raw_bytes(e.index).unwrap_or_default())); - let seen = key.is_some_and(|k| viewed.contains(k)); - let cells: [String; 10] = [ - (e.index + 1).to_string(), - e.white().unwrap_or("").to_string(), - e.white_elo().map(|x| x.to_string()).unwrap_or_default(), - e.black().unwrap_or("").to_string(), - e.black_elo().map(|x| x.to_string()).unwrap_or_default(), - e.result().unwrap_or("*").to_string(), - e.ply_count() - .map(|p| p.div_ceil(2).to_string()) - .unwrap_or_default(), - e.eco().unwrap_or("").to_string(), - e.event().filter(|s| *s != "?").unwrap_or("").to_string(), - display_date(e.date().unwrap_or("")), - ]; - if outcome.is_some() { - row.col(|ui| { - let Some(m) = find(e.index) else { return }; - let mut text = board_search::ply_label(m.ply); - if ordered && !m.same_order { - text = format!("↪{text}"); - } - if m.in_variation { - text.push_str(" 🔀"); - } - ui.add(egui::Label::new(text).selectable(false)) - .on_hover_text(tr("The move after which the position arose in the game. ↪ — reached by another move order, 🔀 — in a variation")); - }); - } - for (i, text) in cells.into_iter().enumerate() { - row.col(|ui| { - if i == 0 && seen { - // A check mark before the number: the game was opened before. - let c = ui.max_rect().left_center() + vec2(7.0, 0.0); - let stroke = Stroke::new(2.0, Color32::from_rgb(0x62, 0x9c, 0x2e)); - ui.painter().line_segment( - [c + vec2(-4.0, 0.0), c + vec2(-1.0, 3.5)], - stroke, - ); - ui.painter().line_segment( - [c + vec2(-1.0, 3.5), c + vec2(5.0, -4.0)], - stroke, - ); - } - if i == 0 { - ui.add_space(14.0); - } - let mut t = RichText::new(text); - if i == 0 { - t = t.weak(); - } - if i == 8 { - t = t.italics(); - } - if i == 0 && (e.flags.has_structure_issues || e.flags.has_decode_errors) - { - t = t.color(Color32::from_rgb(0xe6, 0x8f, 0x00)); - } - ui.add(egui::Label::new(t).selectable(false).truncate()); - }); - } - let resp = row.response(); - if let Some(k) = key { - resp.context_menu(|ui| { - let label = if seen { - tr("Mark as not viewed") - } else { - tr("Mark as viewed") - }; - if ui.button(label).clicked() { - toggle_viewed = Some((k, !seen)); - ui.close(); - } - }); - } - if resp.hovered() { - hovered = Some(e.index); - } - if resp.clicked() { - clicked = Some(e.index); - } - if resp.double_clicked() { - opened = Some(e.index); - } - }); - }); - 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); - } - if let Some(k) = sort_click { - self.sort = if self.sort.0 == k { - (k, !self.sort.1) } else { - (k, true) + tr("Fetch the games played since the last download").to_owned() }; - } - if let Some(i) = clicked { - self.selected_row = Some(i); - } - if let Some(index) = opened { - self.selected_row = Some(index); - actions.push(LibraryAction::OpenGame { path, index, at }); + OnlineButton { + busy: self.online_busy.contains(&path.to_path_buf()), + enabled: self.online, + hint, + } + }); + Header { + format, + format_hint, + online, } } } /// "2010.??.??" → "2010", "1997.05.??" → "05.1997", full dates as "dd.mm.yyyy". pub fn display_date(raw: &str) -> String { - let parts: Vec<&str> = raw.split('.').collect(); + let parts: Vec<&str> = raw.split(['.', '-', '/']).collect(); let known = |s: &&str| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()); match parts.as_slice() { [y, m, d] if known(y) && known(m) && known(d) => format!("{d}.{m}.{y}"), @@ -1322,71 +765,6 @@ pub fn display_date(raw: &str) -> String { } } -/// The games matching `search`, in the order of the column `key`. In a downloaded -/// database (`newest`) the "№" order is the time the games were played, the most recent -/// first: the sites' games are appended to the file oldest first, one site after another. -fn filtered_sorted( - entries: &[GameEntry], - search: &str, - (key, asc): (SortKey, bool), - newest: bool, -) -> Vec { - let needle = search.trim().to_lowercase(); - let mut v: Vec = entries - .iter() - .filter(|e| { - needle.is_empty() - || [ - "White", - "Black", - "Event", - "Site", - "ECO", - "Date", - "Annotator", - ] - .iter() - .any(|t| e.tag(t).is_some_and(|s| s.to_lowercase().contains(&needle))) - }) - .map(|e| e.index) - .collect(); - let text = |e: &GameEntry| -> String { - match key { - SortKey::White => e.white().unwrap_or("").to_lowercase(), - SortKey::Black => e.black().unwrap_or("").to_lowercase(), - SortKey::Result => e.result().unwrap_or("").to_string(), - SortKey::Date => e.date().unwrap_or("").to_string(), - SortKey::Event => e.event().unwrap_or("").to_lowercase(), - SortKey::Eco => e.eco().unwrap_or("").to_string(), - _ => String::new(), - } - }; - let num = |e: &GameEntry| -> i64 { - match key { - SortKey::Index => e.index as i64, - SortKey::WhiteElo => e.white_elo().map(i64::from).unwrap_or(-1), - SortKey::BlackElo => e.black_elo().map(i64::from).unwrap_or(-1), - SortKey::Moves => e.ply_count().map(i64::from).unwrap_or(-1), - _ => 0, - } - }; - if newest && key == SortKey::Index { - let mut keyed: Vec<(String, usize)> = - v.into_iter().map(|i| (entries[i].played_at(), i)).collect(); - keyed.sort_by(|x, y| if asc { y.cmp(x) } else { x.cmp(y) }); - return keyed.into_iter().map(|(_, i)| i).collect(); - } - v.sort_by(|&a, &b| { - let (ea, eb) = (&entries[a], &entries[b]); - let ord = text(ea) - .cmp(&text(eb)) - .then(num(ea).cmp(&num(eb))) - .then(a.cmp(&b)); - if asc { ord } else { ord.reverse() } - }); - v -} - /// User-facing text of an import failure. fn import_error(e: &ImportError) -> String { match e { @@ -1402,34 +780,3 @@ fn import_error(e: &ImportError) -> String { e => e.to_string(), } } - -#[cfg(test)] -mod tests { - use super::*; - use chess_core::pgn::scan_games; - use std::sync::atomic::AtomicBool; - - fn entries(pgn: &str) -> Vec { - scan_games( - pgn.as_bytes(), - chess_core::TextEncoding::Utf8, - &mut |_| {}, - &AtomicBool::new(false), - ) - .unwrap() - } - - #[test] - fn downloaded_games_come_newest_first() { - // As a download writes them: one site's games oldest first, then the other's. - let e = entries(concat!( - "[Site \"lichess\"][UTCDate \"2026.01.01\"][UTCTime \"10:00:00\"] 1. e4 *\n", - "[Site \"lichess\"][UTCDate \"2026.03.01\"][UTCTime \"10:00:00\"] 1. d4 *\n", - "[Site \"chess.com\"][UTCDate \"2026.02.01\"][UTCTime \"10:00:00\"] 1. c4 *\n", - )); - assert_eq!(filtered_sorted(&e, "", (SortKey::Index, true), true), vec![1, 2, 0]); - assert_eq!(filtered_sorted(&e, "", (SortKey::Index, false), true), vec![0, 2, 1]); - // Any other database keeps the order of its file. - assert_eq!(filtered_sorted(&e, "", (SortKey::Index, true), false), vec![0, 1, 2]); - } -} diff --git a/crates/chess-core/src/pgn/scan.rs b/crates/chess-core/src/pgn/scan.rs index 25e9777..db47a62 100644 --- a/crates/chess-core/src/pgn/scan.rs +++ b/crates/chess-core/src/pgn/scan.rs @@ -11,6 +11,9 @@ use crate::pgn::lexer::{Lexer, TokKind, parse_tag}; pub struct EntryFlags { pub has_fen: bool, pub has_comments: bool, + /// A comment with words in it, not only commands such as `[%clk 0:10:07]` or + /// `[%eval 0.3]` (clocks of online games are no comments to look for). + pub has_text_comments: bool, pub has_variations: bool, pub has_nags: bool, /// A `--` token outside comments (teaching null move). @@ -36,6 +39,10 @@ pub struct GameEntry { /// All tags in source order (decoded). pub tags: Vec<(String, String)>, pub flags: EntryFlags, + /// Half-moves of the main line (outside variations), as written. + pub main_plies: u32, + /// Half-moves of the whole tree, variations included. + pub all_plies: u32, } impl GameEntry { @@ -69,6 +76,11 @@ impl GameEntry { pub fn eco(&self) -> Option<&str> { self.tag("ECO") } + /// Moves of the main line: the `PlyCount` tag when the file has it, else counted. + pub fn moves(&self) -> u32 { + self.ply_count().unwrap_or(self.main_plies).div_ceil(2) + } + /// When the game was played, as text that sorts by time: `UTCDate` and `UTCTime` /// when both are there (Lichess, Chess.com), else `Date`. pub fn played_at(&self) -> String { @@ -176,6 +188,8 @@ pub fn scan_games( first_line: tok.line, tags: Vec::new(), flags: EntryFlags::default(), + main_plies: 0, + all_plies: 0, }); depth = 0; result_seen = false; @@ -213,6 +227,10 @@ pub fn scan_games( TokKind::Comment { terminated } => { movetext_tokens += 1; entry.flags.has_comments = true; + let (from, to) = tok.comment_content(); + if !entry.flags.has_text_comments && has_words(&bytes[from..to.max(from)]) { + entry.flags.has_text_comments = true; + } if !terminated { entry.flags.has_structure_issues = true; } @@ -220,6 +238,7 @@ pub fn scan_games( TokKind::LineComment => { movetext_tokens += 1; entry.flags.has_comments = true; + entry.flags.has_text_comments = true; } TokKind::Escape => {} TokKind::Open => { @@ -252,6 +271,11 @@ pub fn scan_games( if depth == 0 && matches!(w, b"1-0" | b"0-1" | b"1/2-1/2" | b"*") { result_seen = true; lx.allow_tag(); + } else if is_move(w) { + entry.all_plies += 1; + if depth == 0 { + entry.main_plies += 1; + } } } } @@ -265,6 +289,31 @@ pub fn scan_games( Ok(entries) } +/// A word of movetext that is a move: not a move number ("12.", "12..."), with or +/// without the move glued to it ("12.e4"), and not the "e.p." of an en passant capture. +fn is_move(w: &[u8]) -> bool { + let rest = &w[w + .iter() + .position(|c| !c.is_ascii_digit() && *c != b'.') + .unwrap_or(w.len())..]; + !rest.is_empty() && rest != b"e.p." +} + +/// Text in a comment besides commands in square brackets (`[%clk …]`, `[%eval …]`, +/// `[%cal …]`). +fn has_words(text: &[u8]) -> bool { + let mut depth = 0usize; + for &c in text { + match c { + b'[' => depth += 1, + b']' => depth = depth.saturating_sub(1), + c if depth == 0 && !c.is_ascii_whitespace() => return true, + _ => {} + } + } + false +} + #[cfg(test)] mod tests { use super::*; @@ -310,6 +359,22 @@ mod tests { assert_eq!(e[1].black(), Some("Ddd")); } + #[test] + fn main_line_moves_and_text_comments() { + let e = scan(concat!( + "1. e4 { [%clk 0:10:07] } e5 { [%clk 0:10:08] } 2.Nf3 (2. f4 exf4) 2...Nc6 *\n", + "1. d4 { A quiet start. [%eval 0.2] } d5 1-0\n", + "[PlyCount \"81\"] 1. c4 *\n", + )); + assert_eq!(e[0].main_plies, 4); + assert_eq!(e[0].all_plies, 6); + assert_eq!(e[0].moves(), 2); + assert!(e[0].flags.has_comments && !e[0].flags.has_text_comments); + assert!(e[1].flags.has_text_comments); + assert_eq!(e[1].moves(), 1); + assert_eq!(e[2].moves(), 41); + } + #[test] fn cancellation() { let cancel = AtomicBool::new(true); diff --git a/crates/chess-import/src/bench.rs b/crates/chess-import/src/bench.rs index 69cf424..a9071ed 100644 --- a/crates/chess-import/src/bench.rs +++ b/crates/chess-import/src/bench.rs @@ -141,6 +141,19 @@ pub fn run(path: &Path, booster_dir: Option<&Path>, out: &mut dyn Write) -> io:: selected.len(), t.elapsed().as_secs_f64() * 1e3 )?; + let quick = Filter { + text: "carlsen 2020".into(), + ..Filter::default() + }; + let t = Instant::now(); + let found = base + .query(&quick, SortKey::Number, true, &counter, &never) + .map_or(0, |v| v.len()); + writeln!( + out, + "quick search \"carlsen 2020\": {found} games in {:.1} ms", + t.elapsed().as_secs_f64() * 1e3 + )?; let t = Instant::now(); let all = base .query(&Filter::default(), SortKey::White, true, &counter, &never) diff --git a/crates/chess-import/src/chessbase/base.rs b/crates/chess-import/src/chessbase/base.rs index a846e0d..bda5caf 100644 --- a/crates/chess-import/src/chessbase/base.rs +++ b/crates/chess-import/src/chessbase/base.rs @@ -68,7 +68,7 @@ pub struct Base { /// Decoded names of a list, folded copies for searching (see [`fold`]), the /// alphabetical rank of each (for sorting by name) and the number of games of each. -struct Names { +pub(crate) struct Names { shown: Vec, folded: Vec, rank: Vec, @@ -76,7 +76,7 @@ struct Names { } impl Names { - fn new(shown: Vec) -> Names { + pub(crate) fn new(shown: Vec) -> Names { let folded: Vec = shown.iter().map(|s| fold(s)).collect(); let mut order: Vec = (0..folded.len() as u32).collect(); order.sort_by(|&a, &b| folded[a as usize].cmp(&folded[b as usize])); @@ -98,22 +98,22 @@ impl Names { } } - fn count(&mut self, id: u32) { + pub(crate) fn count(&mut self, id: u32) { if let Some(n) = self.games.get_mut(id as usize) { *n += 1; } } - fn get(&self, id: u32) -> &str { + pub(crate) fn get(&self, id: u32) -> &str { self.shown.get(id as usize).map_or("", String::as_str) } - fn rank(&self, id: u32) -> u32 { + pub(crate) fn rank(&self, id: u32) -> u32 { self.rank.get(id as usize).copied().unwrap_or(u32::MAX) } /// Ids whose name contains every word of `query`, as a lookup table. - fn matching(&self, query: &str) -> Vec { + pub(crate) fn matching(&self, query: &str) -> Vec { let words = words(query); self.folded .iter() @@ -123,7 +123,7 @@ impl Names { /// Up to `limit` names containing every word of `query`: names starting with /// the first word first, then by number of games. Also the number of matches. - fn suggest(&self, query: &str, limit: usize) -> (Vec, usize) { + pub(crate) fn suggest(&self, query: &str, limit: usize) -> (Vec, usize) { let words = words(query); if words.is_empty() { return (Vec::new(), 0); @@ -179,6 +179,8 @@ pub fn fold(s: &str) -> String { 'ç' | 'ć' | 'ĉ' | 'ċ' | 'č' => "c", 'ď' | 'đ' | 'ð' => "d", 'è'..='ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => "e", + // «Артём» is typed «Артем». + 'ё' => "е", 'ĝ' | 'ğ' | 'ġ' | 'ģ' => "g", 'ĥ' | 'ħ' => "h", 'ì'..='ï' | 'ĩ' | 'ī' | 'ĭ' | 'į' | 'ı' => "i", @@ -208,7 +210,7 @@ pub fn fold(s: &str) -> String { } /// Folded words of a search query; commas separate words too ("Carlsen, M"). -fn words(query: &str) -> Vec { +pub(crate) fn words(query: &str) -> Vec { fold(query) .split(|c: char| c.is_whitespace() || c == ',') .filter(|w| !w.is_empty()) @@ -329,6 +331,9 @@ pub struct Filter { pub with_variations: bool, /// Leave guiding texts out. pub games_only: bool, + /// The quick search: every word in some field of the game — a player, the + /// tournament (title, place, year), the annotator, the ECO code, the date. + pub text: String, } /// ECO ranges of a filter: codes ("B90"), prefixes ("B9" = B90-B99, "B" = B00-B99) @@ -1000,6 +1005,27 @@ impl Base { ids.as_ref() .is_none_or(|t| t.get(id as usize).copied().unwrap_or(false)) }; + // The quick search, word by word: the names it is in. + let quick: Vec = words(&filter.text) + .into_iter() + .map(|w| QuickWord { + players: self.players.matching(&w), + events: self.tournaments.matching(&w), + annotators: (0..self.annotators.len() as u32) + .map(|id| { + fold(&self.annotators.name(id, &self.decoder).unwrap_or_default()) + .contains(w.as_str()) + }) + .collect(), + // A record's year has 12 bits and its ECO 500 values: tables, not text. + years: (0..4096u32) + .map(|y| y > 0 && y.to_string().contains(w.as_str())) + .collect(), + ecos: (0..500u16) + .map(|c| fold(&eco_text(c)).contains(w.as_str())) + .collect(), + }) + .collect(); let names = player_ids.is_some() || opponent_ids.is_some(); let game_only_conditions = names || filter.year_from.is_some() @@ -1028,10 +1054,15 @@ impl Base { } if kind & 0x02 != 0 { // A guiding text: only the tournament and the annotator apply. + // The quick search looks in its tournament and annotator. + let at = |t: &Vec, id: u32| t.get(id as usize).copied().unwrap_or(false); if !filter.games_only && !game_only_conditions && has(&event_ids, u(0x07, 3)) && has(&annotator_ids, u(0x0d, 3)) + && quick + .iter() + .all(|q| at(&q.events, u(0x07, 3)) || at(&q.annotators, u(0x0d, 3))) { out.push(i as u32); } @@ -1121,6 +1152,22 @@ impl Base { { continue; } + if !quick.is_empty() { + let year = (u(0x18, 3) >> 9) & 0xfff; + let eco = eco_number(u(0x23, 2) as u16); + let found = quick.iter().all(|q| { + let at = |t: &Vec, id: u32| t.get(id as usize).copied().unwrap_or(false); + at(&q.players, white) + || at(&q.players, black) + || at(&q.events, u(0x0f, 3)) + || at(&q.annotators, u(0x12, 3)) + || eco.is_some_and(|c| at(&q.ecos, u32::from(c))) + || at(&q.years, year) + }); + if !found { + continue; + } + } out.push(i as u32); } scanned.store(self.records, Ordering::Relaxed); @@ -1194,8 +1241,24 @@ impl Base { } } +/// A word of the quick search and the names it is in. +struct QuickWord { + players: Vec, + events: Vec, + annotators: Vec, + /// Years (0–4095) whose number holds the word. + years: Vec, + /// ECO codes (0 = A00 … 499 = E99) that hold it. + ecos: Vec, +} + +/// 190 → "B90". +pub(crate) fn eco_text(code: u16) -> String { + format!("{}{:02}", char::from(b'A' + (code / 100) as u8), code % 100) +} + /// Ids matching a name filter (`None`: no condition). -fn name_table(names: &Names, f: &NameFilter) -> Option> { +pub(crate) fn name_table(names: &Names, f: &NameFilter) -> Option> { if let Some(id) = f.exact { let mut t = vec![false; names.shown.len()]; if let Some(x) = t.get_mut(id as usize) { diff --git a/crates/chess-import/src/lib.rs b/crates/chess-import/src/lib.rs index 64f1460..6a37c4c 100644 --- a/crates/chess-import/src/lib.rs +++ b/crates/chess-import/src/lib.rs @@ -12,6 +12,7 @@ pub mod bench; pub mod cbv; pub mod chessbase; pub mod memory; +pub mod pgn_catalog; pub mod pgn_positions; pub mod position; @@ -95,6 +96,8 @@ pub const LARGE_CHESSBASE: u64 = 20_000; pub struct PgnDb { pub db: PgnDatabase, positions: Mutex>>, + /// The filters' index of the tags, built on first use. + catalog: std::sync::OnceLock>, } impl PgnDb { @@ -102,14 +105,28 @@ impl PgnDb { PgnDb { db, positions: Mutex::new(None), + catalog: std::sync::OnceLock::new(), } } - /// Memory the position table would need, built: about 20 bytes per position - /// and, while it is built, two to three times that (`docs/dev/import.md`), - /// estimated from the size of the PGN text (a move is some six bytes of it). + /// The filters' index of the games' tags (see [`pgn_catalog`]). + pub fn catalog(&self) -> &pgn_catalog::Catalog { + self.catalog + .get_or_init(|| Box::new(pgn_catalog::Catalog::build(self.db.entries()))) + } + + /// Memory the position table would need while it is built: about 20 bytes per + /// position, and two to three times that during the build (`docs/dev/import.md`). + /// Counted from the moves of the games (variations included): the size of the text + /// says little when every move carries a clock comment. pub fn positions_estimate(&self) -> u64 { - self.db.byte_len() as u64 * 10 + let positions: u64 = self + .db + .entries() + .iter() + .map(|e| u64::from(e.all_plies) + 1) + .sum(); + positions * 20 * 3 } /// Why the position table cannot be built now: the memory it would need @@ -251,6 +268,126 @@ impl Database { } } + /// Games (not guiding texts). + pub fn games(&self) -> usize { + match self { + Database::Pgn(db) => db.len(), + Database::ChessBase(b) => b.games(), + } + } + + /// Guiding texts (only ChessBase databases have them). + pub fn texts(&self) -> usize { + match self { + Database::Pgn(_) => 0, + Database::ChessBase(b) => b.texts(), + } + } + + /// The table row of record `index`. + pub fn row(&self, index: usize) -> chessbase::base::Row { + match self { + Database::Pgn(db) => db + .entries() + .get(index) + .map(|e| pgn_catalog::Catalog::row(e, e.moves())) + .unwrap_or_default(), + Database::ChessBase(b) => b.row(index), + } + } + + /// Records that pass `filter`, sorted; `None` when cancelled. + pub fn query( + &self, + filter: &chessbase::base::Filter, + sort: chessbase::base::SortKey, + ascending: bool, + scanned: &AtomicUsize, + cancel: &AtomicBool, + ) -> Option> { + match self { + Database::Pgn(db) => { + db.catalog() + .query(db.entries(), filter, sort, ascending, scanned, cancel) + } + Database::ChessBase(b) => b.query(filter, sort, ascending, scanned, cancel), + } + } + + pub fn sort_records( + &self, + records: &mut Vec, + sort: chessbase::base::SortKey, + ascending: bool, + ) { + match self { + Database::Pgn(db) => db.catalog().sort_records(records, sort, ascending), + Database::ChessBase(b) => b.sort_records(records, sort, ascending), + } + } + + pub fn suggest_players( + &self, + query: &str, + limit: usize, + ) -> (Vec, usize) { + match self { + Database::Pgn(db) => db.catalog().suggest_players(query, limit), + Database::ChessBase(b) => b.suggest_players(query, limit), + } + } + + pub fn suggest_events( + &self, + query: &str, + limit: usize, + ) -> (Vec, usize) { + match self { + Database::Pgn(db) => db.catalog().suggest_events(query, limit), + Database::ChessBase(b) => b.suggest_events(query, limit), + } + } + + /// Most games have no result: a book of chapters (continuations count chapters). + pub fn books(&self) -> bool { + match self { + Database::Pgn(db) => db.catalog().books(), + Database::ChessBase(_) => false, + } + } + + /// The record could not be read cleanly (structure or encoding problems). + pub fn damaged(&self, index: usize) -> bool { + match self { + Database::Pgn(db) => db + .entries() + .get(index) + .is_some_and(|e| e.flags.has_structure_issues || e.flags.has_decode_errors), + Database::ChessBase(_) => false, + } + } + + /// The position search is ready (a PGN database builds its table on first use). + pub fn positions_ready(&self) -> bool { + match self { + Database::Pgn(db) => db.positions.lock().is_ok_and(|t| t.is_some()), + Database::ChessBase(_) => true, + } + } + + /// Which fields at least one game has (ChessBase databases: all of them). + pub fn filled(&self) -> pgn_catalog::Filled { + match self { + Database::Pgn(db) => db.catalog().filled(), + Database::ChessBase(_) => pgn_catalog::Filled { + eco: true, + annotator: true, + elo: true, + year: true, + }, + } + } + pub fn as_chessbase(&self) -> Option<&Base> { match self { Database::ChessBase(b) => Some(b), diff --git a/crates/chess-import/src/pgn_catalog.rs b/crates/chess-import/src/pgn_catalog.rs new file mode 100644 index 0000000..cc88f8d --- /dev/null +++ b/crates/chess-import/src/pgn_catalog.rs @@ -0,0 +1,827 @@ +//! The game list of a PGN database with the filters, sorting and name suggestions of a +//! ChessBase database ([`crate::chessbase::base`]): built from the tags read when the +//! file was opened, so a filter is a pass over a few arrays in memory. Fields a file +//! does not have (no ECO, no Annotator) simply match nothing when filtered on. + +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +use chess_core::pgn::GameEntry; + +use crate::chessbase::base::{ + EloRule, Filter, Names, Outcome, RecordKind, Row, Side, SortKey, Suggestion, fold, name_table, + words, +}; + +/// What a filter and a sort need of each game, one array per field. +pub struct Catalog { + players: Names, + events: Names, + white: Vec, + black: Vec, + event: Vec, + /// Folded `Annotator` tags. + annotator: Vec, + /// `yyyymmdd` with unknown parts 0; 0 for no date. + date: Vec, + /// When the game was played, for sorting: `yyyymmdd` × 100 000 + seconds of the day + /// (`UTCDate` and `UTCTime` when both are there, as online games have them). + when: Vec, + white_elo: Vec, + black_elo: Vec, + result: Vec, + /// ECO as a number 0 (A00) … 499 (E99). + eco: Vec>, + moves: Vec, + comments: Vec, + variations: Vec, + /// Which fields at least one game has (an empty result says so, §9.8). + filled: Filled, + /// Most games have no result: a book, whose continuations count chapters. + books: bool, +} + +/// Fields at least one game of the database has. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Filled { + pub eco: bool, + pub annotator: bool, + pub elo: bool, + pub year: bool, +} + +/// "2026.10.18", "2026-10-18", "2026/10/18", "1997.05.??", "2010" → yyyymmdd (unknown +/// parts 0); 0 without a year. +pub fn date_number(date: &str) -> u32 { + let mut parts = date.trim().split(['.', '-', '/']); + let num = |s: Option<&str>, max: u32| -> u32 { + s.filter(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit())) + .and_then(|s| s.parse::().ok()) + .filter(|n| *n <= max) + .unwrap_or(0) + }; + let year = num(parts.next(), 9999); + if !(1..=9999).contains(&year) { + return 0; + } + year * 10000 + num(parts.next(), 12) * 100 + num(parts.next(), 31) +} + +/// "13:05:09" → seconds of the day. +fn seconds(time: &str) -> Option { + let mut parts = time.trim().split(':').map(|p| p.parse::().ok()); + let (h, m, s) = ( + parts.next()??, + parts.next()??, + parts.next().flatten().unwrap_or(0), + ); + (h < 24 && m < 60 && s < 61).then_some(h * 3600 + m * 60 + s) +} + +/// "2026-10-18" → "2026.10.18": the PGN way, as the table shows dates. +fn pgn_date(date: &str) -> String { + date.trim().replace(['-', '/'], ".") +} + +/// "B90", "b90a", "B90 Sicilian" → 190 (A00 = 0 … E99 = 499): the first three +/// characters. +fn eco_of(tag: &str) -> Option { + let t = tag.trim().as_bytes(); + let t = t.get(..3)?; + if !(b'A'..=b'E').contains(&t[0].to_ascii_uppercase()) || !t[1..].iter().all(u8::is_ascii_digit) + { + return None; + } + Some( + u16::from(t[0].to_ascii_uppercase() - b'A') * 100 + + u16::from(t[1] - b'0') * 10 + + u16::from(t[2] - b'0'), + ) +} + +fn outcome(result: Option<&str>) -> Outcome { + match result.map(str::trim) { + Some("1-0") => Outcome::WhiteWins, + Some("0-1") => Outcome::BlackWins, + Some("1/2-1/2" | "½-½") => Outcome::Draw, + _ => Outcome::Unknown, + } +} + +/// A name the way a list shows it, spaces squeezed; none for "?", "-" and "" (PGN's +/// unknown). +fn known(name: Option<&str>) -> String { + let n = name + .unwrap_or("") + .split_whitespace() + .collect::>() + .join(" "); + if n == "?" || n == "-" { + String::new() + } else { + n + } +} + +/// When the game was played as yyyymmdd: `Date`, or `UTCDate` when `Date` has no year. +fn game_date(e: &GameEntry) -> u32 { + let d = date_number(e.date().unwrap_or("")); + if d / 10000 > 0 { + d + } else { + date_number(e.tag("UTCDate").unwrap_or("")) + } +} + +/// The place of a game, from `Site`: not "?", not a link (Lichess and Chess.com put the +/// game's address there). +fn place(e: &GameEntry) -> String { + let site = known(e.tag("Site")); + if site.contains("://") { + String::new() + } else { + site + } +} + +/// A tournament as ChessBase names it: "Title (place) year", the place and the year +/// only when the title does not have them already. +fn event_name(e: &GameEntry) -> String { + let title = known(e.event()); + let place = place(e); + let mut name = if !place.is_empty() && !title.contains(&place) { + if title.is_empty() { + place + } else { + format!("{title} ({place})") + } + } else { + title + }; + if name.is_empty() { + return name; + } + let year = game_date(e) / 10000; + if year > 0 && !name.contains(&year.to_string()) { + name = format!("{name} {year}"); + } + name +} + +/// Ids of the distinct names, in first-seen order, and each game's id. +fn intern(values: impl Iterator) -> (Vec, Vec) { + let mut ids = std::collections::HashMap::new(); + let mut shown = Vec::new(); + let of = values + .map(|v| { + *ids.entry(v.clone()).or_insert_with(|| { + shown.push(v); + shown.len() as u32 - 1 + }) + }) + .collect(); + (shown, of) +} + +impl Catalog { + pub fn build(entries: &[GameEntry]) -> Catalog { + // White and Black share one list: a player is the same whichever colour. + let (names, ids) = intern( + entries + .iter() + .flat_map(|e| [known(e.white()), known(e.black())]), + ); + let white: Vec = ids.iter().step_by(2).copied().collect(); + let black: Vec = ids.iter().skip(1).step_by(2).copied().collect(); + let mut players = Names::new(names); + for &id in &ids { + players.count(id); + } + let (event_names, event) = intern(entries.iter().map(event_name)); + let mut events = Names::new(event_names); + for &id in &event { + events.count(id); + } + let elo = |v: Option| v.and_then(|v| u16::try_from(v).ok()).unwrap_or(0); + let date: Vec = entries.iter().map(game_date).collect(); + let when: Vec = entries + .iter() + .zip(&date) + .map( + |(e, &d)| match (e.tag("UTCDate"), e.tag("UTCTime").and_then(seconds)) { + (Some(u), Some(t)) if date_number(u) > 0 => { + u64::from(date_number(u)) * 100_000 + u64::from(t) + } + _ => u64::from(d) * 100_000, + }, + ) + .collect(); + let decided = entries + .iter() + .filter(|e| outcome(e.result()) != Outcome::Unknown) + .count(); + let eco: Vec> = entries.iter().map(|e| e.eco().and_then(eco_of)).collect(); + let annotator: Vec = entries + .iter() + .map(|e| fold(e.tag("Annotator").unwrap_or(""))) + .collect(); + let white_elo: Vec = entries.iter().map(|e| elo(e.white_elo())).collect(); + let black_elo: Vec = entries.iter().map(|e| elo(e.black_elo())).collect(); + let filled = Filled { + eco: eco.iter().any(Option::is_some), + annotator: annotator.iter().any(|a| !a.trim().is_empty()), + elo: white_elo.iter().chain(&black_elo).any(|&e| e > 0), + year: date.iter().any(|&d| d / 10000 > 0), + }; + Catalog { + players, + events, + white, + black, + event, + annotator, + date, + when, + books: decided * 2 < entries.len(), + white_elo, + black_elo, + result: entries.iter().map(|e| outcome(e.result())).collect(), + eco, + moves: entries + .iter() + .map(|e| u16::try_from(e.moves()).unwrap_or(u16::MAX)) + .collect(), + comments: entries.iter().map(|e| e.flags.has_text_comments).collect(), + variations: entries.iter().map(|e| e.flags.has_variations).collect(), + filled, + } + } + + /// Which fields at least one game has. + pub fn filled(&self) -> Filled { + self.filled + } + + /// Most games have no result (a book of chapters). + pub fn books(&self) -> bool { + self.books + } + + pub fn suggest_players(&self, query: &str, limit: usize) -> (Vec, usize) { + self.players.suggest(query, limit) + } + + pub fn suggest_events(&self, query: &str, limit: usize) -> (Vec, usize) { + self.events.suggest(query, limit) + } + + pub fn player_name(&self, id: u32) -> &str { + self.players.get(id) + } + + pub fn event_name(&self, id: u32) -> &str { + self.events.get(id) + } + + /// The table row of game `index`. + pub fn row(entry: &GameEntry, moves: u32) -> Row { + Row { + kind: Some(RecordKind::Game), + white: known(entry.white()), + black: known(entry.black()), + white_elo: entry + .white_elo() + .and_then(|v| u16::try_from(v).ok()) + .unwrap_or(0), + black_elo: entry + .black_elo() + .and_then(|v| u16::try_from(v).ok()) + .unwrap_or(0), + result: match outcome(entry.result()) { + Outcome::WhiteWins => "1-0", + Outcome::BlackWins => "0-1", + Outcome::Draw => "1/2-1/2", + Outcome::Unknown => "*", + }, + eco: entry + .eco() + .and_then(eco_of) + .map(crate::chessbase::base::eco_text), + chess960: entry.tag("Variant").is_some_and(|v| v.contains("960")), + event: known(entry.event()), + site: known(entry.tag("Site")), + date: pgn_date(if date_number(entry.date().unwrap_or("")) / 10000 > 0 { + entry.date().unwrap_or("") + } else { + entry.tag("UTCDate").unwrap_or("") + }), + round: known(entry.tag("Round")), + annotator: entry.tag("Annotator").unwrap_or("").trim().to_owned(), + moves: u8::try_from(moves).unwrap_or(u8::MAX), + has_variations: entry.flags.has_variations, + has_comments: entry.flags.has_text_comments, + title: String::new(), + } + } + + /// Indices of the games that pass `filter`, sorted (see `Base::query`). + pub fn query( + &self, + entries: &[GameEntry], + filter: &Filter, + sort: SortKey, + ascending: bool, + scanned: &AtomicUsize, + cancel: &AtomicBool, + ) -> Option> { + let player_ids = name_table(&self.players, &filter.player); + let opponent_ids = name_table(&self.players, &filter.opponent); + let event_ids = name_table(&self.events, &filter.event); + let annotator = words(&filter.annotator); + // The quick search, word by word: the names it is in; the place, ECO and date of + // a game are looked at only when no name has the word. + let quick: Vec<(String, Vec, Vec)> = words(&filter.text) + .into_iter() + .map(|w| { + let (p, e) = (self.players.matching(&w), self.events.matching(&w)); + (w, p, e) + }) + .collect(); + let has = |ids: &Option>, id: u32| { + ids.as_ref() + .is_none_or(|t| t.get(id as usize).copied().unwrap_or(false)) + }; + let names = player_ids.is_some() || opponent_ids.is_some(); + let relative = filter.player_relative && player_ids.is_some(); + let mut out = Vec::new(); + for i in 0..self.white.len() { + if i % 65536 == 0 { + if cancel.load(Ordering::Relaxed) { + return None; + } + scanned.store(i, Ordering::Relaxed); + } + let (white, black) = (self.white[i], self.black[i]); + let mut player_white = true; + let mut player_black = true; + if names { + let as_white = has(&player_ids, white) && has(&opponent_ids, black); + let as_black = has(&player_ids, black) && has(&opponent_ids, white); + player_white = as_white && filter.side != Side::Black; + player_black = as_black && filter.side != Side::White; + if !player_white && !player_black { + continue; + } + } + if !has(&event_ids, self.event[i]) + || !annotator + .iter() + .all(|w| self.annotator[i].contains(w.as_str())) + { + continue; + } + if filter.year_from.is_some() || filter.year_to.is_some() { + let year = self.date[i] / 10000; + if year == 0 + || filter.year_from.is_some_and(|y| year < u32::from(y)) + || filter.year_to.is_some_and(|y| year > u32::from(y)) + { + continue; + } + } + if let Some(min) = filter.elo_min { + let (we, bl) = (self.white_elo[i], self.black_elo[i]); + let ok = match filter.elo_rule { + EloRule::Both => we >= min && bl >= min, + EloRule::Either => we >= min || bl >= min, + EloRule::Average => { + we > 0 && bl > 0 && (u32::from(we) + u32::from(bl)) / 2 >= u32::from(min) + } + EloRule::Opponent if player_ids.is_some() => { + (player_white && bl >= min) || (player_black && we >= min) + } + EloRule::Opponent => we >= min || bl >= min, + }; + if !ok { + continue; + } + } + if !filter.eco.is_empty() { + let Some(code) = self.eco[i] else { continue }; + if !filter.eco.iter().any(|&(a, b)| (a..=b).contains(&code)) { + continue; + } + } + if !filter.outcomes.is_empty() { + let board = self.result[i]; + let wanted = |o: Outcome| filter.outcomes.contains(&o); + let ok = if relative && matches!(board, Outcome::WhiteWins | Outcome::BlackWins) { + // WhiteWins = the player won, BlackWins = the player lost. + let flipped = match board { + Outcome::WhiteWins => Outcome::BlackWins, + _ => Outcome::WhiteWins, + }; + (player_white && wanted(board)) || (player_black && wanted(flipped)) + } else { + wanted(board) + }; + if !ok { + continue; + } + } + let moves = self.moves[i]; + if filter.moves_from.is_some_and(|m| moves < m) + || filter.moves_to.is_some_and(|m| moves > m) + { + continue; + } + if (filter.with_comments && !self.comments[i]) + || (filter.with_variations && !self.variations[i]) + { + continue; + } + if !quick.is_empty() { + let at = |t: &Vec, id: u32| t.get(id as usize).copied().unwrap_or(false); + let e = entries.get(i); + let found = quick.iter().all(|(w, players, events)| { + at(players, white) + || at(players, black) + || at(events, self.event[i]) + || self.annotator[i].contains(w.as_str()) + || e.is_some_and(|e| { + ["Site", "ECO", "Date", "UTCDate"] + .iter() + .any(|t| e.tag(t).is_some_and(|v| fold(v).contains(w.as_str()))) + }) + }); + if !found { + continue; + } + } + out.push(i as u32); + } + scanned.store(self.white.len(), Ordering::Relaxed); + self.sort_records(&mut out, sort, ascending); + Some(out) + } + + /// Sorts game indices (in file order on entry) by `sort`; games without a value + /// (no rating, no date) stay at the end in both directions. + pub fn sort_records(&self, records: &mut Vec, sort: SortKey, ascending: bool) { + if sort == SortKey::Number { + records.sort_unstable(); + } else { + let mut keyed: Vec<(u64, u32)> = records + .iter() + .map(|&i| (self.sort_key(i as usize, sort), i)) + .collect(); + keyed.sort_unstable(); + *records = keyed.into_iter().map(|(_, i)| i).collect(); + } + if !ascending { + let split = records + .iter() + .position(|&i| self.sort_key(i as usize, sort) == u64::MAX) + .unwrap_or(records.len()); + records[..split].reverse(); + } + } + + fn sort_key(&self, i: usize, sort: SortKey) -> u64 { + let none_if_zero = |v: u32| if v == 0 { u64::MAX } else { u64::from(v) }; + match sort { + SortKey::Number => i as u64, + SortKey::White => self.players.rank(self.white[i]).into(), + SortKey::Black => self.players.rank(self.black[i]).into(), + SortKey::WhiteElo => none_if_zero(self.white_elo[i].into()), + SortKey::BlackElo => none_if_zero(self.black_elo[i].into()), + SortKey::Result => match self.result[i] { + Outcome::WhiteWins => 0, + Outcome::Draw => 1, + Outcome::BlackWins => 2, + Outcome::Unknown => u64::MAX, + }, + SortKey::Moves => none_if_zero(self.moves[i].into()), + SortKey::Eco => self.eco[i].map_or(u64::MAX, u64::from), + SortKey::Event => self.events.rank(self.event[i]).into(), + SortKey::Date => { + if self.when[i] == 0 { + u64::MAX + } else { + self.when[i] + } + } + SortKey::AverageElo => { + let (w, b) = (u64::from(self.white_elo[i]), u64::from(self.black_elo[i])); + if w == 0 || b == 0 { + u64::MAX + } else { + // The average first, then the date. + (((w + b) / 2) << 32) | u64::from(self.date[i]) + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::chessbase::base::NameFilter; + use chess_core::pgn::scan_games; + + fn catalog(pgn: &str) -> (Vec, Catalog) { + let e = scan_games( + pgn.as_bytes(), + chess_core::TextEncoding::Utf8, + &mut |_| {}, + &AtomicBool::new(false), + ) + .unwrap(); + let c = Catalog::build(&e); + (e, c) + } + + fn find(e: &[GameEntry], c: &Catalog, f: &Filter) -> Vec { + c.query( + e, + f, + SortKey::Number, + true, + &AtomicUsize::new(0), + &AtomicBool::new(false), + ) + .unwrap() + } + + fn name(t: &str) -> NameFilter { + NameFilter { + text: t.into(), + exact: None, + } + } + + const GAMES: &str = concat!( + "[Event \"Рапид 42, до 11 лет\"][Date \"2026-10-18\"][White \"Вафин Радель\"][WhiteElo \"1887\"]", + "[Black \"Макаров Артём\"][BlackElo \"1542\"][Result \"1-0\"]\n1. e4 { [%clk 0:10:07] } c5 2. Nf3 1-0\n", + "[Event \"Блиц\"][Site \"Москва\"][Date \"2024.05.??\"][White \"Макаров Артём\"][WhiteElo \"1600\"]", + "[Black \"Hübner, Robert\"][BlackElo \"2600\"][Result \"0-1\"][ECO \"B90a\"]\n1. e4 { A long fight. } c5 (1... e5) 0-1\n", + "[Event \"Rated Blitz game\"][Site \"https://lichess.org/abc\"][Date \"????.??.??\"][UTCDate \"2023.01.02\"]", + "[White \"?\"][Black \"-\"][Result \"½-½\"]\n1. d4 1/2-1/2\n", + ); + + #[test] + fn names_events_and_sides() { + let (e, c) = catalog(GAMES); + assert_eq!( + find( + &e, + &c, + &Filter { + player: name("макаров"), + ..Filter::default() + } + ), + vec![0, 1] + ); + assert_eq!( + find( + &e, + &c, + &Filter { + player: name("макаров"), + side: Side::White, + ..Filter::default() + } + ), + vec![1] + ); + assert_eq!( + find( + &e, + &c, + &Filter { + player: name("hubner"), + ..Filter::default() + } + ), + vec![1] + ); + // «Артём» is typed «Артем»; the order of the words does not matter. + assert_eq!( + find( + &e, + &c, + &Filter { + player: name("артем, макаров"), + ..Filter::default() + } + ), + vec![0, 1] + ); + // Spaces squeezed: «Вафин Радель» is one name. + assert_eq!(c.suggest_players("вафин", 5).0[0].name, "Вафин Радель"); + // "?" and "-" are no player. + assert_eq!(c.suggest_players("?", 5).1, 0); + // Tournaments as ChessBase names them; a link in Site is no place. + assert_eq!(c.suggest_events("блиц", 5).0[0].name, "Блиц (Москва) 2024"); + assert_eq!( + c.suggest_events("rated", 5).0[0].name, + "Rated Blitz game 2023" + ); + assert_eq!( + find( + &e, + &c, + &Filter { + event: name("рапид 2026"), + ..Filter::default() + } + ), + vec![0] + ); + let (list, total) = c.suggest_players("макар", 5); + assert_eq!(total, 1); + assert_eq!(list[0].games, 2); + } + + #[test] + fn years_ratings_results_eco_moves_and_comments() { + let (e, c) = catalog(GAMES); + assert_eq!( + find( + &e, + &c, + &Filter { + year_from: Some(2025), + ..Filter::default() + } + ), + vec![0] + ); + // The year from UTCDate when Date has none. + assert_eq!( + find( + &e, + &c, + &Filter { + year_to: Some(2023), + ..Filter::default() + } + ), + vec![2] + ); + assert_eq!( + find( + &e, + &c, + &Filter { + elo_min: Some(1550), + ..Filter::default() + } + ), + vec![1] + ); + assert_eq!( + find( + &e, + &c, + &Filter { + elo_min: Some(2000), + elo_rule: EloRule::Either, + ..Filter::default() + } + ), + vec![1] + ); + assert_eq!( + find( + &e, + &c, + &Filter { + outcomes: vec![Outcome::Draw], + ..Filter::default() + } + ), + vec![2] + ); + assert_eq!( + find( + &e, + &c, + &Filter { + eco: vec![(190, 199)], + ..Filter::default() + } + ), + vec![1] + ); + assert_eq!( + find( + &e, + &c, + &Filter { + moves_from: Some(2), + ..Filter::default() + } + ), + vec![0] + ); + // A clock is no comment. + assert_eq!( + find( + &e, + &c, + &Filter { + with_comments: true, + ..Filter::default() + } + ), + vec![1] + ); + assert_eq!( + find( + &e, + &c, + &Filter { + with_variations: true, + ..Filter::default() + } + ), + vec![1] + ); + assert_eq!( + c.filled(), + Filled { + eco: true, + annotator: false, + elo: true, + year: true + } + ); + } + + #[test] + fn quick_search_finds_each_word_in_some_field() { + let (e, c) = catalog(GAMES); + let text = |t: &str| Filter { + text: t.into(), + ..Filter::default() + }; + assert_eq!(find(&e, &c, &text("макаров 2024")), vec![1]); + assert_eq!(find(&e, &c, &text("москва b90")), vec![1]); + assert_eq!(find(&e, &c, &text("lichess")), vec![2]); + assert_eq!(find(&e, &c, &text("вафин блиц")), Vec::::new()); + } + + #[test] + fn sorting_and_rows() { + let (e, c) = catalog(GAMES); + let mut v = vec![0, 1, 2]; + c.sort_records(&mut v, SortKey::WhiteElo, false); + assert_eq!(v, vec![0, 1, 2]); + c.sort_records(&mut v, SortKey::WhiteElo, true); + // No rating: last in both directions. + assert_eq!(v, vec![1, 0, 2]); + c.sort_records(&mut v, SortKey::Date, true); + assert_eq!(v, vec![2, 1, 0]); + let r = Catalog::row(&e[0], e[0].moves()); + assert_eq!(r.date, "2026.10.18"); + assert_eq!(r.result, "1-0"); + assert!(!r.has_comments); + assert_eq!(Catalog::row(&e[1], 1).eco.as_deref(), Some("B90")); + let r = Catalog::row(&e[2], 1); + assert_eq!( + ( + r.white.as_str(), + r.black.as_str(), + r.result, + r.date.as_str() + ), + ("", "", "1/2-1/2", "2023.01.02") + ); + } + + #[test] + fn downloaded_games_by_the_time_they_were_played() { + // As a download writes them: one site's games oldest first, then the other's; + // two games of one day differ by their time. + let (_, c) = catalog(concat!( + "[UTCDate \"2026.01.01\"][UTCTime \"10:00:00\"] 1. e4 *\n", + "[UTCDate \"2026.03.01\"][UTCTime \"09:00:00\"] 1. d4 *\n", + "[UTCDate \"2026.03.01\"][UTCTime \"21:30:00\"] 1. c4 *\n", + "[UTCDate \"2026.02.01\"][UTCTime \"10:00:00\"] 1. Nf3 *\n", + )); + let mut v = vec![0, 1, 2, 3]; + c.sort_records(&mut v, SortKey::Date, false); + assert_eq!(v, vec![2, 1, 3, 0]); + } + + #[test] + fn dates() { + assert_eq!(date_number("2026-10-18"), 20261018); + assert_eq!(date_number("1997.05.??"), 19970500); + assert_eq!(date_number("2010"), 20100000); + assert_eq!(date_number("????.??.??"), 0); + assert_eq!(date_number(""), 0); + } +} diff --git a/docs/design/board-search.md b/docs/design/board-search.md index 027a5ac..8c22ff7 100644 --- a/docs/design/board-search.md +++ b/docs/design/board-search.md @@ -98,8 +98,8 @@ ``` - **Большая база — строка есть всегда**, даже без условий (тогда слабым текстом «Условий нет — показаны все партии»). Место зарезервировано, поэтому первый ход или первый фильтр не сдвигает таблицу вниз. -- **Малая база — строка есть только при открытой доске** (там одно поле поиска, а постоянная пустая строка — потеря 26 точек из 434 на минимальном окне). -- Порядок чипов **фиксированный**, а не по времени добавления (чипы не прыгают): Позиция → Игрок → Соперник → Турнир → Комментатор → Годы → Эло → Результат → ECO → Ходов → Аннотации → (малая база) Поиск. +- ~~**Малая база — строка есть только при открытой доске**~~ — с 2026-10-23 у всех баз один экран (LD §9), строка условий есть всегда. +- Порядок чипов **фиксированный**, а не по времени добавления (чипы не прыгают): Позиция → Поиск → Игрок → Соперник → Турнир → Комментатор → Годы → Эло → Результат → ECO → Ходов → Аннотации (с 2026-10-23 «Поиск» — у всех баз, сразу после позиции, LD §9.2). - Чип: `Frame` со скруглением 4, фон — слабая заливка, текст 13, `×` — маленькая кнопка 16×16 справа внутри. Щелчок по `×` — снять условие сразу. Щелчок по тексту чипа — перейти к условию: «Позиция» → `[Доска]`; остальные → `[Фильтры]` с фокусом в соответствующем поле. - Текст чипа «Позиция»: до 8 полуходов — сама линия («Позиция: 1.e4 c5 2.Nf3 d6»); длиннее — «Позиция после 14…Nf6». Tooltip — вся линия и **мини-доска 160×160** (неинтерактивная отрисовка `board.rs`), чтобы условие было видно в режиме «Фильтры». - Если включено «только этот порядок» — «Ходы: 1.e4 c5 2.Nf3 d6 (точно этот порядок) ×». @@ -382,6 +382,8 @@ ### 4.11. Малая база (книга) +> **Заменено 2026-10-23 разделом 9 `large-databases.md`:** PGN и переведённые базы получают тот же экран, что ChessBase (`[Фильтры | Доска]`, панель, строка условий всегда). Отдельной кнопки `[Доска]` у малых баз больше нет. Поиск в вариантах (⑂/🔀), открытие на найденном узле и «N глав» в продолжениях книг остаются (LD §9.9). Ниже — исходный текст для истории. + - Справа в шапке, после поля поиска, — кнопка-переключатель `[Доска]` (для малых баз панели фильтров нет, сегмента «Фильтры» тоже). - Поле поиска и позиция сочетаются по И. Текст поиска при открытой доске дублируется чипом «Поиск: carlsen ×». - Поиск **и в вариантах**. Партия считается один раз; если позиция есть и в основной линии, и в варианте — берётся основная линия, иначе первое вхождение в порядке текста. «⑂» в колонке «Ход». diff --git a/docs/design/large-databases.md b/docs/design/large-databases.md index d716de7..80c30be 100644 --- a/docs/design/large-databases.md +++ b/docs/design/large-databases.md @@ -4,6 +4,8 @@ Эталонная нагрузка — Mega Database 2026: 11 741 260 записей, 479 тыс. игроков, 109 тыс. турниров, 1 823 текстовые главы. +**Обновление 2026-10-23 (раздел 9).** Владелец решил: у PGN те же фильтры и поиск по позиции, что у ChessBase, «идентично как с базами от chessbase», — один экран для всех баз. Быстрый текстовый поиск PGN остаётся и становится частью этого экрана у всех баз. Деление на «малый» и «большой» режим (раздел 0) больше не определяет экран: оно остаётся только техническим (как база читается — по индексу `.cbh` или в память). Где разделы 0–8 говорят о «малом режиме», действует раздел 9. + ## 0. Главная задача экрана и критерий «большой базы» Для книги (сотни партий) задача экрана — «пролистать и открыть». Для Mega — «сузить 11,7 млн до десятков и открыть». Поэтому в большой базе главный элемент — не таблица, а связка «фильтры → счётчик → таблица». Приоритет информации в шапке: сколько найдено из скольких → идёт ли поиск → имя базы и «только чтение». @@ -17,15 +19,15 @@ - Число записей известно сразу (размер `.cbh` / 46), до чтения справочников, поэтому режим выбирается до начала загрузки и экран загрузки уже правильный. - 20 000 — одна константа; книги и учебные базы (≤ 5 000) гарантированно остаются в малом режиме, а базы турниров/дебютов на 50–500 тыс. уже выигрывают от панели. Точное значение — по замеру разработчика: порог там, где конвертация в PGN начинает заметно тормозить открытие (> ~2 с). -- Большие PGN (lichess-выгрузки) в этой версии остаются в малом режиме; панель спроектирована так, что позже её можно включить и для них (открытый вопрос 8.4). +- ~~Большие PGN (lichess-выгрузки) в этой версии остаются в малом режиме~~ — **заменено разделом 9:** экран (панель фильтров, доска, таблица, строка условий) один для всех баз; таблица выше теперь говорит только о том, как база читается (порог `LARGE_CHESSBASE` = 20 000 в `crates/chess-import/src/lib.rs`). -**Поле поиска в большом режиме.** Одно «умное» поле на 11,7 млн неоднозначно (игрок? турнир? год?) и даёт неожиданные выборки, поэтому его нет. На его месте в шапке — счётчик. `Ctrl+F` ведёт в поле «Игрок» панели (раздел 5). В малом режиме поле, его подсказка и `Ctrl+F` не меняются. +**Поле поиска.** ~~Одно «умное» поле на 11,7 млн неоднозначно… поэтому его нет.~~ **Заменено разделом 9.2:** быстрый поиск есть у всех баз, справа в шапке рядом с переключателем; он — ещё одно условие по И, видно чипом «Поиск», поэтому выборка не бывает неожиданной. `Ctrl+F` ведёт в него (раздел 9.10). ## 1. Сценарии Все сценарии — без единого нажатия «Искать»: фильтр применяется сам. -1. **Партии игрока.** `Ctrl+F` → набрать «carlsen» → через 250 мс таблица показывает партии всех игроков, в имени которых есть «carlsen» (Carlsen, Magnus и Carlsen, Henrik), под полем — подсказки «Carlsen, Magnus — 6 812 партий». `↓` + `Enter` в подсказках закрепляет точного игрока. Счётчик: «найдено 6 812 из 11 741 260». `↓` (подсказки закрыты) — к первой строке таблицы, `Enter` — открыть. +1. **Партии игрока.** `Ctrl+F` `Ctrl+F` (второе нажатие ведёт из быстрого поиска в «Игрок», раздел 9.10) → набрать «carlsen» → через 250 мс таблица показывает партии всех игроков, в имени которых есть «carlsen» (Carlsen, Magnus и Carlsen, Henrik), под полем — подсказки «Carlsen, Magnus — 6 812 партий». `↓` + `Enter` в подсказках закрепляет точного игрока. Счётчик: «найдено 6 812 из 11 741 260». `↓` (подсказки закрыты) — к первой строке таблицы, `Enter` — открыть. 2. **Игрок против игрока.** Заполнить «Игрок» (Carlsen) и «Соперник» (Nakamura). Цвет «любым» — партии в обе стороны; «белыми» — только где Carlsen белыми. Результат в этом случае переключается в относительный: «выигрыш / ничья / проигрыш» игрока. 3. **Турнир.** Поле «Турнир» (подстрока по названию и месту): «wijk 2024» → подсказки «Tata Steel Masters · Wijk aan Zee · 2024 — 91 партия». Выбор подсказки — точный турнир; без выбора — все турниры, совпавшие по всем словам. 4. **Годы + минимальный Эло.** «Годы» 2015 – 2024, «Эло от» 2600, «для: обоих». Без имени — проход по всем 11,7 млн записей (до ~1 с), таблица показывает прогресс (раздел 3.6). @@ -142,7 +144,7 @@ ### 3.5. Флажки - «с комментариями», «с вариантами» — по признакам записи `.cbh` (что точно доступно — у аналитика; если признака нет, флажок не показывается, а не делается неактивным). -- «показывать тексты» — текстовые главы. По умолчанию включено; тексты автоматически не входят в выборку, когда задан любой фильтр, который к ним неприменим (игрок, соперник, результат, Эло, ECO, ходы, аннотации) — у текстов нет игроков и результата. Турнир и комментатор к текстам применимы; даты у текстов нет, поэтому условие на годы их тоже исключает (уточнено при реализации, QA-отчёт №2, D6). +- «показывать тексты» — текстовые главы. Флажок есть только у базы, в которой тексты есть (ChessBase с текстами; книга из `.cbv`/малого `.cbh`, переведённая в PGN, — раздел 9.4); у базы без текстов, в том числе у любого обычного PGN, его нет. По умолчанию включено; тексты автоматически не входят в выборку, когда задан любой фильтр, который к ним неприменим (игрок, соперник, результат, Эло, ECO, ходы, аннотации) — у текстов нет игроков и результата. Турнир и комментатор к текстам применимы; даты у текстов нет, поэтому условие на годы их тоже исключает (уточнено при реализации, QA-отчёт №2, D6). ### 3.6. Живая фильтрация @@ -197,7 +199,7 @@ ### 4.7. Сортировка - Клик по заголовку — как сейчас (⏶/⏷). Сортировка запускается тем же фоновым механизмом с индикатором; по числовым полям обычно мгновенно. -- По умолчанию — «№» по возрастанию (порядок базы, без затрат). +- По умолчанию — «№» по возрастанию (порядок базы, без затрат). Исключение — базы, скачанные с Lichess и Chess.com: «Дата ⏷», новые сверху (раздел 9.6). - Строки с пустым значением (без Эло, без даты) — всегда в конце, в обоих направлениях. - Сортировка не сбрасывается при смене фильтра; при смене сортировки выделенная строка остаётся выделенной и прокручивается в центр. @@ -215,8 +217,7 @@ | Клавиша | Где | Действие | | --- | --- | --- | -| `Ctrl+F` | библиотека, большая база | фокус в «Игрок», текст выделяется целиком; если панель свёрнута — раскрыть | -| `Ctrl+F` | малая база | поле поиска над таблицей (как сейчас) | +| `Ctrl+F` | библиотека, любая база | **заменено разделом 9.10:** фокус в быстрый поиск в шапке; повторное `Ctrl+F` из поиска — панель «Фильтры» и фокус в «Игрок» | | `Tab` / `Shift+Tab` | панель | по полям сверху вниз, затем в таблицу | | `Esc` | поле с открытыми подсказками | закрыть подсказки | | `Esc` | непустое поле | очистить поле (условие снимается сразу) | @@ -261,11 +262,141 @@ Tooltip-ы (коротко, по делу): ## 8. Открытые вопросы к владельцу продукта -1. **Порог большой базы — 20 000 записей ChessBase?** Рекомендую 20 000 (одна константа, уточнить по замеру). Альтернатива — только по формату (любой `.cbh` → панель), но книги в `.cbv` на 300 партий тогда потеряют привычное поле поиска. -2. **Общее поле поиска в большом режиме убрать?** Рекомендую убрать (вместо него счётчик, `Ctrl+F` → «Игрок»). +1. ~~**Порог большой базы — 20 000 записей ChessBase?**~~ Решено (20 000, `LARGE_CHESSBASE`); с 2026-10-23 порог влияет только на способ чтения, не на экран (раздел 9). +2. ~~**Общее поле поиска в большом режиме убрать?**~~ Пересмотрено 2026-10-23: быстрый поиск есть у всех баз (раздел 9.2); вопрос 9.13.1. 3. **Фильтры между запусками:** рекомендую только в пределах сессии (раздел 7). -4. **Панель для больших PGN** (lichess, сотни тысяч партий) и кнопка «Фильтры» для малых баз — рекомендую позже, тем же компонентом. +4. ~~**Панель для больших PGN** и кнопка «Фильтры» для малых баз~~ — решено владельцем 2026-10-23: у всех PGN тот же экран (раздел 9). 5. **Экспорт выборки в PGN** («сохранить 6 812 найденных партий») — очень полезно и естественно после фильтра, но это новый тяжёлый фоновый процесс с прогрессом. Рекомендую следующей итерацией, не сейчас. 6. **Сворачивание полки в большой базе** до одной строки при высоте окна < 700 — рекомендую не делать в первой итерации, проверить на 900×600 после реализации. 7. **Переход к партии по номеру** (`Ctrl+G` → «№ 10234567») — дёшево, полезно для ссылок из книг и комментариев. Рекомендую добавить, если не мешает срокам. 8. **Колонка «✎» (есть комментарии/варианты)** — зависит от того, что подтвердит аналитик в записи `.cbh`; если признаков нет, колонка и флажки не показываются. + +## 9. Один экран для всех баз: PGN как ChessBase + +Статус: проект дизайнера, 2026-10-23, по решению владельца: «идентично как с базами от chessbase». Поля, которых в PGN может не быть (ECO, комментатор), остаются видны, а фильтр по ним просто ничего не находит. Быстрый текстовый поиск PGN остаётся. Пример реальной нагрузки — `Гран-при_РШШ_архив_все_партии.pgn`: 81 МБ, 33 640 партий. Теги `Event`, `Date` (вида `2026-10-18`), `Round`, `Board`, `White`/`Black`, Эло, `WebSite`, `GameId`, `Result`. У каждого хода `[%clk]`, ECO нет. + +### 9.1. Какой экран у какой базы + +- **Все базы полки открываются в одном экране** — экран раздела 2 и `board-search.md`: шапка, строка условий (чипы), таблица, справа `[Фильтры | Доска]`. Это PGN любого размера, от одной партии до миллиона, скачанные с Lichess и Chess.com, архивы, малые ChessBase и `.cbv`, переведённые в PGN, и большие ChessBase. Порога «маленькая база — без панели» нет: учебный файл на 38 партий получает тот же экран. Два экрана означали бы два набора клавиш и поведений, а владелец просит один. +- Панель по умолчанию у новой базы — «Фильтры», как у ChessBase сейчас. Кому панель в книге на 49 глав мешает, тот скрывает её щелчком по активному сегменту, и таблица займёт всю ширину (§2.1 `board-search.md`). +- Различия между базами идут только от данных, а не от экрана (§9.11): у элемента, которому нечего показать, нет места на экране; неактивных заглушек нет. +- Технически `LargeView` работает над источником записей с двумя реализациями: `Base` (ChessBase, как сейчас) и таблица записей PGN в памяти (§9.7). Им нужны одни операции: `query`, `sort_records`, `suggest_players`/`suggest_events`, строка таблицы, число записей и текстов. `SmallBoard` и отдельная таблица PGN в `library.rs::table_area` уходят. `Filter`, `NameFilter`, `fold`, `words`, `parse_eco` выносятся из `chessbase::base` в общий модуль `chess-import`, чтобы оба источника понимали условия одинаково. + +### 9.2. Быстрый поиск + +``` +│ Гран-при_РШШ_архив_все_партии · PGN, UTF-8 · найдено 412 из 33 640 ⟳ 40 % [⚠ 2] [🔍 вафин ×] [Фильтры | Доска] │ шапка 28 +│ Поиск: вафин × · Годы: 2025–2026 × · Результат: 1-0 × сбросить все │ чипы 26 +``` + +- **Место** — шапка, справа, слева от переключателя `[Фильтры | Доска]`. Поле на месте у всех баз, включая ChessBase (вопрос 9.13.1). Ширина 220; в узкой шапке сжимается до 140. Раньше него укорачиваются имя базы и счётчик, а подпись формата прячется по нынешнему правилу (< 520). Подсказка в пустом поле — существующая строка «🔍 Поиск: игрок, турнир, ECO, год». +- **Что ищет.** Слова без учёта регистра и диакритики (`fold`, как в §3.1). Каждое слово должно найтись хотя бы в одном поле; поля для разных слов могут быть разные. У PGN поля те же, что сейчас: `White`, `Black`, `Event`, `Site`, `ECO`, `Date`, `Annotator`. У ChessBase — имена белых и чёрных, турнир (название, место, год), комментатор, код ECO, год. Это сознательное изменение: сейчас вся строка должна была стоять в одном теге, и «carlsen 2024» не находил ничего. +- **Живой поиск** — тот же механизм, что у полей панели (§3.6): 250 мс после последней клавиши, фоновый проход, отмена старого прохода, затемнение после 150 мс. На PGN в тысячи партий проход мгновенный, мигания нет. +- **Сочетание** — по И с панелью и позицией. Поиск по позиции ищет среди партий, прошедших панель и быстрый поиск (сейчас `SmallBoard` делает то же для текста). +- **Чип «Поиск: вафин ×»** есть в строке условий, пока поле не пусто. Порядок чипов: Позиция → **Поиск** → Игрок → … (`board-search.md` §2.2: там «Поиск» стоял последним и только у малой базы). Щелчок по тексту чипа ставит фокус в поле поиска. +- **Очистка:** `×` в поле, `×` на чипе, `Esc` в непустом поле, `Ctrl+Shift+Backspace` (снимает всё, включая позицию). «Сбросить фильтры (N)» в подвале панели снимает только условия панели. Поиск, как и позиция, остаётся: у них свои `×`, и в N поиск не входит. В «Фильтры (N)» на переключателе тоже не входит. +- **Счётчик** «найдено N из M» показывается при любом условии, поиск тоже считается. + +### 9.3. Поля фильтра для PGN + +| Поле | ChessBase | PGN | +| --- | --- | --- | +| Игрок, Соперник, цвет | игроки `.cbp` | теги `White`, `Black`. Игрок — строка имени как в файле, крайние пробелы убраны, двойные сжаты. `?`, `-` и пустое имя — «нет игрока»: в подсказки не попадает и не совпадает ни с чем | +| Турнир или место | турнир `.cbt`: «Название (место) год» | тот же вид имени: `Event`, место из `Site`, год из `Date`; по этому имени ищет свободный текст. `Site` берётся местом, только если это не `?`, не ссылка (нет `://`: Lichess и Chess.com пишут туда адрес партии) и его ещё нет в названии. «Блиц 5, до 15 лет 2026» и «… 2025» — разные турниры, как в ChessBase. Работают «wijk 2024», «блиц 5 2026»; у Lichess `Event` вида «Rated Blitz game», поэтому слово «blitz» отбирает блиц | +| Комментатор | `.cbc`, слова | тег `Annotator`, слова, без подсказок (как у ChessBase) | +| Годы | дата записи | год из `Date`; если в `Date` года нет — из `UTCDate`. Разделители `.`, `-`, `/`: `2026-10-18`, `2026.10.18`, `2010.??.??` → 2010. `????.??.??` или нет тега — года нет: при заданных годах партия исключается, без них показывается (§3.2) | +| Эло от + «для» | Эло записи, 0 — нет | `WhiteElo`/`BlackElo`, целое > 0. `?`, `-`, пусто, 0 — «нет Эло». Правила «обоих / любого / среднего / соперника» те же | +| Результат | байт результата | `Result`: `1-0`, `0-1`, `1/2-1/2` (и `½-½`). Всё прочее или нет тега — `*`. Относительно игрока — как в §3.3 | +| ECO | код записи | первые три знака тега `ECO`, `A00`–`E99`, без учёта регистра: `B90a` и `B90 Sicilian` → B90. Иначе ECO нет, и при заданном ECO партия исключается. Поле остаётся и тогда, когда ECO нет ни у одной партии (решение владельца), а пустой результат объясняет причину (§9.8) | +| Ходов | ходы основной линии | `GameEntry::moves()`: тег `PlyCount`, если он есть, иначе полуходы основной линии вне скобок, пополам с округлением вверх. Разработчик уже добавляет `main_plies` в `scan.rs` | +| с комментариями | признак записи | `has_text_comments`: в комментарии есть текст помимо команд `[%…]`. `[%clk]`, `[%eval]`, `[%emt]`, `[%cal]`, `[%csl]` не считаются, комментарий `;` считается, одни NAG (`!?`, `$14`) — нет. В примере РШШ таких партий 0, и это правильно: часы — не комментарий | +| с вариантами | признак записи | `has_variations`: скобки в нотации | +| показывать тексты | тексты базы | §9.4 | + +### 9.4. Тексты + +- **У обычного PGN текстов нет, и флажка «показывать тексты» нет**: он скрыт, а не неактивен. Это не фильтр по полю, которое может быть пустым, а вид записей, которых в базе нет. Правило одно для всех баз: флажок есть, только если в базе есть тексты; у ChessBase без текстов его тоже нет (§3.5). +- **PGN, переведённый из ChessBase** (`.cbv`, малый `.cbh`, архивы с ними): конвертер точно знает, какие записи были текстами (`writer::text_game`). Он помечает их (список номеров в `Opened`/`PgnDb`), и дальше они ведут себя как тексты ChessBase: строка «📄 заголовок» курсивом и правила §3.5 и §4.5. Угадывать текст по признаку «нет ходов» нельзя: запись с заголовком и без ходов — законная партия (так в Mega записаны тысячи партий). + +### 9.5. Совпадение имён и подсказки + +- **Правило то же, что у ChessBase** (`Names::matching`). Имя и запрос приводятся к `fold`, запрос делится на слова по пробелам и запятым, каждое слово должно быть подстрокой имени, порядок любой. Поэтому «Карлсен, М» находит «Магнус Карлсен», а «magnus carlsen» — «Carlsen, Magnus»: порядок «фамилия первой» не важен ни в одну сторону. «вафин» находит «Вафин Радель». Транслитерации нет (`Carlsen` ≠ `Карлсен`): разные алфавиты — разные имена, как и в ChessBase. +- **Решение дизайнера для обоих форматов:** в `fold` добавить `ё → е`. В русских PGN одно имя пишут и «Артём», и «Артем» (в примере РШШ есть «Макаров Артём»), а набирают почти всегда через «е». Это одна строка в `fold` и тест. +- **Подсказки PGN** берутся из таблиц имён, которые строятся при открытии (§9.7): разные игроки и разные турниры (§9.3) с числом партий. Вид, порядок (совпадение с начала имени → число партий → алфавит), 8 строк, «ещё N совпадений…», закрепление `=` — как в §3.1. Выбор подсказки закрепляет одну строку имени. Разные написания одного человека остаются разными игроками, как в ChessBase. + +### 9.6. Таблица + +Колонки те же, что у ChessBase в коде: `[Ход] · № · Белые · Elo · Чёрные · Elo · Рез. · Длина · ECO · 💬 · Турнир · Раунд · Дата`. Порядок скрытия при узком окне тот же (`board-search.md` §2.7). + +- **№** — порядковый номер партии в файле (с 1). Ширина колонки — по числу цифр в базе (не меньше 52; 84 при восьми цифрах). +- **Турнир** — `Event` (`?` → пусто), курсивом, как сейчас. Отдельной колонки «Место» нет, потому что её нет и у ChessBase. Место видно в подсказке «Турнир или место» и в tooltip строки: «Турнир · место · раунд · длина · комментатор». Ссылку из `Site` место не показывает. +- **Раунд** — `Round` как в файле (`1.1`), `?` → пусто. Тег `Board` не показывается. +- **Дата** — `Date` (если нет, то `UTCDate`), «18.10.2026», «05.1997», «1997». Найденный дефект: `library::display_date` понимает только точки, и у файла РШШ дата `2026-10-18` сейчас показывается пустой. Нужно понимать `.`, `-` и `/`. +- **Длина** — `moves()` (§9.3). Сейчас она пуста у файлов без `PlyCount`, в том числе у РШШ. +- **💬** — отметки «есть комментарии / варианты» по признакам §9.3. У партий, где есть только часы, отметки нет. +- ✓ «просмотрено» (ключ — содержимое партии, как сейчас у PGN) и оранжевый номер при ошибках структуры или кодировки — без изменений. + +**Сортировка** — по тем же колонкам, что у ChessBase. Пустые значения (нет Эло, даты, ECO) — в конце в обоих направлениях (§4.7); сейчас PGN ставит партии без Эло первыми при сортировке по возрастанию. Ключ даты — `played_at()`: `UTCDate` + `UTCTime`, когда есть оба, иначе `Date`. Так партии одного дня из онлайн-выгрузки идут по времени. + +**Порядок по умолчанию:** «№ ⏶» — порядок файла (книга читается главами по порядку). У баз, скачанных с Lichess и Chess.com (`online::is_online`), — «Дата ⏷», новые сверху. Сейчас «новые сверху» спрятано в колонке «№» под стрелкой ⏶, а будет видно честной стрелкой на «Дата». Это сортировка по умолчанию, а не выбор пользователя (`sort_chosen = false`): с позицией включаются «сильнейшие сверху», а после снятия позиции возвращается «Дата ⏷». + +### 9.7. Открытие, подготовка, перечитывание + +- **Загрузка** — как сейчас: «Читаю … — найдено партий: N», полоса, «Отменить». Один раз за сеанс строится **таблица записей для фильтров** (в коде — `pgn_catalog::Catalog`). Её строит поток загрузки сразу после разбора или первый фоновый проход фильтра, но не поток интерфейса: на выгрузке в миллион партий это заметное время. На партию в ней номера белых, чёрных, турнира и комментатора, год, два Эло, результат, ECO, длина и признаки; к ней добавляются таблицы имён с числом партий. Это десятки байт на партию: 33 640 партий — мгновенно, миллион партий выгрузки — меньше секунды. Если подготовка дольше 150 мс, полоса стоит на 100 % с подписью «Готовлю список…». Таблица и панель появляются вместе, как у ChessBase. +- **Перечитывание** («⟳ Новые партии», файл растёт во время скачивания, «Перечитать базу»): фильтры, поиск, позиция, сортировка и выделение сохраняются (состояние привязано к пути). Выборка пересчитывается тем же проходом. Выделение остаётся, если номер партии ещё есть в выборке: скачанные партии дописываются в конец файла, номера старых не меняются. Прокрутка не прыгает. Таблица позиций (§9.9) после перечитывания строится заново при следующем использовании доски. + +### 9.8. Состояния + +- **Пусто** — как в §4.2: «Ничего не найдено», чипы с `×` и кнопка «Сбросить фильтры и поиск». Она снимает условия панели и поиск, а позиция остаётся; при заданной позиции та же кнопка называется «Искать во всей базе» и тоже снимает поиск (`board-search.md` §4.5). +- **Поле, которого в базе нет.** Если условие задано по полю, которое не заполнено ни у одной партии базы, под «Ничего не найдено» стоит строка-объяснение: «Ни у одной партии этой базы нет кода ECO» (а также комментатора, Эло, года). Число заполненных полей считается при подготовке (§9.7). Поле в панели при этом остаётся как есть, без серого и без предупреждений до поиска — так решил владелец. +- **Ошибка открытия** — как сейчас: причина и «Повторить». Ошибок фильтрации у PGN не бывает: фильтр не читает диск. +- **Партия не разбирается при открытии** — как сейчас: открывается с диагностикой. + +### 9.9. Поиск по позиции + +- Та же панель доски, те же чипы, колонка «Ход», продолжения, «сильнейшие сверху», ↪ и «только этот порядок». PGN ищет и в вариантах (🔀 в колонке «Ход»), ChessBase — только основную линию. Это различие данных, и tooltip колонки «Ход» уже его объясняет. +- **Книги:** продолжения «N глав» без результатов и Эло, если у большинства партий нет результата (правило `SmallBoard::books`: решённых < половины). Правило общее для всех баз. +- **Подготовка таблицы позиций.** Таблица строится при первом использовании доски — первый поиск или продолжения начальной позиции — один раз за сеанс (0,12 с на 33 640 партиях). Отдельной строки, как у ускорителя ChessBase, нет: подготовка — часть первого поиска. В области продолжений вместо «Считаю… N %» стоит «Готовлю поиск по позициям (один раз)… N %». Правило 300 мс то же, поэтому на 0,12 с надпись не мелькнёт; таблица затемняется через 150 мс, как всегда. Та же таблица служит вкладке «Справочник». +- **Не хватает памяти** (`positions_blocked`). Проверка — перед запуском поиска, не каждый кадр. + - Панель доски: строка предупреждения (существующий текст «Не хватает памяти… нужно ещё около N МБ», цвет предупреждения) и кнопка «Попробовать ещё раз». + - Доска остаётся рабочей: ходы делаются, линия растёт. Продолжения: «—». + - Чип: «Позиция: 1.e4 c5 ⚠», tooltip «Не применена: не хватает памяти для поиска по позициям». + - Таблица показывает выборку по фильтрам без позиции, без колонки «Ход»; счётчик — по фильтрам. Результат прежней позиции не показывается никогда. + - Повторная проверка — по кнопке и при следующем ходе на доске (одна проверка на ход). + - Фильтры панели и быстрый поиск работают полностью: таблица позиций им не нужна. + +### 9.10. Клавиатура + +| Клавиша | Где | Действие | +| --- | --- | --- | +| `Ctrl+F` | библиотека, любая база | фокус в быстрый поиск, текст выделяется целиком | +| `Ctrl+F` | в быстром поиске | панель «Фильтры» (раскрыть, если скрыта или показана доска) и фокус в «Игрок». Tooltip поиска: «Ctrl+F; ещё раз — фильтры» | +| `Esc` | быстрый поиск | непустой — очистить (условие снимается сразу), пустой — фокус в таблицу | +| `↓` / `↑`, `PgUp` / `PgDn` | быстрый поиск | выделение в таблице (как сейчас у PGN) | +| `Enter` | быстрый поиск | открыть выделенную партию; без выделения — ничего (§4.8) | +| `Tab` | шапка | быстрый поиск → поля панели сверху вниз → таблица | + +Остальные клавиши — §5 и `board-search.md` §5, одинаково для всех баз: `Ctrl+B`, `Ctrl+Shift+Backspace` (всё, включая поиск и позицию), `Ctrl+Backspace` (позиция) и прочие. + +### 9.11. Чего у PGN нет и как это скрыто + +| Элемент | ChessBase | PGN | +| --- | --- | --- | +| Подпись формата в шапке | «ChessBase, только чтение» | «PGN, UTF-8» / «PGN, кодировка windows-1251»; у переведённых — «ChessBase CBV, только чтение» (как сейчас) | +| «⟳ Новые партии» | — | только у скачанных баз, в шапке, как сейчас | +| Строка ускорителя «Ускоряю поиск по этой базе (один раз)…» | есть, когда нужна | нет; вместо неё подготовка внутри первого поиска (§9.9) | +| «показывать тексты» | если есть тексты | только у переведённых из ChessBase с текстами (§9.4) | +| ECO «960», сводка Chess960 | есть | нет (колонка ECO показывает тег как есть; поиск по позиции для таких партий — без изменений против нынешнего) | +| Варианты в поиске по позиции | только основная линия | и варианты (🔀) | +| Замечания импорта `⚠ N`, ✓ просмотрено, 🔒 на карточке | — | без изменений | + +Элемент, которого у базы нет, не рисуется. Неактивных элементов с объяснением «у PGN этого нет» нет. Поля фильтра, которых у конкретных партий нет (ECO, комментатор), к этому не относятся: они видны всегда (§9.3). + +### 9.12. Сохранение + +Как в §7 и `board-search.md` §4.12. Фильтры, **быстрый поиск**, позиция, сортировка, правая панель и выделение хранятся для каждой базы в пределах сессии. Сейчас текст поиска PGN общий (`Library::search`) и переходит в другую базу — это исправляется. Между запусками фильтры и поиск не сохраняются; ширина панелей запоминается, как сейчас. + +### 9.13. Вопросы владельцу + +1. **Быстрый поиск и у баз ChessBase (Mega)?** Рекомендую да: один экран без исключений. Ранний довод против (§0) снят: поиск — обычное условие с чипом и счётчиком, неожиданных выборок нет. Проход по Mega — около секунды, с тем же прогрессом. Альтернатива — поле только у PGN; тогда экраны различаются одним элементом. +2. **`Ctrl+F` ведёт в быстрый поиск, а повторное `Ctrl+F` — в «Игрок»?** Рекомендую да. Сейчас у ChessBase `Ctrl+F` ведёт в «Игрок», у PGN — в поиск, а одна клавиша должна делать одно. Альтернатива — `Ctrl+F` всегда в «Игрок», в поиск — мышью. diff --git a/docs/dev/import.md b/docs/dev/import.md index 1c0ae64..603f8f5 100644 --- a/docs/dev/import.md +++ b/docs/dev/import.md @@ -124,6 +124,16 @@ cargo test -p chess-import # модульные + фор cargo run -p chess-import --example convert -- "Book.cbv" > book.pgn # PGN в stdout, заметки в stderr ``` +## Фильтры PGN (`pgn_catalog.rs`) + +Каталог тегов PGN с теми же фильтрами, сортировкой и подсказками имён, что у ChessBase (`Filter`, `NameFilter`, `Names` и `fold` общие из `chessbase/base.rs`), для единого экрана библиотеки (`docs/design/large-databases.md` §9). Строится один раз при первом запросе (в фоновом проходе фильтра), на партию — номера игроков и турнира, дата, Эло, результат, ECO, длина и признаки; десятки байт на партию. + +- Турнир — как у ChessBase: «Event (место) год»; место из `Site`, если это не `?` и не ссылка. Год — из `Date`, иначе из `UTCDate`; разделители `.`, `-`, `/`. +- Длина — `PlyCount`, иначе полуходы основной линии, посчитанные при сканировании (`GameEntry::main_plies`); `all_plies` (с вариантами) даёт оценку памяти для таблицы позиций. +- «С комментариями» — `has_text_comments`: текст помимо команд `[%…]` (часы онлайн-партий — не комментарии). +- Быстрый поиск (`Filter::text`) — каждое слово в каком-нибудь поле: игроки, турнир, комментатор, место, ECO, дата. У ChessBase — игроки, турнир, комментатор, ECO, год (таблицы по годам и кодам ECO: Mega — около 0,1 с). +- Сортировка по дате — по времени партии (`UTCDate` + `UTCTime`, иначе `Date`): так скачанные партии идут свежими сверху. + ## Поиск по позиции (PGN) Модуль `crates/chess-import/src/pgn_positions.rs` (решение 13 в `docs/decisions.md`). Работает для PGN-файлов и для всего, что конвертируется в `PgnDatabase`: малые ChessBase (`.cbh` < 20 000 записей, `.cbv`) и архивы. Общие типы — `position.rs`.