Open ChessBase databases (.cbh, .cbv) and zip/7z archives
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run

New crate chess-import converts non-PGN sources to PGN in memory and returns
a PgnDatabase, so the library, notation and analysis work unchanged:
- .cbv archives (container rewritten after uncbv), .cbh with companion files
  (layout after the public Morphy format description): games, variations,
  comments with per-database code page detection, NAGs, squares/arrows, set-up
  positions, time spent, book chapters (guiding texts) as move-less records;
- ChessBase figurines become piece letters, diagram/object markers handled,
  Western names in Cyrillic databases read correctly;
- .zip/.7z with PGN (own encoding each), .cbh and .cbv; duplicates skipped;
- .cbz/encrypted archives and 2CBH rejected with clear messages.
Library: '+ Add database', format shown, import notes; comments keep
paragraph breaks. Tests on the user's sample books (skipped when absent).

Also: AUR PKGBUILD for 0.2.0 with the bundled Stockfish.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubel 2026-10-18 13:18:27 +03:00
parent 26bf901124
commit bb7d3b3fa6
31 changed files with 3618 additions and 64 deletions

View file

@ -11,6 +11,7 @@ license.workspace = true
[dependencies]
chess-core.workspace = true
chess-import.workspace = true
shakmaty.workspace = true
uci.workspace = true
egui.workspace = true

View file

@ -245,7 +245,13 @@ impl App {
fn pick_databases(&self, ctx: &egui::Context) {
self.spawn_dialog(ctx, || {
rfd::FileDialog::new()
.set_title(tr("Open PGN"))
.set_title(tr("Open database"))
.add_filter(
tr("Chess databases"),
&[
"pgn", "PGN", "cbh", "CBH", "cbv", "CBV", "zip", "ZIP", "7z", "7Z",
],
)
.add_filter("PGN", &["pgn", "PGN"])
.add_filter(tr("All files"), &["*"])
.pick_files()

View file

@ -107,6 +107,10 @@ impl GameView {
pub fn title(&self) -> String {
let g = &self.game;
let white = g.tag("White").filter(|s| *s != "?").unwrap_or(tr("White"));
// A book chapter imported from ChessBase: its title is in White, Black is empty.
if g.tag("Black") == Some("") {
return white.to_string();
}
let black = g.tag("Black").filter(|s| *s != "?").unwrap_or(tr("Black"));
format!("{white} — {black}")
}

View file

@ -212,14 +212,6 @@ const ROWS: &[[&str; 6]] = &[
"Pianoforte",
],
// --- app ---
[
"Open PGN",
"Открыть PGN",
"Ouvrir un PGN",
"PGN öffnen",
"Abrir PGN",
"Apri PGN",
],
[
"All files",
"Все файлы",
@ -573,22 +565,6 @@ const ROWS: &[[&str; 6]] = &[
"Tablero en la posición inicial (Ctrl+N)",
"Scacchiera nella posizione iniziale (Ctrl+N)",
],
[
"+ Add PGN",
"+ Добавить PGN",
"+ Ajouter un PGN",
"+ PGN hinzufügen",
"+ Añadir PGN",
"+ Aggiungi PGN",
],
[
"Open a PGN file (Ctrl+O)",
"Открыть PGN-файл (Ctrl+O)",
"Ouvrir un fichier PGN (Ctrl+O)",
"PGN-Datei öffnen (Ctrl+O)",
"Abrir un archivo PGN (Ctrl+O)",
"Apri un file PGN (Ctrl+O)",
],
[
"{n} games",
"{n} партий",
@ -1412,6 +1388,95 @@ const ROWS: &[[&str; 6]] = &[
"Stockfish (del sistema)",
"Stockfish (di sistema)",
],
// Importing ChessBase databases and archives
[
"Open database",
"Открыть базу",
"Ouvrir une base",
"Datenbank öffnen",
"Abrir base de datos",
"Apri database",
],
[
"Chess databases",
"Шахматные базы",
"Bases d'échecs",
"Schachdatenbanken",
"Bases de datos de ajedrez",
"Database di scacchi",
],
[
"Import notes",
"Замечания импорта",
"Remarques d'import",
"Importhinweise",
"Notas de importación",
"Note di importazione",
],
[
"Everything else was read. Games listed here are shown as far as they could be decoded.",
"Всё остальное прочитано. Перечисленные здесь партии показаны до того места, где их удалось раскодировать.",
"Tout le reste a été lu. Les parties listées ici sont affichées jusqu'où elles ont pu être décodées.",
"Alles andere wurde gelesen. Die hier aufgeführten Partien werden so weit gezeigt, wie sie entschlüsselt werden konnten.",
"Todo lo demás se ha leído. Las partidas listadas aquí se muestran hasta donde se pudieron decodificar.",
"Tutto il resto è stato letto. Le partite elencate qui sono mostrate fin dove è stato possibile decodificarle.",
],
[
"+ Add database",
"+ Добавить базу",
"+ Ajouter une base",
"+ Datenbank hinzufügen",
"+ Añadir base",
"+ Aggiungi database",
],
[
"Open PGN, ChessBase (.cbh, .cbv) or an archive (.zip, .7z) (Ctrl+O)",
"Открыть PGN, ChessBase (.cbh, .cbv) или архив (.zip, .7z) (Ctrl+O)",
"Ouvrir un PGN, une base ChessBase (.cbh, .cbv) ou une archive (.zip, .7z) (Ctrl+O)",
"PGN, ChessBase (.cbh, .cbv) oder ein Archiv (.zip, .7z) öffnen (Strg+O)",
"Abrir PGN, ChessBase (.cbh, .cbv) o un archivo comprimido (.zip, .7z) (Ctrl+O)",
"Apri PGN, ChessBase (.cbh, .cbv) o un archivio (.zip, .7z) (Ctrl+O)",
],
[
"Converted to PGN when opened; the original files are not changed. Save a game to keep your edits.",
"При открытии база переводится в PGN, исходные файлы не меняются. Чтобы сохранить правки, сохраните партию.",
"Convertie en PGN à l'ouverture ; les fichiers d'origine ne sont pas modifiés. Enregistrez une partie pour garder vos modifications.",
"Beim Öffnen in PGN umgewandelt; die Originaldateien bleiben unverändert. Speichern Sie eine Partie, um Ihre Änderungen zu behalten.",
"Se convierte a PGN al abrirla; los archivos originales no cambian. Guarda una partida para conservar tus cambios.",
"Convertito in PGN all'apertura; i file originali non vengono modificati. Salva una partita per mantenere le modifiche.",
],
[
"No PGN or ChessBase database in the archive",
"В архиве нет баз PGN или ChessBase",
"Aucune base PGN ou ChessBase dans l'archive",
"Keine PGN- oder ChessBase-Datenbank im Archiv",
"No hay ninguna base PGN o ChessBase en el archivo",
"Nessun database PGN o ChessBase nell'archivio",
],
[
"Password-protected archives (.cbz, encrypted zip/7z) are not supported",
"Архивы с паролем (.cbz, зашифрованные zip/7z) не поддерживаются",
"Les archives protégées par mot de passe (.cbz, zip/7z chiffrés) ne sont pas prises en charge",
"Passwortgeschützte Archive (.cbz, verschlüsselte zip/7z) werden nicht unterstützt",
"Los archivos con contraseña (.cbz, zip/7z cifrados) no son compatibles",
"Gli archivi protetti da password (.cbz, zip/7z cifrati) non sono supportati",
],
[
"The ChessBase 2CBH format is not supported: export the database from ChessBase as CBH or PGN",
"Формат ChessBase 2CBH не поддерживается: экспортируйте базу из ChessBase в CBH или PGN",
"Le format ChessBase 2CBH n'est pas pris en charge : exportez la base depuis ChessBase en CBH ou PGN",
"Das ChessBase-Format 2CBH wird nicht unterstützt: Exportieren Sie die Datenbank aus ChessBase als CBH oder PGN",
"El formato ChessBase 2CBH no es compatible: exporta la base desde ChessBase como CBH o PGN",
"Il formato ChessBase 2CBH non è supportato: esporta il database da ChessBase come CBH o PGN",
],
[
"· {n} games · {format}, read-only",
"· {n} партий · {format}, только чтение",
"· {n} parties · {format}, lecture seule",
"· {n} Partien · {format}, schreibgeschützt",
"· {n} partidas · {format}, solo lectura",
"· {n} partite · {format}, sola lettura",
],
];
#[cfg(test)]

View file

@ -1,4 +1,5 @@
//! Library screen: shelf of PGN databases + searchable, sortable game table.
//! Library screen: shelf of databases (PGN, ChessBase, archives) + searchable,
//! sortable game table.
use crate::i18n::{tr, trf};
use std::collections::HashMap;
@ -7,7 +8,8 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, channel};
use std::sync::{Arc, Mutex};
use chess_core::{GameEntry, OpenError, PgnDatabase, ScanProgress};
use chess_core::{GameEntry, PgnDatabase, ScanProgress};
use chess_import::{Format, ImportError, Opened, Unsupported};
use egui::{Color32, RichText, Sense, Ui, vec2};
use egui_extras::{Column, TableBuilder};
@ -15,7 +17,7 @@ enum Slot {
Loading {
progress: Arc<Mutex<ScanProgress>>,
cancel: Arc<AtomicBool>,
rx: Receiver<Result<PgnDatabase, OpenError>>,
rx: Receiver<Result<Opened, ImportError>>,
},
Ready(Arc<PgnDatabase>),
Failed(String),
@ -45,8 +47,17 @@ pub enum LibraryAction {
Quit,
}
/// How a database was imported, and what is worth knowing about it.
struct ImportInfo {
format: Format,
notes: Vec<String>,
}
pub struct Library {
slots: HashMap<PathBuf, Slot>,
info: HashMap<PathBuf, ImportInfo>,
/// Database whose import notes are shown.
notes_open: Option<PathBuf>,
pub selected_db: Option<PathBuf>,
search: String,
selected_row: Option<usize>,
@ -61,6 +72,8 @@ impl Library {
pub fn new() -> Self {
Self {
slots: HashMap::new(),
info: HashMap::new(),
notes_open: None,
selected_db: None,
search: String::new(),
selected_row: None,
@ -93,9 +106,9 @@ impl Library {
ctx.clone(),
);
let spawned = std::thread::Builder::new()
.name("pgn-scan".into())
.name("db-open".into())
.spawn(move || {
let res = PgnDatabase::open(
let res = chess_import::open(
&path_owned,
&mut |sp| {
if let Ok(mut g) = p.lock() {
@ -138,6 +151,7 @@ impl Library {
}
pub fn forget(&mut self, path: &Path) {
self.info.remove(path);
if let Some(Slot::Loading { cancel, .. }) = self.slots.remove(path) {
cancel.store(true, Ordering::Relaxed);
}
@ -155,14 +169,22 @@ impl Library {
}
fn poll(&mut self) {
for slot in self.slots.values_mut() {
for (path, slot) in self.slots.iter_mut() {
if let Slot::Loading { rx, .. } = slot
&& let Ok(res) = rx.try_recv()
{
*slot = match res {
Ok(db) => Slot::Ready(Arc::new(db)),
Err(OpenError::Cancelled) => Slot::Failed(tr("Loading cancelled").into()),
Err(e) => Slot::Failed(e.to_string()),
Ok(o) => {
self.info.insert(
path.clone(),
ImportInfo {
format: o.format,
notes: o.notes,
},
);
Slot::Ready(Arc::new(o.db))
}
Err(e) => Slot::Failed(import_error(&e)),
};
self.view_key = None;
}
@ -174,9 +196,41 @@ impl Library {
let mut actions = Vec::new();
egui::Panel::top("shelf").show(ui, |ui| self.shelf(ui, databases, &mut actions));
egui::CentralPanel::default().show(ui, |ui| self.table_area(ui, &mut actions));
self.notes_window(ui.ctx());
actions
}
fn notes_window(&mut self, ctx: &egui::Context) {
let Some(path) = self.notes_open.clone() else {
return;
};
let Some(info) = self.info.get(&path) else {
self.notes_open = None;
return;
};
let mut open = true;
egui::Window::new(tr("Import notes"))
.open(&mut open)
.default_width(560.0)
.show(ctx, |ui| {
ui.label(
RichText::new(tr(
"Everything else was read. Games listed here are shown as far as they could be decoded.",
))
.weak(),
);
ui.add_space(4.0);
egui::ScrollArea::vertical().max_height(420.0).show(ui, |ui| {
for n in &info.notes {
ui.label(RichText::new(format!("⚠ {n}")).color(ui.visuals().warn_fg_color));
}
});
});
if !open {
self.notes_open = None;
}
}
fn shelf(&mut self, ui: &mut Ui, databases: &[PathBuf], actions: &mut Vec<LibraryAction>) {
ui.add_space(8.0);
ui.horizontal(|ui| {
@ -217,11 +271,16 @@ impl Library {
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
tr("+ Add PGN"),
tr("+ Add database"),
egui::FontId::proportional(15.0),
visuals.text_color(),
);
if resp.on_hover_text(tr("Open a PGN file (Ctrl+O)")).clicked() {
if resp
.on_hover_text(tr(
"Open PGN, ChessBase (.cbh, .cbv) or an archive (.zip, .7z) (Ctrl+O)",
))
.clicked()
{
actions.push(LibraryAction::AddDatabases);
}
});
@ -270,12 +329,17 @@ impl Library {
egui::FontId::proportional(22.0),
text_color,
);
let galley = ui.painter().layout(
// Long names (book titles) are cut to two lines so the detail line stays readable.
let mut job = egui::text::LayoutJob::simple(
name,
egui::FontId::proportional(14.0),
text_color,
rect.width() - 52.0,
);
job.wrap.max_rows = 2;
job.wrap.break_anywhere = false;
job.wrap.overflow_character = Some('…');
let galley = ui.fonts_mut(|f| f.layout_job(job));
ui.painter()
.galley(rect.left_top() + vec2(44.0, 9.0), galley, text_color);
ui.painter().text(
@ -379,14 +443,41 @@ impl Library {
)
.strong(),
);
let enc = db.encoding();
ui.label(
RichText::new(trf(
"· {n} games · encoding {enc}",
&[("n", &db.len()), ("enc", &enc.label())],
))
.weak(),
);
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 = db.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
&& ui
.button(
RichText::new(format!("⚠ {notes}")).color(ui.visuals().warn_fg_color),
)
.on_hover_text(tr("Import notes"))
.clicked()
{
self.notes_open = Some(path.clone());
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let resp = ui.add(
egui::TextEdit::singleline(&mut self.search)
@ -626,3 +717,19 @@ fn filtered_sorted(entries: &[GameEntry], search: &str, (key, asc): (SortKey, bo
});
v
}
/// User-facing text of an import failure.
fn import_error(e: &ImportError) -> String {
match e {
ImportError::Cancelled => tr("Loading cancelled").into(),
ImportError::Empty => tr("No PGN or ChessBase database in the archive").into(),
ImportError::Unsupported(Unsupported::Encrypted) => {
tr("Password-protected archives (.cbz, encrypted zip/7z) are not supported").into()
}
ImportError::Unsupported(Unsupported::ChessBase2) => tr(
"The ChessBase 2CBH format is not supported: export the database from ChessBase as CBH or PGN",
)
.into(),
e => e.to_string(),
}
}

View file

@ -354,12 +354,24 @@ fn comment_text(comments: &[String]) -> String {
for c in comments {
for part in parse_comment(c) {
if let CommentPart::Text(t) = part {
// Source line breaks are formatting, not content: reflow to the panel width.
for word in t.split_whitespace() {
if !out.is_empty() {
out.push(' ');
// Single line breaks are formatting, not content: reflow to the panel width.
// A blank line starts a new paragraph (book chapters imported from ChessBase).
let mut blank = false;
for line in t.lines() {
if line.trim().is_empty() {
blank = true;
continue;
}
if blank && !out.is_empty() {
out.push_str("\n\n");
}
blank = false;
for word in line.split_whitespace() {
if !out.is_empty() && !out.ends_with('\n') {
out.push(' ');
}
out.push_str(word);
}
out.push_str(word);
}
}
}