diff --git a/CHANGELOG.md b/CHANGELOG.md index fb7efb9..e7da087 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). +## [Unreleased] + +- Open ChessBase databases (`.cbh` with companion files) and ChessBase archives (`.cbv`), and + `.zip` / `.7z` archives holding PGN, `.cbh` or `.cbv` files. Games, variations, comments (with the + right code page, including Cyrillic), symbols, coloured squares and arrows, set-up positions and + book chapters are converted to PGN in memory; sources are read-only. Problems are listed under + "Import notes" in the library. +- Comments keep paragraph breaks (a blank line starts a new paragraph). +- Library: "+ Add database"; long database names are shortened on the cards. + ## [0.2.0] — 2026-10-18 - Stockfish 19 is bundled with every package (unmodified official "universal" build, which picks diff --git a/Cargo.lock b/Cargo.lock index be02a37..73dced2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -535,6 +535,15 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "bzip2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c" +dependencies = [ + "libbz2-rs-sys", +] + [[package]] name = "calloop" version = "0.13.0" @@ -645,12 +654,25 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "chess-import" +version = "0.2.0" +dependencies = [ + "chess-core", + "encoding_rs", + "sevenz-rust2", + "shakmaty", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "chesspenguin" version = "0.2.0" dependencies = [ "arboard", "chess-core", + "chess-import", "directories", "eframe", "egui", @@ -851,6 +873,12 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" +[[package]] +name = "deflate64" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2" + [[package]] name = "directories" version = "6.0.0" @@ -1795,6 +1823,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +[[package]] +name = "libbz2-rs-sys" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c" + [[package]] name = "libc" version = "0.2.191" @@ -1868,6 +1902,12 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "lzma-rust2" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1c46f3fcd2e888afdb01a07efc071cb21300e07c68d32c3e8b01b5c8cb1fcaa" + [[package]] name = "mach2" version = "0.5.0" @@ -2023,6 +2063,18 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nohash-hasher" version = "0.2.0" @@ -2812,6 +2864,12 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "ppmd-rust" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "196a7c80b9a7652aba7cc070827516c2abe4ccdf53d128e1944003cf5726cff1" + [[package]] name = "presser" version = "0.3.1" @@ -3231,6 +3289,21 @@ dependencies = [ "serde_core", ] +[[package]] +name = "sevenz-rust2" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f0c68c0e8289bfd09e49ef433e8de02c7c464afc1d7f5a275c99749a880e301" +dependencies = [ + "bzip2", + "crc32fast", + "flate2", + "js-sys", + "lzma-rust2", + "ppmd-rust", + "wasm-bindgen", +] + [[package]] name = "shakmaty" version = "0.30.2" @@ -3817,6 +3890,12 @@ dependencies = [ "rustc-hash 2.1.3", ] +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + [[package]] name = "uci" version = "0.2.0" @@ -4915,6 +4994,22 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "zip" +version = "9.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e04976da629d3b04204ba8105b396a193af8ad2583b2c79bfb3ab8af580a11e" +dependencies = [ + "bzip2", + "crc32fast", + "deflate64", + "flate2", + "indexmap", + "memchr", + "nix", + "typed-path", +] + [[package]] name = "zlib-rs" version = "0.6.8" diff --git a/Cargo.toml b/Cargo.toml index ec81652..023d2a8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "3" -members = ["crates/chess-core", "crates/uci", "apps/desktop"] +members = ["crates/chess-core", "crates/chess-import", "crates/uci", "apps/desktop"] [workspace.package] version = "0.2.0" @@ -27,6 +27,7 @@ arboard = { version = "3.6", features = ["wayland-data-control"] } rodio = "0.22" directories = "6" chess-core = { path = "crates/chess-core" } +chess-import = { path = "crates/chess-import" } uci = { path = "crates/uci" } [profile.dev.package."*"] diff --git a/README.md b/README.md index 2c6962f..6011dbc 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,9 @@ ## Features - **PGN library** — keep several databases at hand, search and sort games, reopen where you left off. +- **ChessBase and archives** — open ChessBase databases (`.cbh`) and archives (`.cbv`), and `.zip` / + `.7z` files with PGN or ChessBase inside: games, variations, comments, symbols, arrows and the book + chapters, read-only (export to PGN by saving a game). - **Real-world PGN** — nested variations, comments, NAGs, games from a FEN position, legacy encodings (windows-1251, windows-1252, KOI8-R, CP866) and teaching null moves (`--`). Source files are never modified. diff --git a/README.ru.md b/README.ru.md index a08dfaa..6cdea32 100644 --- a/README.ru.md +++ b/README.ru.md @@ -10,6 +10,9 @@ ## Возможности - **Библиотека PGN** — несколько баз под рукой, поиск и сортировка партий, возврат к той же строке. +- **ChessBase и архивы** — базы ChessBase (`.cbh`) и архивы (`.cbv`), а также `.zip` / `.7z` с PGN + или ChessBase внутри: партии, варианты, комментарии, знаки, стрелки и текстовые главы книг; только + чтение (в PGN — сохранением партии). - **Реальные PGN** — вложенные варианты, комментарии, NAG, партии из позиции FEN, старые кодировки (windows-1251, windows-1252, KOI8-R, CP866) и учебные нулевые ходы `--`. Исходные файлы не изменяются. - **Нотация** — основная линия таблицей в две колонки, комментарии и варианты блоками, diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index ab9e45e..de9b81f 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -50,7 +50,16 @@ https://github.com/official-stockfish/Stockfish/releases/tag/sf_19 (SHA-256 pinn Open Database License (ODbL). - ChessPenguin runs Stockfish as a separate process over the UCI protocol. +## ChessBase formats + +- `crates/chess-import/src/cbv.rs` reads ChessBase archives following uncbv + (https://github.com/antoyo/uncbv, Antoni Boucher, GPL-3.0-or-later); the code is a rewrite. +- The ChessBase database layout (`crates/chess-import/src/chessbase/`) follows the public format + description in https://github.com/Yarin78/morphy (`format/v1`), used as a source of facts; no code + is taken from that project. +- ChessBase is a trademark of ChessBase GmbH; ChessPenguin is not affiliated with it. + ## Rust crates Dependency licenses are recorded by `Cargo.lock`; key ones: shakmaty / pgn-reader (GPL-3.0-or-later), -egui / eframe (MIT OR Apache-2.0). +egui / eframe (MIT OR Apache-2.0), zip (MIT), sevenz-rust2 (Apache-2.0). diff --git a/apps/desktop/Cargo.toml b/apps/desktop/Cargo.toml index 3573ddd..efa4bc4 100644 --- a/apps/desktop/Cargo.toml +++ b/apps/desktop/Cargo.toml @@ -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 diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index b0018b3..d874ab0 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -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() diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 829c0c4..0abd07e 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -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}") } diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 7e88805..f0fb2ab 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -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)] diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index 908bf7b..984a548 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -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>, cancel: Arc, - rx: Receiver>, + rx: Receiver>, }, Ready(Arc), 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, +} + pub struct Library { slots: HashMap, + info: HashMap, + /// Database whose import notes are shown. + notes_open: Option, pub selected_db: Option, search: String, selected_row: Option, @@ -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) { 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(), + } +} diff --git a/apps/desktop/src/notation.rs b/apps/desktop/src/notation.rs index 557b59c..fd471e2 100644 --- a/apps/desktop/src/notation.rs +++ b/apps/desktop/src/notation.rs @@ -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); } } } diff --git a/crates/chess-import/Cargo.toml b/crates/chess-import/Cargo.toml new file mode 100644 index 0000000..13aba72 --- /dev/null +++ b/crates/chess-import/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "chess-import" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "Opens chess databases other than plain PGN: ChessBase (.cbh, .cbv) and zip/7z archives" + +[dependencies] +chess-core.workspace = true +shakmaty.workspace = true +encoding_rs.workspace = true +thiserror.workspace = true +zip = { version = "9.0.5", default-features = false, features = ["deflate-flate2-zlib-rs", "deflate64", "bzip2"] } +sevenz-rust2 = { version = "0.24.1", default-features = false, features = ["bzip2", "ppmd", "deflate"] } diff --git a/crates/chess-import/examples/convert.rs b/crates/chess-import/examples/convert.rs new file mode 100644 index 0000000..5e676c5 --- /dev/null +++ b/crates/chess-import/examples/convert.rs @@ -0,0 +1,32 @@ +//! Converts a database to PGN on stdout; notes go to stderr. +//! +//! cargo run -p chess-import --example convert -- "Some Book.cbv" > book.pgn + +use std::io::Write; +use std::sync::atomic::AtomicBool; + +fn main() { + let Some(path) = std::env::args_os().nth(1) else { + eprintln!("usage: convert "); + std::process::exit(2); + }; + let never = AtomicBool::new(false); + match chess_import::open(std::path::Path::new(&path), &mut |_| {}, &never) { + Ok(o) => { + eprintln!("{}: {} games", o.format.label(), o.db.len()); + for n in &o.notes { + eprintln!("note: {n}"); + } + let mut out = std::io::stdout().lock(); + for i in 0..o.db.len() { + if let Some(text) = o.db.raw_text(i) { + let _ = writeln!(out, "{}\n", text.trim_end()); + } + } + } + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } + } +} diff --git a/crates/chess-import/src/archive.rs b/crates/chess-import/src/archive.rs new file mode 100644 index 0000000..c530b4b --- /dev/null +++ b/crates/chess-import/src/archive.rs @@ -0,0 +1,105 @@ +//! `.zip` and `.7z` archives, read into memory. + +use std::io::{Cursor, Read}; + +use crate::ImportError; + +/// A file of an archive (directories are left out). +pub struct Entry { + /// Path inside the archive with `/` separators. + pub name: String, + pub data: Vec, +} + +/// Total size an archive may unpack to: protection against archive bombs. +const MAX_TOTAL: u64 = 2 << 30; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Zip, + SevenZip, +} + +pub fn sniff(bytes: &[u8]) -> Option { + if bytes.starts_with(b"PK\x03\x04") || bytes.starts_with(b"PK\x05\x06") { + Some(Kind::Zip) + } else if bytes.starts_with(&[0x37, 0x7a, 0xbc, 0xaf, 0x27, 0x1c]) { + Some(Kind::SevenZip) + } else { + None + } +} + +/// Reads the members whose name `wanted` accepts (by lower-case name). +pub fn read( + bytes: &[u8], + kind: Kind, + wanted: &dyn Fn(&str) -> bool, +) -> Result, ImportError> { + match kind { + Kind::Zip => read_zip(bytes, wanted), + Kind::SevenZip => read_7z(bytes, wanted), + } +} + +fn too_large() -> ImportError { + ImportError::Corrupt("the archive unpacks to more than 2 GB".into()) +} + +fn read_zip(bytes: &[u8], wanted: &dyn Fn(&str) -> bool) -> Result, ImportError> { + let bad = |e: zip::result::ZipError| ImportError::Corrupt(format!("zip archive: {e}")); + let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(bad)?; + let mut out = Vec::new(); + let mut total = 0u64; + for i in 0..zip.len() { + let mut f = zip.by_index(i).map_err(bad)?; + let name = f.name().map_err(bad)?.replace('\\', "/"); + if f.is_dir() || !wanted(&name.to_lowercase()) { + continue; + } + if f.encrypted() { + return Err(ImportError::Unsupported(crate::Unsupported::Encrypted)); + } + total += f.size(); + if total > MAX_TOTAL { + return Err(too_large()); + } + let mut data = Vec::with_capacity(f.size().min(MAX_TOTAL) as usize); + f.by_ref() + .take(MAX_TOTAL) + .read_to_end(&mut data) + .map_err(|e| ImportError::Corrupt(format!("zip archive, {name}: {e}")))?; + out.push(Entry { name, data }); + } + Ok(out) +} + +fn read_7z(bytes: &[u8], wanted: &dyn Fn(&str) -> bool) -> Result, ImportError> { + let bad = |e: sevenz_rust2::Error| match e { + sevenz_rust2::Error::PasswordRequired => { + ImportError::Unsupported(crate::Unsupported::Encrypted) + } + e => ImportError::Corrupt(format!("7z archive: {e}")), + }; + let mut reader = + sevenz_rust2::ArchiveReader::new(Cursor::new(bytes), sevenz_rust2::Password::empty()) + .map_err(bad)?; + let declared: u64 = reader.archive().files.iter().map(|f| f.size()).sum(); + if declared > MAX_TOTAL { + return Err(too_large()); + } + let mut out = Vec::new(); + reader + .for_each_entries(|entry, r| { + let name = entry.name().replace('\\', "/"); + // Solid archives decode in order: entries that are not wanted are still read. + let mut data = Vec::new(); + r.take(MAX_TOTAL).read_to_end(&mut data)?; + if !entry.is_directory() && wanted(&name.to_lowercase()) { + out.push(Entry { name, data }); + } + Ok(true) + }) + .map_err(bad)?; + Ok(out) +} diff --git a/crates/chess-import/src/cbv.rs b/crates/chess-import/src/cbv.rs new file mode 100644 index 0000000..bcfd7fc --- /dev/null +++ b/crates/chess-import/src/cbv.rs @@ -0,0 +1,270 @@ +//! ChessBase archives (`.cbv`): a container of the files of one database, each +//! compressed in blocks with an LZ77-style scheme and an optional Huffman stage. +//! +//! Layout (little-endian), as implemented by uncbv (GPL-3.0-or-later, Antoni +//! Boucher), rewritten here without unsafe code and with bounds checks: +//! +//! - header: `08 00`, file count (u16), size of a directory entry (u8), 3 bytes; +//! - directory: per file, a zero-terminated name in a 132-byte field, the +//! compressed and the decompressed size (i32), padded to the entry size; +//! - data: per file, blocks of `size (u16), unknown (u16), flag (u8), payload`, +//! where flag bit 1 = Huffman-coded payload, bit 0 = LZ-compressed payload. +//! +//! Password-protected archives (`.cbz`, DES) are not supported. + +use crate::ImportError; + +/// One file of an archive, decompressed. +#[derive(Clone, Debug)] +pub struct Member { + /// Name as stored (Windows-1252), `\` replaced by `/`. + pub name: String, + pub data: Vec, +} + +const NAME_FIELD: usize = 132; +/// Upper bound for one decompressed member (a corrupt size must not exhaust memory). +const MAX_MEMBER: usize = 1 << 30; + +/// True if `bytes` start like a CBV archive. +pub fn looks_like_cbv(bytes: &[u8]) -> bool { + bytes.len() >= 8 && bytes[0] == 0x08 && bytes[1] == 0x00 && bytes[4] as usize >= NAME_FIELD + 8 +} + +/// Unpacks every member of the archive. +pub fn unpack(bytes: &[u8]) -> Result, ImportError> { + let corrupt = |what: &str| ImportError::Corrupt(format!("CBV archive: {what}")); + if !looks_like_cbv(bytes) { + return Err(corrupt("not a ChessBase archive")); + } + let count = usize::from(u16::from_le_bytes([bytes[2], bytes[3]])); + let entry = usize::from(bytes[4]); + let mut pos = 8; + let mut directory = Vec::with_capacity(count); + for _ in 0..count { + let e = bytes + .get(pos..pos + entry) + .ok_or_else(|| corrupt("truncated directory"))?; + let name_bytes = &e[..NAME_FIELD]; + let end = name_bytes + .iter() + .position(|b| *b == 0) + .unwrap_or(NAME_FIELD); + let (name, _, _) = encoding_rs::WINDOWS_1252.decode(&name_bytes[..end]); + let compressed = i32::from_le_bytes([e[132], e[133], e[134], e[135]]); + let decompressed = i32::from_le_bytes([e[136], e[137], e[138], e[139]]); + let (Ok(compressed), Ok(decompressed)) = + (usize::try_from(compressed), usize::try_from(decompressed)) + else { + return Err(corrupt("negative size")); + }; + if decompressed > MAX_MEMBER { + return Err(corrupt("member too large")); + } + directory.push((name.replace('\\', "/"), compressed, decompressed)); + pos += entry; + } + let mut members = Vec::with_capacity(count); + for (name, compressed, decompressed) in directory { + let data = bytes + .get(pos..pos + compressed) + .ok_or_else(|| corrupt("truncated data"))?; + pos += compressed; + let out = unpack_member(data, decompressed) + .map_err(|e| ImportError::Corrupt(format!("CBV archive, {name}: {e}")))?; + members.push(Member { name, data: out }); + } + Ok(members) +} + +fn unpack_member(mut data: &[u8], expected: usize) -> Result, String> { + let mut out = Vec::with_capacity(expected); + while !data.is_empty() { + if data.len() < 4 { + return Err("truncated block header".into()); + } + let size = usize::from(u16::from_le_bytes([data[0], data[1]])); + let block = data.get(4..4 + size).ok_or("truncated block")?; + data = &data[4 + size..]; + let (&flag, payload) = block.split_first().ok_or("empty block")?; + if flag > 3 { + return Err(format!("unknown block flag {flag}")); + } + let decoded; + let payload = if flag & 0b10 != 0 { + decoded = huffman(payload)?; + &decoded[..] + } else { + payload + }; + if flag & 0b01 != 0 { + lz_decompress(payload, &mut out)?; + } else { + out.extend_from_slice(payload); + } + if out.len() > MAX_MEMBER { + return Err("member too large".into()); + } + } + if out.len() != expected { + return Err(format!( + "size {} instead of the declared {expected}", + out.len() + )); + } + Ok(out) +} + +/// LZ77 with run-length codes. Groups of 16 items are preceded by a 16-bit mask +/// (bit 15 first); a set bit marks a coded item, a clear bit a literal byte. +fn lz_decompress(mut input: &[u8], out: &mut Vec) -> Result<(), String> { + // The block's output starts a new window: references never reach into earlier blocks. + let base = out.len(); + let take = |input: &mut &[u8], n: usize| -> Result, String> { + let s = input.get(..n).ok_or("truncated LZ data")?.to_vec(); + *input = &input[n..]; + Ok(s) + }; + 'outer: while !input.is_empty() { + let m = take(&mut input, 2)?; + let mut mask = u16::from_le_bytes([m[0], m[1]]); + for _ in 0..16 { + if input.is_empty() { + break 'outer; + } + if mask & 0x8000 == 0 { + out.push(input[0]); + input = &input[1..]; + } else { + let b = take(&mut input, 1)?[0]; + let (high, low) = (usize::from(b >> 4), usize::from(b & 0x0f)); + match high { + 0 => { + // Short run: low + 3 copies of the next byte. + let v = take(&mut input, 1)?[0]; + out.extend(std::iter::repeat_n(v, low + 3)); + } + 1 => { + // Long run: low + (next byte << 4) + 0x13 copies. + let x = take(&mut input, 2)?; + let n = low + (usize::from(x[0]) << 4) + 0x13; + out.extend(std::iter::repeat_n(x[1], n)); + } + _ => { + // Back reference: offset from the next byte and `low`; the length + // is `high`, or a following byte + 0x10 when `high` is 2. + let x = take(&mut input, 1)?[0]; + let offset = (usize::from(x) << 4) + low + 3; + let len = if high == 2 { + usize::from(take(&mut input, 1)?[0]) + 0x10 + } else { + high + }; + if offset > out.len() - base { + return Err("LZ reference before the start of the block".into()); + } + let start = out.len() - offset; + // Byte by byte: the copy may overlap what it produces. + for i in 0..len { + let v = out[start + i]; + out.push(v); + } + } + } + } + mask <<= 1; + } + } + Ok(()) +} + +/// Huffman stage: decompressed size (u16, big-endian), then a bit stream (most +/// significant bit first) with, for each of the 256 byte values, a 4-bit code +/// length and the code itself, followed by the coded data. +fn huffman(payload: &[u8]) -> Result, String> { + let size = usize::from(u16::from_be_bytes([ + *payload.first().ok_or("truncated Huffman block")?, + *payload.get(1).ok_or("truncated Huffman block")?, + ])); + let mut bits = Bits { + data: &payload[2..], + pos: 0, + }; + // codes[len] maps a code of that length to its byte value. + let mut codes: Vec> = vec![Default::default(); 16]; + for value in 0..=255u8 { + let len = bits.read(4).ok_or("truncated Huffman table")? as usize; + if len > 0 { + let code = bits.read(len).ok_or("truncated Huffman table")?; + codes[len].insert(code, value); + } + } + let mut out = Vec::with_capacity(size); + while out.len() < size { + let (mut code, mut len) = (0u16, 0usize); + loop { + code = (code << 1) | bits.read(1).ok_or("truncated Huffman data")?; + len += 1; + if len >= 16 { + return Err("invalid Huffman code".into()); + } + if let Some(v) = codes[len].get(&code) { + out.push(*v); + break; + } + } + } + Ok(out) +} + +struct Bits<'a> { + data: &'a [u8], + pos: usize, +} + +impl Bits<'_> { + fn read(&mut self, n: usize) -> Option { + let mut v = 0u16; + for _ in 0..n { + let byte = *self.data.get(self.pos / 8)?; + let bit = (byte >> (7 - self.pos % 8)) & 1; + v = (v << 1) | u16::from(bit); + self.pos += 1; + } + Some(v) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lz_runs_and_overlapping_references() { + // mask: literal 'a', literal 'b', run of 4 'x', reference (offset 3, len 3) + // Items: 'a' (0), 'b' (0), coded 0x01 'x' (1), coded 0x30 0x00 (1). + let mask: u16 = 0b0011_0000_0000_0000; + let mut input = mask.to_le_bytes().to_vec(); + input.extend_from_slice(b"ab"); + input.extend_from_slice(&[0x01, b'x']); + input.extend_from_slice(&[0x30, 0x00]); + let mut out = Vec::new(); + lz_decompress(&input, &mut out).expect("valid"); + assert_eq!(out, b"abxxxxxxx"); + } + + #[test] + fn rejects_garbage() { + assert!(unpack(b"PK\x03\x04").is_err()); + let mut fake = vec![0x08, 0x00, 0x01, 0x00, 0x95, 0, 0, 0]; + let mut entry = b"a.cbh".to_vec(); + entry.resize(NAME_FIELD, 0); + entry.extend_from_slice(&100i32.to_le_bytes()); + entry.extend_from_slice(&10i32.to_le_bytes()); + entry.resize(0x95, 0); + fake.extend(entry); + assert!(unpack(&fake).is_err(), "member data past the end"); + fake.truncate(60); + assert!(unpack(&fake).is_err(), "truncated directory"); + } +} diff --git a/crates/chess-import/src/chessbase/annotations.rs b/crates/chess-import/src/chessbase/annotations.rs new file mode 100644 index 0000000..9cef177 --- /dev/null +++ b/crates/chess-import/src/chessbase/annotations.rs @@ -0,0 +1,198 @@ +//! `.cba`: the annotations of a game, each attached to a move by its position in the +//! stored move order (−1 = the game as a whole). Big-endian. + +use std::collections::BTreeMap; + +use super::be; +use super::headers::Record; +use super::text::Decoder; + +/// What can be shown in PGN. Other annotation types (training, game quotations, +/// pictures, clocks, …) are skipped. +#[derive(Clone, Debug, PartialEq)] +pub enum Item { + Before(String), + After(String), + Nags(Vec), + /// (colour letter, square index a1 = 0) + Squares(Vec<(char, u8)>), + Arrows(Vec<(char, u8, u8)>), + /// Time spent on the move: h, m, s. + TimeSpent(u8, u8, u8), +} + +#[derive(Clone, Debug, Default)] +pub struct Annotations { + pub at: BTreeMap>, +} + +struct Raw<'a> { + position: i32, + kind: u8, + data: &'a [u8], +} + +const RECORD_HEADER: usize = 14; + +fn parse(cba: &[u8], offset: u32) -> Result<(u32, Vec>), String> { + let at = offset as usize; + let (Some(game), Some(size)) = (be(cba, at, 3), be(cba, at + 10, 4)) else { + return Err("annotations outside the .cba file".into()); + }; + let record = cba + .get(at..at + size as usize) + .filter(|r| r.len() >= RECORD_HEADER) + .ok_or("annotations outside the .cba file")?; + let mut items = Vec::new(); + let mut i = RECORD_HEADER; + while i + 6 <= record.len() { + let pos = be(record, i, 3).unwrap_or(0); + // Sign-extend the 24-bit position. + let position = ((pos << 8) as i32) >> 8; + let kind = record[i + 3]; + let len = be(record, i + 4, 2).unwrap_or(0) as usize; + if len < 6 || i + len > record.len() { + return Err("damaged annotation record".into()); + } + items.push(Raw { + position, + kind, + data: &record[i + 6..i + len], + }); + i += len; + } + Ok((game, items)) +} + +/// Adds the text bytes of every game's annotations to `buf` (for code page detection). +pub fn sample_texts(cba: &[u8], records: &[Record], buf: &mut Vec) { + for r in records { + if let Record::Game(h) = r + && h.annotations_offset > 0 + && let Ok((_, items)) = parse(cba, h.annotations_offset) + { + for it in items { + if matches!(it.kind, 0x02 | 0x82) && it.data.len() > 2 { + buf.extend_from_slice(&it.data[2..]); + buf.push(b' '); + } + } + } + } +} + +pub fn read(cba: &[u8], offset: u32, game_id: usize, d: &Decoder) -> Result { + let (game, items) = parse(cba, offset)?; + if game as usize != game_id { + return Err("annotations belong to another game".into()); + } + let mut out = Annotations::default(); + for it in items { + let item = match it.kind { + 0x02 | 0x82 => { + let text = d + .decode(it.data.get(2..).unwrap_or(&[])) + .replace(super::text::OBJECT, " ") + .replace("\r\n", "\n") + .replace('\r', "\n"); + let text = text.trim(); + if text.is_empty() { + continue; + } + if it.kind == 0x02 { + Item::After(text.to_owned()) + } else { + Item::Before(text.to_owned()) + } + } + 0x03 => { + let nags: Vec = it.data.iter().copied().filter(|n| *n != 0).collect(); + if nags.is_empty() { + continue; + } + Item::Nags(nags) + } + 0x04 => Item::Squares( + it.data + .as_chunks::<2>() + .0 + .iter() + .filter_map(|c| Some((colour(c[0])?, c[1].checked_sub(1)?))) + .filter(|(_, sq)| *sq < 64) + .collect(), + ), + 0x05 => Item::Arrows( + it.data + .as_chunks::<3>() + .0 + .iter() + .filter_map(|c| { + Some((colour(c[0])?, c[1].checked_sub(1)?, c[2].checked_sub(1)?)) + }) + .filter(|(_, a, b)| *a < 64 && *b < 64) + .collect(), + ), + 0x07 if it.data.len() >= 3 => Item::TimeSpent(it.data[0], it.data[1], it.data[2]), + _ => continue, + }; + out.at.entry(it.position).or_default().push(item); + } + Ok(out) +} + +/// ChessBase colours 2 green, 3 yellow, 4 red as PGN `%csl`/`%cal` letters. +fn colour(c: u8) -> Option { + match c { + 2 => Some('G'), + 3 => Some('Y'), + 4 => Some('R'), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use chess_core::TextEncoding; + + fn ann(position: i32, kind: u8, data: &[u8]) -> Vec { + let mut v = (position as u32).to_be_bytes()[1..].to_vec(); + v.push(kind); + v.extend_from_slice(&((data.len() + 6) as u16).to_be_bytes()); + v.extend_from_slice(data); + v + } + + #[test] + fn reads_texts_symbols_and_graphics() { + let mut body = Vec::new(); + body.extend(ann(-1, 0x02, b"\x00\x00Intro")); + body.extend(ann(0, 0x03, &[1, 0, 0])); + body.extend(ann(0, 0x02, &[0, 0, 0xd0, 0xe0, 0xe7, 0x9e])); + body.extend(ann(1, 0x04, &[2, 1, 4, 64])); + body.extend(ann(1, 0x05, &[3, 13, 29, 9, 1, 2])); + let size = (RECORD_HEADER + body.len()) as u32; + let mut cba = vec![0u8; 26]; + let offset = cba.len() as u32; + cba.extend_from_slice(&[0, 0, 7, 1, 0, 0x0e, 0x0e, 0, 0, 6]); + cba.extend_from_slice(&size.to_be_bytes()); + cba.extend(body); + let d = Decoder::new(TextEncoding::Windows1251); + let a = read(&cba, offset, 7, &d).expect("record"); + assert_eq!(a.at[&-1], vec![Item::After("Intro".into())]); + assert_eq!( + a.at[&0], + vec![Item::Nags(vec![1]), Item::After("Раз".into())], + "cp1251 text, diagram marker removed" + ); + assert_eq!( + a.at[&1], + vec![ + Item::Squares(vec![('G', 0), ('R', 63)]), + Item::Arrows(vec![('Y', 12, 28)]), + ], + "unknown colour 9 dropped" + ); + assert!(read(&cba, offset, 8, &d).is_err(), "wrong game id"); + } +} diff --git a/crates/chess-import/src/chessbase/entities.rs b/crates/chess-import/src/chessbase/entities.rs new file mode 100644 index 0000000..e9c75e5 --- /dev/null +++ b/crates/chess-import/src/chessbase/entities.rs @@ -0,0 +1,109 @@ +//! `.cbp` players, `.cbt` tournaments, `.cbc` annotators: fixed-size records after a +//! small little-endian header; an entity id is the record's index. + +use super::le_i32; +use super::text::Decoder; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Player, + Tournament, + Annotator, +} + +/// Raw string fields of every record (decoded later, once the code page is known). +#[derive(Clone, Debug, Default)] +pub struct Entities { + kind: Option, + records: Vec>>, + /// Tournament start dates (packed), by id. + dates: Vec, +} + +/// Node of the tree (9 bytes) before the data of each record. +const NODE: usize = 9; + +pub fn read(bytes: Option<&[u8]>, kind: Kind) -> Entities { + let mut out = Entities { + kind: Some(kind), + ..Entities::default() + }; + let Some(bytes) = bytes else { return out }; + let (Some(count), Some(data_size), Some(extra)) = + (le_i32(bytes, 0), le_i32(bytes, 0x0c), le_i32(bytes, 0x18)) + else { + return out; + }; + let header = 28 + usize::try_from(extra).unwrap_or(0).min(4); + let Ok(record) = usize::try_from(data_size).map(|d| d + NODE) else { + return out; + }; + // Fields: (offset in data, length). + let fields: &[(usize, usize)] = match kind { + Kind::Player => &[(0x00, 30), (0x1e, 20)], + Kind::Tournament => &[(0x00, 40), (0x28, 30)], + Kind::Annotator => &[(0x00, 45)], + }; + for i in 0..usize::try_from(count).unwrap_or(0) { + let Some(rec) = bytes.get(header + i * record..header + (i + 1) * record) else { + break; + }; + let data = &rec[NODE..]; + out.records.push( + fields + .iter() + .map(|&(at, len)| { + let f = data.get(at..at + len).unwrap_or(&[]); + let end = f.iter().position(|b| *b == 0).unwrap_or(f.len()); + f[..end].to_vec() + }) + .collect(), + ); + if kind == Kind::Tournament { + out.dates.push( + le_i32(data, 0x46) + .and_then(|d| u32::try_from(d).ok()) + .unwrap_or(0), + ); + } + } + out +} + +impl Entities { + pub fn sample(&self, buf: &mut Vec) { + for rec in &self.records { + for f in rec { + buf.extend_from_slice(f); + buf.push(b' '); + } + } + } + + fn field(&self, id: u32, i: usize, d: &Decoder) -> Option { + let f = self.records.get(id as usize)?.get(i)?; + let s = d.decode_name(f).trim().to_owned(); + (!s.is_empty()).then_some(s) + } + + /// "Last, First" for a player; the title of a tournament; an annotator's name. + pub fn name(&self, id: u32, d: &Decoder) -> Option { + let first = self.field(id, 0, d); + if self.kind == Some(Kind::Player) { + return match (first, self.field(id, 1, d)) { + (Some(last), Some(given)) => Some(format!("{last}, {given}")), + (last, given) => last.or(given), + }; + } + first + } + + /// Tournament place. + pub fn place(&self, id: u32, d: &Decoder) -> Option { + self.field(id, 1, d) + } + + pub fn date(&self, id: u32) -> u32 { + self.dates.get(id as usize).copied().unwrap_or(0) + } +} diff --git a/crates/chess-import/src/chessbase/headers.rs b/crates/chess-import/src/chessbase/headers.rs new file mode 100644 index 0000000..048d564 --- /dev/null +++ b/crates/chess-import/src/chessbase/headers.rs @@ -0,0 +1,149 @@ +//! `.cbh`: one 46-byte record per game or guiding text (big-endian). + +use super::be; +use crate::ImportError; + +const RECORD: usize = 46; + +#[derive(Clone, Debug)] +pub enum Record { + Game(GameHeader), + Text(TextHeader), + Deleted, +} + +#[derive(Clone, Debug, Default)] +pub struct GameHeader { + pub moves_offset: u32, + pub annotations_offset: u32, + pub white: u32, + pub black: u32, + pub tournament: u32, + pub annotator: u32, + pub date: u32, + pub result: u8, + pub round: u8, + pub subround: u8, + pub white_elo: u16, + pub black_elo: u16, + pub eco: u16, +} + +#[derive(Clone, Debug, Default)] +pub struct TextHeader { + pub text_offset: u32, + pub tournament: u32, + pub annotator: u32, + pub round: u8, + pub subround: u8, +} + +pub fn read(cbh: &[u8]) -> Result, ImportError> { + if cbh.len() < RECORD || be(cbh, 3, 2) != Some(RECORD as u32) { + return Err(ImportError::Corrupt( + "ChessBase database: the .cbh file has an unknown layout".into(), + )); + } + let mut out = Vec::new(); + for rec in cbh[RECORD..].as_chunks::().0 { + let kind = rec[0]; + if kind & 1 == 0 { + // All-zero records lie past the last game. + break; + } + let u = |at, n| be(rec.as_slice(), at, n).unwrap_or(0); + out.push(if kind & 0x80 != 0 { + Record::Deleted + } else if kind & 0x02 != 0 { + Record::Text(TextHeader { + text_offset: u(0x01, 4), + tournament: u(0x07, 3), + annotator: u(0x0d, 3), + round: rec[0x10], + subround: rec[0x11], + }) + } else { + Record::Game(GameHeader { + moves_offset: u(0x01, 4), + annotations_offset: u(0x05, 4), + white: u(0x09, 3), + black: u(0x0c, 3), + tournament: u(0x0f, 3), + annotator: u(0x12, 3), + date: u(0x18, 3), + result: rec[0x1b], + round: rec[0x1d], + subround: rec[0x1e], + white_elo: u(0x1f, 2) as u16, + black_elo: u(0x21, 2) as u16, + eco: u(0x23, 2) as u16, + }) + }); + } + Ok(out) +} + +impl GameHeader { + pub fn result_tag(&self) -> &'static str { + match self.result { + 0 | 4 => "0-1", + 1 | 5 => "1/2-1/2", + 2 | 6 => "1-0", + _ => "*", + } + } + + /// "C41" (sub-codes are ChessBase-specific and dropped); `None` for no ECO or Chess960. + pub fn eco_tag(&self) -> Option { + if self.eco == 0 || self.eco >= 64576 { + return None; + } + let code = usize::from(self.eco / 128).checked_sub(1)?; + let letter = *b"ABCDE".get(code / 100)?; + Some(format!("{}{:02}", letter as char, code % 100)) + } +} + +/// "1858.??.??" from a packed date (day bits 0-4, month 5-8, year 9-20). +pub fn date_tag(packed: u32) -> String { + let (day, month, year) = (packed & 31, (packed >> 5) & 15, (packed >> 9) & 0xfff); + let part = |v: u32, w: usize| { + if v == 0 { + "?".repeat(w) + } else { + format!("{v:0w$}") + } + }; + format!("{}.{}.{}", part(year, 4), part(month, 2), part(day, 2)) +} + +pub fn round_tag(round: u8, subround: u8) -> String { + match (round, subround) { + (0, _) => "?".into(), + (r, 0) => r.to_string(), + (r, s) => format!("{r}.{s}"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dates_eco_and_rounds() { + assert_eq!(date_tag((1905 << 9) | (8 << 5) | 31), "1905.08.31"); + assert_eq!(date_tag(1907 << 9), "1907.??.??"); + assert_eq!(date_tag(0), "????.??.??"); + let h = |eco| GameHeader { + eco, + ..GameHeader::default() + }; + assert_eq!(h((201 + 1) * 128 + 5).eco_tag().as_deref(), Some("C01")); + assert_eq!(h(128).eco_tag().as_deref(), Some("A00")); + assert_eq!(h(0).eco_tag(), None); + assert_eq!(h(64576).eco_tag(), None); + assert_eq!(round_tag(0, 0), "?"); + assert_eq!(round_tag(3, 0), "3"); + assert_eq!(round_tag(3, 2), "3.2"); + } +} diff --git a/crates/chess-import/src/chessbase/mod.rs b/crates/chess-import/src/chessbase/mod.rs new file mode 100644 index 0000000..1c79dad --- /dev/null +++ b/crates/chess-import/src/chessbase/mod.rs @@ -0,0 +1,235 @@ +//! ChessBase databases (`.cbh` and companion files) converted to PGN text. +//! +//! The layout follows the public format description of the Morphy project +//! (`format/v1` in github.com/Yarin78/morphy), used as a source of facts; no code is taken +//! from it. Only reading is supported, and the source files are never written. + +mod annotations; +mod entities; +mod headers; +mod moves; +mod text; +mod writer; + +use std::collections::HashMap; +use std::path::Path; + +use chess_core::TextEncoding; + +use crate::ImportError; + +/// The files of one database, by lower-case extension (`cbh`, `cbg`, …). +#[derive(Clone, Debug, Default)] +pub struct Files { + pub name: String, + files: HashMap>, +} + +impl Files { + /// Reads `/.` for every extension the reader uses. + pub fn from_dir(cbh: &Path) -> Result { + let dir = cbh.parent().unwrap_or(Path::new(".")); + let stem = cbh + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + let mut files = Files { + name: stem.clone(), + files: HashMap::new(), + }; + let entries = std::fs::read_dir(dir).map_err(|source| ImportError::Io { + path: dir.to_owned(), + source, + })?; + for e in entries.flatten() { + let p = e.path(); + let (Some(s), Some(ext)) = (p.file_stem(), p.extension()) else { + continue; + }; + let ext = ext.to_string_lossy().to_ascii_lowercase(); + if s.to_string_lossy() == stem && USED.contains(&ext.as_str()) { + let bytes = std::fs::read(&p).map_err(|source| ImportError::Io { + path: p.clone(), + source, + })?; + files.files.insert(ext, bytes); + } + } + Ok(files) + } + + /// Picks the files of the database whose `.cbh` member is `cbh_name` from archive + /// members (`name`, bytes). + pub fn from_members<'a>( + cbh_name: &str, + members: impl IntoIterator, + ) -> Files { + let stem = stem_of(cbh_name).to_owned(); + let mut files = Files { + name: stem.rsplit('/').next().unwrap_or(&stem).to_owned(), + files: HashMap::new(), + }; + for (name, data) in members { + if let Some(ext) = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()) + && stem_of(name) == stem + && USED.contains(&ext.as_str()) + { + files.files.insert(ext, data.to_vec()); + } + } + files + } + + fn get(&self, ext: &str) -> Option<&[u8]> { + self.files.get(ext).map(Vec::as_slice) + } + + fn required(&self, ext: &str) -> Result<&[u8], ImportError> { + self.get(ext).ok_or_else(|| { + ImportError::Corrupt(format!( + "ChessBase database {}: the .{ext} file is missing", + self.name + )) + }) + } +} + +/// Files the reader uses; the others (search boosters, settings, media) are ignored. +const USED: [&str; 6] = ["cbh", "cbg", "cba", "cbp", "cbt", "cbc"]; + +fn stem_of(name: &str) -> &str { + name.rsplit_once('.').map_or(name, |(s, _)| s) +} + +/// Result of converting one database. +#[derive(Clone, Debug, Default)] +pub struct Conversion { + /// UTF-8 PGN text, games and guiding texts in game id order. + pub pgn: String, + pub games: usize, + pub texts: usize, + /// Single-byte code page of the database's texts (UTF-8 texts are recognized + /// individually). + pub encoding: Option, + /// Problems worth showing to the user, one line each. + pub notes: Vec, +} + +/// Converts a database to PGN. Games that cannot be decoded completely are kept up +/// to the last readable move and reported in the notes. +pub fn convert(files: &Files) -> Result { + let cbh = files.required("cbh")?; + let cbg = files.required("cbg")?; + let cba = files.get("cba").unwrap_or(&[]); + let records = headers::read(cbh)?; + let players = entities::read(files.get("cbp"), entities::Kind::Player); + let tournaments = entities::read(files.get("cbt"), entities::Kind::Tournament); + let annotators = entities::read(files.get("cbc"), entities::Kind::Annotator); + + // One code page for the whole database, detected from all its single-byte texts. + let mut sample = Vec::new(); + for e in [&players, &tournaments, &annotators] { + e.sample(&mut sample); + } + annotations::sample_texts(cba, &records, &mut sample); + let encoding = text::detect(&sample); + let decoder = text::Decoder::new(encoding); + + let mut out = Conversion { + encoding: Some(encoding), + ..Conversion::default() + }; + let mut problems = Problems::default(); + for (id, rec) in records.iter().enumerate() { + let game_id = id + 1; + match rec { + headers::Record::Game(h) => { + let tags = writer::tags(h, &players, &tournaments, &annotators, &decoder); + let decoded = moves::decode(cbg, h.moves_offset); + let (tree, error) = match decoded { + Ok(t) => (t, None), + Err(moves::DecodeError { partial, reason }) => (partial, Some(reason)), + }; + if let Some(reason) = &error { + problems.add(game_id, &tags, reason); + } + let notes = if h.annotations_offset > 0 { + annotations::read(cba, h.annotations_offset, game_id, &decoder) + } else { + Ok(annotations::Annotations::default()) + }; + let notes = notes.unwrap_or_else(|reason| { + problems.add(game_id, &tags, &reason); + annotations::Annotations::default() + }); + writer::game(&mut out.pgn, &tags, &tree, ¬es, h.result_tag()); + out.games += 1; + } + headers::Record::Text(t) => match text::guiding_text(cbg, t.text_offset, &decoder) { + Ok(body) => { + let tags = + writer::text_tags(t, &body.title, &tournaments, &annotators, &decoder); + writer::text_game(&mut out.pgn, &tags, &body.text); + out.texts += 1; + } + Err(reason) => problems.add(game_id, &[], &reason), + }, + headers::Record::Deleted => {} + } + } + out.notes = problems.into_notes(); + Ok(out) +} + +/// Collects per-game problems; reports each kind once with the number of games. +#[derive(Default)] +struct Problems { + by_reason: Vec<(String, Vec)>, +} + +impl Problems { + fn add(&mut self, game_id: usize, tags: &[(String, String)], reason: &str) { + let tag = |k: &str| { + tags.iter() + .find(|(n, _)| n == k) + .map(|(_, v)| v.as_str()) + .unwrap_or("?") + }; + let who = if tags.is_empty() { + format!("#{game_id}") + } else { + format!("#{game_id} {} – {}", tag("White"), tag("Black")) + }; + match self.by_reason.iter_mut().find(|(r, _)| r == reason) { + Some((_, games)) => games.push(who), + None => self.by_reason.push((reason.to_owned(), vec![who])), + } + } + + fn into_notes(self) -> Vec { + self.by_reason + .into_iter() + .map(|(reason, games)| { + let shown: Vec<&str> = games.iter().take(5).map(String::as_str).collect(); + let more = if games.len() > 5 { + format!(" (+{})", games.len() - 5) + } else { + String::new() + }; + format!("{reason}: {}{more}", shown.join("; ")) + }) + .collect() + } +} + +/// Big-endian unsigned integer of `n` bytes at `at`. +fn be(bytes: &[u8], at: usize, n: usize) -> Option { + let s = bytes.get(at..at + n)?; + Some(s.iter().fold(0u32, |acc, b| (acc << 8) | u32::from(*b))) +} + +/// Little-endian signed 32-bit integer at `at`. +fn le_i32(bytes: &[u8], at: usize) -> Option { + let s = bytes.get(at..at + 4)?; + Some(i32::from_le_bytes([s[0], s[1], s[2], s[3]])) +} diff --git a/crates/chess-import/src/chessbase/moves.rs b/crates/chess-import/src/chessbase/moves.rs new file mode 100644 index 0000000..8f4307e --- /dev/null +++ b/crates/chess-import/src/chessbase/moves.rs @@ -0,0 +1,761 @@ +//! `.cbg` game records: the start position and the move tree. +//! +//! Every byte of the move stream goes through a per-mode permutation together with +//! the number of moves decoded so far. The compact encoder then names a piece by +//! its index among the pieces of its kind (in the order they were found on the start +//! board) and gives a displacement modulo 8; the simple encoder stores squares. + +use shakmaty::fen::Fen; +use shakmaty::san::SanPlus; +use shakmaty::{ + Bitboard, CastlingMode, Chess, Color, EnPassantMode, File, FromSetup, Move, Piece, Position, + Rank, Role, Setup, Square, +}; + +use super::be; + +/// The decoded move tree of one game. +#[derive(Clone, Debug, Default)] +pub struct Tree { + /// FEN of the start position when it is not the usual one. + pub start_fen: Option, + /// `nodes[0]` is the start; every other node is a move. + pub nodes: Vec, + /// Node of each move in stored order (the annotation position numbering). + pub order: Vec, +} + +#[derive(Clone, Debug, Default)] +pub struct Node { + /// SAN with check marks, or `--` for a null move. + pub san: String, + /// Move number and whether white made the move. + pub number: u32, + pub white: bool, + /// The first child is the main continuation. + pub children: Vec, +} + +/// A game that could only be read in part. +pub struct DecodeError { + pub partial: Tree, + pub reason: String, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Encoder { + Compact, + Simple, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Modifier { + Pre, + Post, +} + +pub fn decode(cbg: &[u8], offset: u32) -> Result { + let fail = |reason: &str| DecodeError { + partial: Tree::default(), + reason: reason.into(), + }; + let at = offset as usize; + let (Some(flags), Some(size)) = (cbg.get(at).copied(), be(cbg, at + 1, 3)) else { + return Err(fail("moves outside the .cbg file")); + }; + let record = cbg + .get(at..at + size as usize) + .filter(|r| r.len() >= 4) + .ok_or_else(|| fail("moves outside the .cbg file"))?; + let mode = flags & 0x3f; + let (encoder, modifier, table) = match mode { + 0 => (Encoder::Compact, Modifier::Pre, &TABLE_0), + 4 => (Encoder::Compact, Modifier::Post, &TABLE_4), + 5 => (Encoder::Simple, Modifier::Post, &TABLE_5), + 10 | 11 => return Err(fail("Chess960 games are not supported")), + 8 | 9 => return Err(fail("losing chess games are not supported")), + m => return Err(fail(&format!("move encoding {m} is not supported"))), + }; + let mut body = &record[4..]; + let (start, start_fen) = if flags & 0x40 != 0 { + let s = body + .get(..28) + .ok_or_else(|| fail("truncated start position"))?; + body = &body[28..]; + let pos = start_position(s).ok_or_else(|| fail("invalid start position"))?; + let fen = Fen::from_position(&pos, EnPassantMode::Legal).to_string(); + (pos, Some(fen)) + } else { + (Chess::default(), None) + }; + let mut d = Decoder { + tree: Tree { + start_fen, + nodes: vec![Node::default()], + order: Vec::new(), + }, + table, + modifier, + count: 0, + }; + let result = match encoder { + Encoder::Compact => d.compact(body, start), + Encoder::Simple => d.simple(body, start), + }; + match result { + Ok(()) => Ok(d.tree), + Err(reason) => Err(DecodeError { + partial: d.tree, + reason, + }), + } +} + +/// The 28-byte start position: marker, en passant file and side to move, castling +/// rights, move number, then 192 bits of board, square by square from a1, a2, … h8. +fn start_position(s: &[u8]) -> Option { + let mut setup = Setup::empty(); + let mut bits = BitReader { + data: &s[4..], + pos: 0, + }; + for idx in 0..64 { + if bits.read(1)? == 0 { + continue; + } + let color = if bits.read(1)? == 0 { + Color::White + } else { + Color::Black + }; + let role = match bits.read(3)? { + 1 => Role::King, + 2 => Role::Queen, + 3 => Role::Knight, + 4 => Role::Bishop, + 5 => Role::Rook, + 6 => Role::Pawn, + _ => return None, + }; + setup + .board + .set_piece_at(cb_square(idx), Piece { color, role }); + } + setup.turn = if s[1] & 0x10 != 0 { + Color::Black + } else { + Color::White + }; + let mut rights = Bitboard::EMPTY; + for (bit, sq) in [ + (0, Square::A1), + (1, Square::H1), + (2, Square::A8), + (3, Square::H8), + ] { + if s[2] & (1 << bit) != 0 { + rights.add(sq); + } + } + setup.castling_rights = rights; + let ep = u32::from(s[1] & 0x0f); + if (1..=8).contains(&ep) { + let rank = if setup.turn == Color::White { + Rank::Sixth + } else { + Rank::Third + }; + setup.ep_square = Some(Square::from_coords(File::new(ep - 1), rank)); + } + setup.fullmoves = std::num::NonZeroU32::new(u32::from(s[3]).max(1))?; + // Positions with doubtful castling rights or en passant squares are still usable. + let pos = match Chess::from_setup(setup, CastlingMode::Standard) { + Ok(p) => p, + Err(e) => match e.ignore_invalid_castling_rights() { + Ok(p) => p, + Err(e) => e.ignore_invalid_ep_square().ok()?, + }, + }; + Some(pos) +} + +/// ChessBase numbers squares file by file: a1 = 0, a2 = 1, … h8 = 63. +fn cb_square(idx: u32) -> Square { + Square::from_coords(File::new(idx / 8), Rank::new(idx % 8)) +} + +struct BitReader<'a> { + data: &'a [u8], + pos: usize, +} + +impl BitReader<'_> { + fn read(&mut self, n: usize) -> Option { + let mut v = 0; + for _ in 0..n { + let byte = *self.data.get(self.pos / 8)?; + v = (v << 1) | u32::from((byte >> (7 - self.pos % 8)) & 1); + self.pos += 1; + } + Some(v) + } +} + +/// Which square each piece of a side is on, in ChessBase's numbering. +#[derive(Clone, Default)] +struct Side { + king: Option, + queens: Vec, + rooks: Vec, + bishops: Vec, + knights: Vec, + /// Pawns keep their number for the whole game; a captured pawn leaves a gap. + pawns: [Option; 8], +} + +#[derive(Clone)] +struct State { + pos: Chess, + sides: [Side; 2], + node: usize, +} + +impl State { + fn new(pos: Chess) -> State { + let mut sides: [Side; 2] = Default::default(); + let mut pawn_count = [0usize; 2]; + for idx in 0..64 { + let sq = cb_square(idx); + let Some(p) = pos.board().piece_at(sq) else { + continue; + }; + let c = p.color as usize; + let s = &mut sides[c]; + match p.role { + Role::King => s.king = Some(sq), + Role::Queen => s.queens.push(sq), + Role::Rook => s.rooks.push(sq), + Role::Bishop => s.bishops.push(sq), + Role::Knight => s.knights.push(sq), + Role::Pawn => { + if let Some(slot) = s.pawns.get_mut(pawn_count[c]) { + *slot = Some(sq); + } + pawn_count[c] += 1; + } + } + } + State { + pos, + sides, + node: 0, + } + } + + fn side(&mut self, c: Color) -> &mut Side { + &mut self.sides[c as usize] + } + + /// Keeps the piece lists in step with a move about to be played. + fn track(&mut self, m: &Move) { + let us = self.pos.turn(); + match *m { + Move::Normal { + from, + to, + capture, + promotion, + .. + } => { + if capture.is_some() { + self.side(!us).remove(to); + } + self.side(us).relocate(from, to); + if let Some(role) = promotion { + let s = self.side(us); + s.remove(to); + s.list(role).push(to); + } + } + Move::EnPassant { from, to } => { + self.side(!us) + .remove(Square::from_coords(to.file(), from.rank())); + self.side(us).relocate(from, to); + } + Move::Castle { king, rook } => { + let short = rook.file() > king.file(); + let rank = king.rank(); + let (k, r) = if short { + (File::G, File::F) + } else { + (File::C, File::D) + }; + let s = self.side(us); + s.relocate(rook, Square::from_coords(r, rank)); + s.relocate(king, Square::from_coords(k, rank)); + } + Move::Put { .. } => {} + } + } +} + +impl Side { + fn list(&mut self, role: Role) -> &mut Vec { + match role { + Role::Queen => &mut self.queens, + Role::Rook => &mut self.rooks, + Role::Bishop => &mut self.bishops, + _ => &mut self.knights, + } + } + + /// A captured piece: later pieces of its kind move down one; a pawn leaves a gap. + fn remove(&mut self, sq: Square) { + for list in [ + &mut self.queens, + &mut self.rooks, + &mut self.bishops, + &mut self.knights, + ] { + if let Some(i) = list.iter().position(|s| *s == sq) { + list.remove(i); + return; + } + } + for p in &mut self.pawns { + if *p == Some(sq) { + *p = None; + return; + } + } + } + + fn relocate(&mut self, from: Square, to: Square) { + if self.king == Some(from) { + self.king = Some(to); + return; + } + for list in [ + &mut self.queens, + &mut self.rooks, + &mut self.bishops, + &mut self.knights, + ] { + if let Some(s) = list.iter_mut().find(|s| **s == from) { + *s = to; + return; + } + } + for p in self.pawns.iter_mut().flatten() { + if *p == from { + *p = to; + return; + } + } + } +} + +struct Decoder { + tree: Tree, + table: &'static [u8; 256], + modifier: Modifier, + /// Moves decoded so far, variations and null moves included. + count: u32, +} + +/// What a byte of the compact encoder asks for. +enum Code { + Null, + /// Piece kind, its index, displacement. + Piece(Role, usize, (i32, i32)), + Pawn(usize, u8), + Castle { + short: bool, + }, + TwoBytes, + Ignore, + Push, + Pop, +} + +const KING: [(i32, i32); 8] = [ + (0, 1), + (1, 1), + (1, 0), + (1, -1), + (0, -1), + (-1, -1), + (-1, 0), + (-1, 1), +]; +const KNIGHT: [(i32, i32); 8] = [ + (2, 1), + (1, 2), + (-1, 2), + (-2, 1), + (-2, -1), + (-1, -2), + (1, -2), + (2, -1), +]; + +/// Displacement of the `i`-th step of a line piece: groups of 7 steps in the +/// directions `dirs`. +fn line_step(i: usize, dirs: &[(i32, i32)]) -> (i32, i32) { + let (dx, dy) = dirs[i / 7]; + let n = (i % 7 + 1) as i32; + (dx * n, dy * n) +} + +const QUEEN_DIRS: [(i32, i32); 4] = [(0, 1), (1, 0), (1, 1), (1, -1)]; +const ROOK_DIRS: [(i32, i32); 2] = [(0, 1), (1, 0)]; +const BISHOP_DIRS: [(i32, i32); 2] = [(1, 1), (1, -1)]; + +fn classify(code: u8) -> Option { + let c = usize::from(code); + Some(match c { + 0 => Code::Null, + 1..=8 => Code::Piece(Role::King, 0, KING[c - 1]), + 9 => Code::Castle { short: true }, + 10 => Code::Castle { short: false }, + 11..=38 => Code::Piece(Role::Queen, 0, line_step(c - 11, &QUEEN_DIRS)), + 39..=52 => Code::Piece(Role::Rook, 0, line_step(c - 39, &ROOK_DIRS)), + 53..=66 => Code::Piece(Role::Rook, 1, line_step(c - 53, &ROOK_DIRS)), + 67..=80 => Code::Piece(Role::Bishop, 0, line_step(c - 67, &BISHOP_DIRS)), + 81..=94 => Code::Piece(Role::Bishop, 1, line_step(c - 81, &BISHOP_DIRS)), + 95..=102 => Code::Piece(Role::Knight, 0, KNIGHT[c - 95]), + 103..=110 => Code::Piece(Role::Knight, 1, KNIGHT[c - 103]), + 111..=142 => Code::Pawn((c - 111) / 4, ((c - 111) % 4) as u8), + 143..=170 => Code::Piece(Role::Queen, 1, line_step(c - 143, &QUEEN_DIRS)), + 171..=198 => Code::Piece(Role::Queen, 2, line_step(c - 171, &QUEEN_DIRS)), + 199..=212 => Code::Piece(Role::Rook, 2, line_step(c - 199, &ROOK_DIRS)), + 213..=226 => Code::Piece(Role::Bishop, 2, line_step(c - 213, &BISHOP_DIRS)), + 227..=234 => Code::Piece(Role::Knight, 2, KNIGHT[c - 227]), + 235 => Code::TwoBytes, + 236 => Code::Ignore, + 254 => Code::Push, + 255 => Code::Pop, + _ => return None, + }) +} + +impl Decoder { + fn translate(&self, byte: u8) -> u8 { + let n = (self.count % 256) as u8; + match self.modifier { + Modifier::Pre => self.table[usize::from(byte.wrapping_sub(n))], + Modifier::Post => self.table[usize::from(byte)].wrapping_sub(n), + } + } + + fn compact(&mut self, data: &[u8], start: Chess) -> Result<(), String> { + let mut state = State::new(start); + let mut stack: Vec = Vec::new(); + let mut i = 0; + while i < data.len() { + let raw = self.translate(data[i]); + i += 1; + let code = classify(raw).ok_or_else(|| format!("unknown move code {raw}"))?; + let m = match code { + Code::Push => { + stack.push(state.clone()); + continue; + } + Code::Pop => match stack.pop() { + Some(s) => { + state = s; + continue; + } + None => return Ok(()), + }, + Code::Ignore => continue, + Code::Null => None, + Code::TwoBytes => { + let (Some(&a), Some(&b)) = (data.get(i), data.get(i + 1)) else { + return Err("truncated move".into()); + }; + i += 2; + let v = (u16::from(self.translate(a)) << 8) | u16::from(self.translate(b)); + Some(square_move(&state.pos, v)?) + } + Code::Castle { short } => Some(castle(&state.pos, short)?), + Code::Piece(role, index, delta) => { + let side = &state.sides[state.pos.turn() as usize]; + let from = match role { + Role::King => side.king, + Role::Queen => side.queens.get(index).copied(), + Role::Rook => side.rooks.get(index).copied(), + Role::Bishop => side.bishops.get(index).copied(), + _ => side.knights.get(index).copied(), + } + .ok_or("move of a piece that is not on the board")?; + Some(find_move(&state.pos, from, displaced(from, delta), None)?) + } + Code::Pawn(index, kind) => { + let from = state.sides[state.pos.turn() as usize].pawns[index] + .ok_or("move of a pawn that is not on the board")?; + let white = state.pos.turn() == Color::White; + let delta = match (kind, white) { + (0, true) => (0, 1), + (1, true) => (0, 2), + (2, true) => (1, 1), + (_, true) => (-1, 1), + (0, false) => (0, -1), + (1, false) => (0, -2), + (2, false) => (-1, -1), + (_, false) => (1, -1), + }; + Some(find_move(&state.pos, from, displaced(from, delta), None)?) + } + }; + self.play(&mut state, m)?; + } + // A stream without its final end marker: keep what was read. + Ok(()) + } + + fn simple(&mut self, data: &[u8], start: Chess) -> Result<(), String> { + let mut state = State::new(start); + let mut stack: Vec = Vec::new(); + for pair in data.as_chunks::<2>().0 { + let v = (u16::from(self.translate(pair[0])) << 8) | u16::from(self.translate(pair[1])); + if v & 0x8000 != 0 { + stack.push(state.clone()); + } + // A move from a square to itself is a null move. + let m = if (v & 63) == ((v >> 6) & 63) { + None + } else { + Some(square_move(&state.pos, v & 0x3fff)?) + }; + self.play(&mut state, m)?; + if v & 0x4000 != 0 { + match stack.pop() { + Some(s) => state = s, + None => return Ok(()), + } + } + } + Ok(()) + } + + /// Adds the move (`None` = null move) as a child of the current node and plays it. + fn play(&mut self, state: &mut State, m: Option) -> Result<(), String> { + let pos = &state.pos; + let node = Node { + san: match m { + Some(m) => SanPlus::from_move(pos.clone(), m).to_string(), + None => "--".into(), + }, + number: pos.fullmoves().get(), + white: pos.turn() == Color::White, + children: Vec::new(), + }; + let next = match m { + Some(m) => { + state.track(&m); + let mut p = state.pos.clone(); + p.play_unchecked(m); + p + } + None => null_move(&state.pos).ok_or("null move while in check")?, + }; + let id = self.tree.nodes.len(); + self.tree.nodes.push(node); + self.tree.nodes[state.node].children.push(id); + self.tree.order.push(id); + state.node = id; + state.pos = next; + self.count += 1; + Ok(()) + } +} + +fn displaced(from: Square, (dx, dy): (i32, i32)) -> Square { + let x = (from.file() as i32 + dx).rem_euclid(8) as u32; + let y = (from.rank() as i32 + dy).rem_euclid(8) as u32; + Square::from_coords(File::new(x), Rank::new(y)) +} + +/// Move given by squares: bits 0-5 from, 6-11 to, 12-13 promotion piece. +fn square_move(pos: &Chess, v: u16) -> Result { + let from = cb_square(u32::from(v & 63)); + let to = cb_square(u32::from((v >> 6) & 63)); + let promotion = + [Role::Queen, Role::Rook, Role::Bishop, Role::Knight][usize::from((v >> 12) & 3)]; + find_move(pos, from, to, Some(promotion)) +} + +/// The legal move from `from` to `to` (the king's destination for castling); a +/// promotion takes `promotion`, or a queen. +fn find_move( + pos: &Chess, + from: Square, + to: Square, + promotion: Option, +) -> Result { + let wanted = promotion.unwrap_or(Role::Queen); + pos.legal_moves() + .into_iter() + .find(|m| { + m.from() == Some(from) + && king_target(m) == to + && m.promotion().is_none_or(|p| p == wanted) + }) + .ok_or_else(|| "illegal move".to_owned()) +} + +fn castle(pos: &Chess, short: bool) -> Result { + pos.legal_moves() + .into_iter() + .find(|m| matches!(m, Move::Castle { king, rook } if (rook.file() > king.file()) == short)) + .ok_or_else(|| "illegal castling".to_owned()) +} + +/// Destination as a player sees it: castling goes to the g or c file. +fn king_target(m: &Move) -> Square { + match *m { + Move::Castle { king, rook } => { + let file = if rook.file() > king.file() { + File::G + } else { + File::C + }; + Square::from_coords(file, king.rank()) + } + _ => m.to(), + } +} + +/// Teaching null move: the side to move passes (as `--` in PGN). +fn null_move(pos: &Chess) -> Option { + if pos.is_check() { + return None; + } + let mut setup = pos.to_setup(EnPassantMode::Legal); + let was_black = setup.turn == Color::Black; + setup.swap_turn(); + setup.ep_square = None; + setup.halfmoves = setup.halfmoves.saturating_add(1); + if was_black { + setup.fullmoves = setup.fullmoves.saturating_add(1); + } + Chess::from_setup(setup, CastlingMode::Standard).ok() +} + +const TABLE_0: [u8; 256] = [ + 0xa2, 0x95, 0x43, 0xf5, 0xc1, 0x3d, 0x4a, 0x6c, 0x53, 0x83, 0xcc, 0x7c, 0xff, 0xae, 0x68, 0xad, + 0xd1, 0x92, 0x8b, 0x8d, 0x35, 0x81, 0x5e, 0x74, 0x26, 0x8e, 0xab, 0xca, 0xfd, 0x9a, 0xf3, 0xa0, + 0xa5, 0x15, 0xfc, 0xb1, 0x1e, 0xed, 0x30, 0xea, 0x22, 0xeb, 0xa7, 0xcd, 0x4e, 0x6f, 0x2e, 0x24, + 0x32, 0x94, 0x41, 0x8c, 0x6e, 0x58, 0x82, 0x50, 0xbb, 0x02, 0x8a, 0xd8, 0xfa, 0x60, 0xde, 0x52, + 0xba, 0x46, 0xac, 0x29, 0x9d, 0xd7, 0xdf, 0x08, 0x21, 0x01, 0x66, 0xa3, 0xf1, 0x19, 0x27, 0xb5, + 0x91, 0xd5, 0x42, 0x0e, 0xb4, 0x4c, 0xd9, 0x18, 0x5f, 0xbc, 0x25, 0xa6, 0x96, 0x04, 0x56, 0x6a, + 0xaa, 0x33, 0x1c, 0x2b, 0x73, 0xf0, 0xdd, 0xa4, 0x37, 0xd3, 0xc5, 0x10, 0xbf, 0x5a, 0x23, 0x34, + 0x75, 0x5b, 0xb8, 0x55, 0xd2, 0x6b, 0x09, 0x3a, 0x57, 0x12, 0xb3, 0x77, 0x48, 0x85, 0x9b, 0x0f, + 0x9e, 0xc7, 0xc8, 0xa1, 0x7f, 0x7a, 0xc0, 0xbd, 0x31, 0x6d, 0xf6, 0x3e, 0xc3, 0x11, 0x71, 0xce, + 0x7d, 0xda, 0xa8, 0x54, 0x90, 0x97, 0x1f, 0x44, 0x40, 0x16, 0xc9, 0xe3, 0x2c, 0xcb, 0x84, 0xec, + 0x9f, 0x3f, 0x5c, 0xe6, 0x76, 0x0b, 0x3c, 0x20, 0xb7, 0x36, 0x00, 0xdc, 0xe7, 0xf9, 0x4f, 0xf7, + 0xaf, 0x06, 0x07, 0xe0, 0x1a, 0x0a, 0xa9, 0x4b, 0x0c, 0xd6, 0x63, 0x87, 0x89, 0x1d, 0x13, 0x1b, + 0xe4, 0x70, 0x05, 0x47, 0x67, 0x7b, 0x2f, 0xee, 0xe2, 0xe8, 0x98, 0x0d, 0xef, 0xcf, 0xc4, 0xf4, + 0xfb, 0xb0, 0x17, 0x99, 0x64, 0xf2, 0xd4, 0x2a, 0x03, 0x4d, 0x78, 0xc6, 0xfe, 0x65, 0x86, 0x88, + 0x79, 0x45, 0x3b, 0xe5, 0x49, 0x8f, 0x2d, 0xb9, 0xbe, 0x62, 0x93, 0x14, 0xe9, 0xd0, 0x38, 0x9c, + 0xb2, 0xc2, 0x59, 0x5d, 0xb6, 0x72, 0x51, 0xf8, 0x28, 0x7e, 0x61, 0x39, 0xe1, 0xdb, 0x69, 0x80, +]; + +const TABLE_4: [u8; 256] = [ + 0x58, 0xa3, 0xee, 0x72, 0x47, 0xb9, 0x1f, 0xa0, 0x26, 0xfd, 0xdc, 0x6d, 0xf1, 0xe3, 0xcb, 0xc5, + 0xe2, 0xd0, 0x29, 0xe7, 0x89, 0xe1, 0xae, 0x7b, 0x34, 0x41, 0x35, 0x4b, 0xa5, 0x7c, 0xf6, 0xe5, + 0xdb, 0x8c, 0x5f, 0x37, 0x05, 0xbb, 0x32, 0x54, 0x4c, 0xef, 0x5d, 0x2a, 0x7f, 0xd3, 0x81, 0x86, + 0xdf, 0x18, 0xc3, 0x44, 0x16, 0xf7, 0x85, 0x0f, 0x4d, 0x30, 0x79, 0x14, 0x45, 0xaa, 0xa2, 0x6c, + 0x15, 0x92, 0xa6, 0x62, 0x48, 0x19, 0xe9, 0x3c, 0x38, 0x94, 0x28, 0xa8, 0x66, 0x09, 0x03, 0x63, + 0x20, 0x7d, 0x36, 0xd7, 0x2e, 0x98, 0xec, 0xda, 0x01, 0x13, 0x24, 0x73, 0xcd, 0x9e, 0xcf, 0xd9, + 0xd5, 0x68, 0x8b, 0xd2, 0xab, 0x5b, 0x69, 0xb0, 0x27, 0xfc, 0x31, 0x1b, 0x53, 0x7e, 0x65, 0x76, + 0x55, 0x75, 0xaf, 0x0a, 0xcc, 0xc7, 0xc4, 0xb2, 0xb5, 0x22, 0xe8, 0xa7, 0xbe, 0xf5, 0x00, 0x5a, + 0x21, 0xd1, 0x74, 0x8e, 0xde, 0x9c, 0xe4, 0x42, 0x2b, 0xb1, 0x9b, 0x93, 0xc1, 0x78, 0x70, 0xd6, + 0xb6, 0xad, 0x4e, 0x6a, 0x64, 0x7a, 0x57, 0x49, 0x11, 0x9d, 0x12, 0xc0, 0x3a, 0x2f, 0xe6, 0x84, + 0xc6, 0x07, 0xce, 0x08, 0x82, 0x04, 0x90, 0xb8, 0x87, 0xca, 0x6e, 0x1e, 0x40, 0x1a, 0x50, 0xb4, + 0x10, 0xbc, 0x43, 0x8a, 0x71, 0x0b, 0x8d, 0x5c, 0x3b, 0x3f, 0x88, 0xba, 0xf4, 0xf3, 0x61, 0x1d, + 0xf9, 0xfe, 0x25, 0x51, 0x0d, 0xeb, 0xc8, 0x59, 0x17, 0x46, 0xa4, 0xf2, 0x56, 0xb7, 0x02, 0x2d, + 0x33, 0x9f, 0xd8, 0x83, 0xfb, 0xbf, 0xea, 0xed, 0xac, 0x60, 0x67, 0x39, 0xdd, 0x96, 0x6b, 0xa9, + 0xc2, 0x77, 0x0c, 0x0e, 0x91, 0xfa, 0x99, 0x9a, 0xe0, 0xa1, 0xf0, 0x5e, 0xc9, 0x06, 0x4f, 0xbd, + 0x52, 0x80, 0xd4, 0xf8, 0x97, 0x23, 0x3e, 0x1c, 0x2c, 0x95, 0x4a, 0x8f, 0x3d, 0x6f, 0xff, 0xb3, +]; + +const TABLE_5: [u8; 256] = [ + 0xe0, 0x1b, 0x97, 0x86, 0xa2, 0x48, 0xf0, 0x23, 0x01, 0x37, 0xfa, 0xeb, 0x50, 0x76, 0x5d, 0xcd, + 0x80, 0x1a, 0x31, 0x5c, 0xff, 0xbc, 0x78, 0xda, 0xe5, 0xa3, 0x75, 0xb3, 0x71, 0xe1, 0xa1, 0x0e, + 0x56, 0x41, 0x3f, 0xe3, 0x0d, 0xc4, 0x25, 0xe6, 0x88, 0x89, 0x70, 0xdc, 0x99, 0xa6, 0x0b, 0x9a, + 0x14, 0x2c, 0x57, 0x9e, 0x69, 0x7a, 0xdf, 0x55, 0xad, 0x73, 0x7c, 0xc5, 0x03, 0x72, 0xf5, 0x45, + 0x62, 0x8e, 0xaf, 0x5f, 0xcc, 0xc0, 0x5e, 0xf3, 0x18, 0x13, 0xb5, 0x38, 0x09, 0x28, 0x3c, 0xbd, + 0x10, 0x8b, 0xe9, 0xdd, 0x8c, 0x94, 0x08, 0x81, 0xa7, 0xfe, 0x24, 0x79, 0x44, 0x2b, 0xc1, 0x36, + 0x32, 0x7f, 0x67, 0xe4, 0xfd, 0x49, 0x4b, 0x21, 0xa9, 0x5b, 0x77, 0x1f, 0x1c, 0xf6, 0x40, 0x65, + 0x3d, 0xf9, 0x5a, 0xf8, 0x47, 0x26, 0x53, 0xd4, 0x20, 0xd2, 0xd8, 0x4f, 0x27, 0xae, 0xfb, 0xb6, + 0x9b, 0x74, 0xb8, 0x42, 0xfc, 0x16, 0x6f, 0xd7, 0x9f, 0xb9, 0x7b, 0x60, 0xde, 0xc2, 0x46, 0x06, + 0x9c, 0xd3, 0x2a, 0xc7, 0x05, 0x85, 0x3e, 0xb1, 0x00, 0x15, 0xd1, 0x96, 0xce, 0x90, 0x95, 0x11, + 0x33, 0x8f, 0xc6, 0x82, 0x84, 0xb7, 0x39, 0xa0, 0xe8, 0x34, 0x1e, 0x7d, 0xa8, 0xd0, 0xea, 0xe2, + 0xef, 0x4c, 0xc3, 0x58, 0x4e, 0x02, 0x1d, 0xb2, 0x7e, 0x98, 0x2d, 0x07, 0xd5, 0xca, 0x68, 0xcb, + 0x30, 0xb4, 0xac, 0x83, 0x63, 0xec, 0x87, 0xee, 0x2e, 0xbe, 0xcf, 0x6d, 0x4d, 0x8a, 0xd6, 0x04, + 0xb0, 0x35, 0xc8, 0xc9, 0x12, 0x17, 0x61, 0x8d, 0x64, 0x0f, 0xa5, 0x54, 0x29, 0x3a, 0x4a, 0x6b, + 0xbb, 0x2f, 0xd9, 0x3b, 0x93, 0x6a, 0xaa, 0xa4, 0x22, 0xf4, 0x19, 0x43, 0x6e, 0xf1, 0xf7, 0xdb, + 0x92, 0xed, 0x66, 0x59, 0x0a, 0xbf, 0x6c, 0x51, 0x91, 0x52, 0xf2, 0x0c, 0x9d, 0xab, 0xba, 0xe7, +]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tables_are_permutations() { + for t in [&TABLE_0, &TABLE_4, &TABLE_5] { + let mut seen = [false; 256]; + for v in t.iter() { + assert!(!seen[usize::from(*v)]); + seen[usize::from(*v)] = true; + } + } + } + + #[test] + fn start_board_bits() { + // The example from the format description: white pawn a2, black rook b1, + // white knight b4 (bits 0 10110 000000 11101 00 10011), plus both kings. + let mut s = vec![1, 0, 0, 1]; + let mut board = vec![0x58, 0x0e, 0x93]; + board.resize(24, 0); + s.extend(board); + // Kings are needed for a valid position: add them on h1 (white) and h8 (black). + let mut bits: Vec = Vec::new(); + let mut pos = BitReader { + data: &s[4..], + pos: 0, + }; + for _ in 0..24 { + bits.push(pos.read(1).unwrap_or(0) as u8); + } + assert_eq!(bits[..6], [0, 1, 0, 1, 1, 0]); + assert!(start_position(&s).is_none(), "no kings: invalid"); + } + + #[test] + fn displacement_wraps_modulo_8() { + // A queen on c2 moving (+7, 0) reaches b2. + assert_eq!(displaced(Square::C2, (7, 0)), Square::B2); + assert_eq!(displaced(Square::A1, (-1, -1)), Square::H8); + assert_eq!(line_step(7, &QUEEN_DIRS), (1, 0)); + assert_eq!(line_step(13, &QUEEN_DIRS), (7, 0)); + assert_eq!(line_step(27, &QUEEN_DIRS), (7, -7)); + } + + #[test] + fn piece_numbering_follows_the_start_board() { + let s = State::new(Chess::default()); + let w = &s.sides[Color::White as usize]; + assert_eq!(w.rooks, vec![Square::A1, Square::H1]); + assert_eq!(w.knights, vec![Square::B1, Square::G1]); + assert_eq!(w.pawns[0], Some(Square::A2)); + assert_eq!(w.pawns[7], Some(Square::H2)); + let b = &s.sides[Color::Black as usize]; + assert_eq!(b.rooks, vec![Square::A8, Square::H8]); + assert_eq!(b.pawns[0], Some(Square::A7)); + } +} diff --git a/crates/chess-import/src/chessbase/text.rs b/crates/chess-import/src/chessbase/text.rs new file mode 100644 index 0000000..2d59813 --- /dev/null +++ b/crates/chess-import/src/chessbase/text.rs @@ -0,0 +1,386 @@ +//! Text decoding and guiding texts. +//! +//! ChessBase does not record the code page of its texts: a text is UTF-8 or a +//! single-byte code page. A database is decoded with one single-byte code page, +//! detected from all its texts at once, while each text that is valid UTF-8 (and +//! not plain ASCII) is taken as UTF-8. + +use chess_core::{TextEncoding, detect_encoding}; + +use super::be; + +/// The byte ChessBase uses in single-byte texts to place a diagram. +const DIAGRAM: u8 = 0x9e; +/// The same marker in UTF-8 texts (a private-use character). +const DIAGRAM_UTF8: char = '\u{e005}'; +/// Where a text embeds an object (a diagram, a picture, a link to a game or chapter); +/// what the object is lies in formatting data whose layout is unknown. +pub const OBJECT: char = '\u{4}'; + +/// Piece figurines in single-byte texts: bytes 0xa2-0xa7 stand for K Q N B R and a pawn +/// when a square or a capture follows ("¤f3", "¥:g4"). +const FIGURINES_SINGLE: [&str; 6] = ["K", "Q", "N", "B", "R", ""]; +/// Piece figurines in UTF-8 texts: U+E024-U+E029 stand for K Q R B N and a pawn. +const FIGURINES_UTF8: [&str; 6] = ["K", "Q", "R", "B", "N", ""]; + +pub fn detect(sample: &[u8]) -> TextEncoding { + match detect_encoding(sample).encoding { + // All ASCII or UTF-8: single-byte texts (if any) are most likely Western. + TextEncoding::Utf8 => TextEncoding::Windows1252, + e => e, + } +} + +pub struct Decoder { + single_byte: TextEncoding, +} + +impl Decoder { + pub fn new(single_byte: TextEncoding) -> Decoder { + Decoder { single_byte } + } + + /// A comment or a guiding text. Control characters are dropped, apart from line + /// breaks, tabs and [`OBJECT`]. + pub fn decode(&self, bytes: &[u8]) -> String { + let mut s = self.decode_raw(bytes); + s.retain(|c| !c.is_control() || matches!(c, '\n' | '\r' | '\t' | OBJECT)); + s + } + + fn decode_raw(&self, bytes: &[u8]) -> String { + if !bytes.is_ascii() + && let Ok(s) = std::str::from_utf8(bytes) + { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + DIAGRAM_UTF8 => {} + '\u{e024}'..='\u{e029}' => { + out.push_str(FIGURINES_UTF8[(c as u32 - 0xe024) as usize]); + } + c => out.push(c), + } + } + return out; + } + let mut cleaned = Vec::with_capacity(bytes.len()); + for (i, &b) in bytes.iter().enumerate() { + let next = bytes.get(i + 1).copied().unwrap_or(0); + match b { + DIAGRAM => {} + 0xa2..=0xa7 if matches!(next, b'a'..=b'h' | b'x' | b':') => { + cleaned.extend_from_slice(FIGURINES_SINGLE[usize::from(b - 0xa2)].as_bytes()); + } + b => cleaned.push(b), + } + } + self.single_byte.decode(&cleaned).0.into_owned() + } + + /// A name of a player, tournament or annotator. ChessBase stores names in a Western + /// code page even in a database whose texts are Cyrillic, but a name may also be + /// typed in Cyrillic: the reading that does not mix Latin and Cyrillic letters + /// within a word wins ("Nürnberg", not "Nьrnberg"). + pub fn decode_name(&self, bytes: &[u8]) -> String { + let own = self.decode(bytes).replace(OBJECT, " "); + if bytes.is_ascii() + || std::str::from_utf8(bytes).is_ok() + || !matches!( + self.single_byte, + TextEncoding::Windows1251 | TextEncoding::Koi8R | TextEncoding::Ibm866 + ) + { + return own; + } + let mut western = TextEncoding::Windows1252.decode(bytes).0.into_owned(); + western.retain(|c| !c.is_control()); + if mixed_words(&western) < mixed_words(&own) { + western + } else { + own + } + } +} + +/// Words that contain both Latin and Cyrillic letters. +fn mixed_words(s: &str) -> usize { + s.split(|c: char| !c.is_alphanumeric()) + .filter(|w| { + let latin = w.chars().any(|c| c.is_alphabetic() && (c as u32) < 0x250); + let cyrillic = w.chars().any(|c| ('\u{400}'..='\u{4ff}').contains(&c)); + latin && cyrillic + }) + .count() +} + +pub struct Body { + pub title: String, + pub text: String, +} + +/// Reads a guiding text record from `.cbg`: titles and contents in one or more +/// languages; the first of each is used. +pub fn guiding_text(cbg: &[u8], offset: u32, d: &Decoder) -> Result { + let at = offset as usize; + let size = be(cbg, at + 1, 3).ok_or("text outside the .cbg file")? as usize; + let rec = cbg.get(at..at + size).ok_or("text outside the .cbg file")?; + let mut r = Le { data: rec, pos: 4 }; + let bad = || "damaged guiding text".to_owned(); + let version = r.u16().ok_or_else(bad)?; + let mut title = String::new(); + for i in 0..r.u16().ok_or_else(bad)? { + let _lang = r.u16().ok_or_else(bad)?; + let len = usize::from(r.u16().ok_or_else(bad)?); + let t = r.take(len).ok_or_else(bad)?; + if i == 0 { + title = d.decode(t).trim().to_owned(); + } + } + r.take(1).ok_or_else(bad)?; + let mut text = String::new(); + for i in 0..r.u16().ok_or_else(bad)? { + let _lang = r.u16().ok_or_else(bad)?; + let body = match version { + 1 => { + let len = usize::from(r.u16().ok_or_else(bad)?); + let t = r.take(len).ok_or_else(bad)?; + let fmt = usize::from(r.u16().ok_or_else(bad)?); + r.take(fmt).ok_or_else(bad)?; + tidy(&objects_to_breaks(&d.decode(t))) + } + 2 => { + let len = r.u32().ok_or_else(bad)? as usize; + let t = r.take(len).ok_or_else(bad)?; + let fmt = r.u32().ok_or_else(bad)? as usize; + r.take(fmt).ok_or_else(bad)?; + tidy(&objects_to_breaks(&d.decode(t))) + } + 3 => { + let len = r.u32().ok_or_else(bad)? as usize; + let t = r.take(len).ok_or_else(bad)?; + r.take(4); + html_to_text(&d.decode(t).replace(OBJECT, " ")) + } + v => return Err(format!("guiding text format {v} is not supported")), + }; + if i == 0 { + text = body; + } + } + Ok(Body { title, text }) +} + +struct Le<'a> { + data: &'a [u8], + pos: usize, +} + +impl<'a> Le<'a> { + fn take(&mut self, n: usize) -> Option<&'a [u8]> { + let s = self.data.get(self.pos..self.pos + n)?; + self.pos += n; + Some(s) + } + + fn u16(&mut self) -> Option { + self.take(2).map(|b| u16::from_le_bytes([b[0], b[1]])) + } + + fn u32(&mut self) -> Option { + self.take(4) + .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) + } +} + +/// Readable text from the HTML of a guiding text: block elements become line +/// breaks, scripts and styles are dropped, entities are decoded. +pub fn html_to_text(html: &str) -> String { + let mut out = String::new(); + let mut rest = html; + while let Some(lt) = rest.find('<') { + out.push_str(&decode_entities(&rest[..lt])); + let Some(gt) = rest[lt..].find('>') else { + rest = ""; + break; + }; + let tag = rest[lt + 1..lt + gt].trim().to_ascii_lowercase(); + rest = &rest[lt + gt + 1..]; + let name: String = tag + .trim_start_matches('/') + .chars() + .take_while(|c| c.is_ascii_alphanumeric()) + .collect(); + if !tag.starts_with('/') && matches!(name.as_str(), "script" | "style" | "head" | "title") { + let close = format!(" { + rest = &rest[end..]; + if let Some(gt) = rest.find('>') { + rest = &rest[gt + 1..]; + } + } + None => rest = "", + } + continue; + } + if matches!( + name.as_str(), + "br" | "p" | "div" | "li" | "tr" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "table" + ) && !out.ends_with('\n') + { + out.push('\n'); + } + } + out.push_str(&decode_entities(rest)); + tidy(&out) +} + +/// Plain guiding texts carry no line breaks: paragraphs start after an embedded +/// object (a diagram, a link). A run of objects becomes a paragraph break when a +/// capital letter or a digit follows, and a space otherwise ("games (• and •)"). +pub fn objects_to_breaks(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + if c != OBJECT { + out.push(c); + continue; + } + while chars + .peek() + .is_some_and(|c| *c == OBJECT || c.is_whitespace()) + { + chars.next(); + } + let next = chars.peek().copied(); + if next.is_none_or(|n| n.is_uppercase() || n.is_ascii_digit()) { + out.push('\n'); + } else { + out.push(' '); + } + } + out +} + +/// One paragraph per non-empty line, separated by a blank line; whitespace inside a +/// line collapsed. +pub fn tidy(text: &str) -> String { + // Line breaks may be "\r\n", "\n" or a lone "\r" (older ChessBase texts). + text.replace("\r\n", "\n") + .replace('\r', "\n") + .lines() + .map(|l| l.split_whitespace().collect::>().join(" ")) + .filter(|l| !l.is_empty()) + .collect::>() + .join("\n\n") +} + +fn decode_entities(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut rest = s; + while let Some(amp) = rest.find('&') { + out.push_str(&rest[..amp]); + let tail = &rest[amp..]; + let Some(semi) = tail.find(';').filter(|i| *i <= 10) else { + out.push('&'); + rest = &tail[1..]; + continue; + }; + let name = &tail[1..semi]; + let ch = match name { + "amp" => Some('&'), + "lt" => Some('<'), + "gt" => Some('>'), + "quot" => Some('"'), + "apos" => Some('\''), + "nbsp" => Some(' '), + _ => name + .strip_prefix("#x") + .or_else(|| name.strip_prefix("#X")) + .and_then(|h| u32::from_str_radix(h, 16).ok()) + .or_else(|| name.strip_prefix('#').and_then(|n| n.parse().ok())) + .and_then(char::from_u32), + }; + match ch { + Some(c) => { + out.push(c); + rest = &tail[semi + 1..]; + } + None => { + out.push('&'); + rest = &tail[1..]; + } + } + } + out.push_str(rest); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn utf8_texts_win_over_the_code_page() { + let d = Decoder::new(TextEncoding::Windows1251); + assert_eq!(d.decode("Привет".as_bytes()), "Привет"); + assert_eq!(d.decode(&[0xcf, 0xf0, 0xe8, 0xe2, 0xe5, 0xf2]), "Привет"); + assert_eq!(d.decode(b"plain"), "plain"); + } + + #[test] + fn figurines_and_diagrams() { + let d = Decoder::new(TextEncoding::Windows1252); + assert_eq!( + d.decode(b"3...\xa5g4 4 \xa4:e5 \xa6xh5 \xa7b2+ \x9e"), + "3...Bg4 4 N:e5 Rxh5 b2+ " + ); + assert_eq!( + d.decode(b"price \xa3 5"), + "price £ 5", + "not before a square" + ); + assert_eq!( + d.decode("plan \u{e027}e3, \u{e025}d2 \u{e028}c6 \u{e005}".as_bytes()), + "plan Be3, Qd2 Nc6 " + ); + } + + #[test] + fn names_pick_the_code_page_per_name() { + let d = Decoder::new(TextEncoding::Windows1251); + assert_eq!(d.decode_name(b"N\xfcrnberg"), "Nürnberg"); + assert_eq!(d.decode_name(b"\xc0\xeb\xe5\xf5\xe8\xed"), "Алехин"); + assert_eq!( + d.decode_name(b"1.7.\xe0"), + "1.7.а", + "a tie keeps the database code page" + ); + // Comments keep the database code page even when Latin squares follow Cyrillic. + assert_eq!(d.decode(b"\xcaf3"), "Кf3"); + } + + #[test] + fn embedded_objects_split_paragraphs() { + let t = + "Title! \u{4} Body text (\u{4} and \u{4}) here. \u{4}\u{4} \u{4}УПРАЖНЕНИЯ \u{4} \u{4}"; + assert_eq!( + tidy(&objects_to_breaks(t)), + "Title!\n\nBody text ( and ) here.\n\nУПРАЖНЕНИЯ" + ); + let d = Decoder::new(TextEncoding::Windows1252); + assert_eq!(d.decode(b"a\x01b\x81c\x04d"), "abc\u{4}d"); + } + + #[test] + fn html_becomes_text() { + let html = "x\ +

First line & more

Second
third ч

\ + "; + assert_eq!(html_to_text(html), "First line & more\n\nSecond\n\nthird ч"); + assert_eq!(tidy("\t\n A b \n\n\n\tc\n "), "A b\n\nc"); + assert_eq!(tidy("One\r\rTwo\r\nThree"), "One\n\nTwo\n\nThree"); + assert_eq!(html_to_text("a & b; c"), "a & b; c"); + } +} diff --git a/crates/chess-import/src/chessbase/writer.rs b/crates/chess-import/src/chessbase/writer.rs new file mode 100644 index 0000000..3433048 --- /dev/null +++ b/crates/chess-import/src/chessbase/writer.rs @@ -0,0 +1,345 @@ +//! PGN text for decoded games and guiding texts. + +use std::fmt::Write as _; + +use super::annotations::{Annotations, Item}; +use super::entities::Entities; +use super::headers::{GameHeader, TextHeader, date_tag, round_tag}; +use super::moves::Tree; +use super::text::Decoder; + +pub type Tags = Vec<(String, String)>; + +pub fn tags( + h: &GameHeader, + players: &Entities, + tournaments: &Entities, + annotators: &Entities, + d: &Decoder, +) -> Tags { + let or_q = |s: Option| s.unwrap_or_else(|| "?".into()); + let event_date = tournaments.date(h.tournament); + let mut t: Tags = vec![ + ("Event".into(), or_q(tournaments.name(h.tournament, d))), + ("Site".into(), or_q(tournaments.place(h.tournament, d))), + ("Date".into(), date_tag(h.date)), + ("Round".into(), round_tag(h.round, h.subround)), + ("White".into(), or_q(players.name(h.white, d))), + ("Black".into(), or_q(players.name(h.black, d))), + ("Result".into(), h.result_tag().into()), + ]; + if h.white_elo > 0 { + t.push(("WhiteElo".into(), h.white_elo.to_string())); + } + if h.black_elo > 0 { + t.push(("BlackElo".into(), h.black_elo.to_string())); + } + if let Some(eco) = h.eco_tag() { + t.push(("ECO".into(), eco)); + } + if let Some(a) = annotators.name(h.annotator, d) { + t.push(("Annotator".into(), a)); + } + if event_date != 0 { + t.push(("EventDate".into(), date_tag(event_date))); + } + t +} + +/// A guiding text is shown as a game without moves: the title in place of the +/// players and the text as the opening comment. +pub fn text_tags( + h: &TextHeader, + title: &str, + tournaments: &Entities, + annotators: &Entities, + d: &Decoder, +) -> Tags { + let mut t: Tags = vec![ + ( + "Event".into(), + tournaments + .name(h.tournament, d) + .unwrap_or_else(|| "?".into()), + ), + ("Site".into(), "?".into()), + ("Date".into(), "????.??.??".into()), + ("Round".into(), round_tag(h.round, h.subround)), + ( + "White".into(), + if title.is_empty() { + "?".into() + } else { + title.into() + }, + ), + ("Black".into(), String::new()), + ("Result".into(), "*".into()), + ]; + if let Some(a) = annotators.name(h.annotator, d) { + t.push(("Annotator".into(), a)); + } + t +} + +pub fn text_game(out: &mut String, tags: &Tags, text: &str) { + write_tags(out, tags, None); + let mut w = Movetext::default(); + if !text.trim().is_empty() { + w.comment(text); + } + w.token("*"); + out.push_str(&w.finish()); +} + +pub fn game(out: &mut String, tags: &Tags, tree: &Tree, notes: &Annotations, result: &str) { + // Main-line length, for the library's move count. + let mut plies = 0; + let mut node = 0; + while let Some(&next) = tree.nodes[node].children.first() { + plies += 1; + node = next; + } + let mut tags = tags.clone(); + if plies > 0 { + tags.push(("PlyCount".into(), plies.to_string())); + } + write_tags(out, &tags, tree.start_fen.as_deref()); + // Annotation position of each node. + let mut position = vec![None; tree.nodes.len()]; + for (i, n) in tree.order.iter().enumerate() { + position[*n] = i32::try_from(i).ok(); + } + let mut w = Movetext::default(); + if let Some(items) = notes.at.get(&-1) { + // Before-move texts of the whole game read as an introduction too. + let mut intro: Vec<&Item> = items.iter().collect(); + intro.sort_by_key(|i| !matches!(i, Item::Before(_))); + w.after_comment(&intro); + } + let ctx = Ctx { + tree, + notes, + position: &position, + }; + ctx.line(&mut w, 0); + w.token(result); + out.push_str(&w.finish()); +} + +struct Ctx<'a> { + tree: &'a Tree, + notes: &'a Annotations, + position: &'a [Option], +} + +impl Ctx<'_> { + /// Writes the continuation of `node`: its main move, the alternatives to that + /// move as variations, then the rest of the main line. + fn line(&self, w: &mut Movetext, mut node: usize) { + loop { + let children = &self.tree.nodes[node].children; + let Some(&main) = children.first() else { + return; + }; + self.write_move(w, main); + for &alt in &children[1..] { + w.open(); + self.write_move(w, alt); + self.line(w, alt); + w.close(); + } + node = main; + } + } + + fn write_move(&self, w: &mut Movetext, id: usize) { + let n = &self.tree.nodes[id]; + let items: &[Item] = self.position[id] + .and_then(|p| self.notes.at.get(&p)) + .map(Vec::as_slice) + .unwrap_or(&[]); + for it in items { + if let Item::Before(t) = it { + w.comment(t); + } + } + // The number and the move stay on one line. + let number = if n.white { + format!("{}. ", n.number) + } else if w.need_number { + format!("{}... ", n.number) + } else { + String::new() + }; + w.need_number = false; + w.token(&format!("{number}{}", n.san)); + for it in items { + if let Item::Nags(nags) = it { + for nag in nags { + w.token(&format!("${nag}")); + } + } + } + let after: Vec<&Item> = items + .iter() + .filter(|i| !matches!(i, Item::Before(_) | Item::Nags(_))) + .collect(); + w.after_comment(&after); + } +} + +fn write_tags(out: &mut String, tags: &Tags, fen: Option<&str>) { + for (k, v) in tags { + let _ = writeln!(out, "[{k} \"{}\"]", escape_tag(v)); + } + if let Some(fen) = fen { + let _ = writeln!(out, "[SetUp \"1\"]"); + let _ = writeln!(out, "[FEN \"{}\"]", escape_tag(fen)); + } + out.push('\n'); +} + +fn escape_tag(v: &str) -> String { + v.replace('\\', "\\\\") + .replace('"', "\\\"") + .replace(['\r', '\n'], " ") +} + +/// Movetext builder with line wrapping at 80 columns. +#[derive(Default)] +struct Movetext { + lines: Vec, + current: String, + need_number: bool, +} + +impl Movetext { + fn token(&mut self, t: &str) { + if !self.current.is_empty() && self.current.chars().count() + 1 + t.chars().count() > 80 { + self.lines.push(std::mem::take(&mut self.current)); + } + if !self.current.is_empty() && !self.current.ends_with('(') { + self.current.push(' '); + } + self.current.push_str(t); + } + + fn comment(&mut self, text: &str) { + // '}' would end the comment early; ChessBase texts rarely contain it. + let clean = text.replace('}', ")"); + self.token(&format!("{{{clean}}}")); + self.need_number = true; + } + + /// One comment with the graphics as `[%csl]`/`[%cal]`/`[%emt]` commands and the texts. + fn after_comment(&mut self, items: &[&Item]) { + let mut parts: Vec = Vec::new(); + for it in items { + match it { + Item::Squares(list) if !list.is_empty() => parts.push(format!( + "[%csl {}]", + list.iter() + .map(|(c, s)| format!("{c}{}", square(*s))) + .collect::>() + .join(",") + )), + Item::Arrows(list) if !list.is_empty() => parts.push(format!( + "[%cal {}]", + list.iter() + .map(|(c, a, b)| format!("{c}{}{}", square(*a), square(*b))) + .collect::>() + .join(",") + )), + Item::TimeSpent(h, m, s) => parts.push(format!("[%emt {h}:{m:02}:{s:02}]")), + Item::After(t) | Item::Before(t) => parts.push(t.clone()), + _ => {} + } + } + if !parts.is_empty() { + self.comment(&parts.join(" ")); + } + } + + fn open(&mut self) { + self.token("("); + self.need_number = true; + } + + fn close(&mut self) { + self.current.push(')'); + self.need_number = true; + } + + fn finish(mut self) -> String { + if !self.current.is_empty() { + self.lines.push(self.current); + } + let mut s = self.lines.join("\n"); + s.push_str("\n\n"); + s + } +} + +/// Square name from ChessBase numbering (a1 = 0, a2 = 1, … h8 = 63). +fn square(idx: u8) -> String { + let file = (b'a' + idx / 8) as char; + let rank = (b'1' + idx % 8) as char; + format!("{file}{rank}") +} + +#[cfg(test)] +mod tests { + use super::super::moves::Node; + use super::*; + + fn node(san: &str, number: u32, white: bool, children: Vec) -> Node { + Node { + san: san.into(), + number, + white, + children, + } + } + + #[test] + fn variations_comments_and_graphics() { + // 1. e4 c5 (1... c6 2. d4) 2. Nf3 + let tree = Tree { + start_fen: None, + nodes: vec![ + node("", 0, true, vec![1]), + node("e4", 1, true, vec![2, 4]), + node("c5", 1, false, vec![3]), + node("Nf3", 2, true, vec![]), + node("c6", 1, false, vec![5]), + node("d4", 2, true, vec![]), + ], + order: vec![1, 2, 3, 4, 5], + }; + let mut notes = Annotations::default(); + notes.at.insert(-1, vec![Item::After("Intro".into())]); + notes.at.insert( + 0, + vec![ + Item::Nags(vec![1]), + Item::Arrows(vec![('G', 35, 36)]), + Item::After("Best by test }".into()), + ], + ); + notes.at.insert(3, vec![Item::Before("Also".into())]); + let mut out = String::new(); + game( + &mut out, + &vec![("Event".into(), "Test \"x\"".into())], + &tree, + ¬es, + "*", + ); + assert_eq!( + out, + "[Event \"Test \\\"x\\\"\"]\n[PlyCount \"3\"]\n\n{Intro} 1. e4 $1 {[%cal Ge4e5] Best by test )} 1... c5 ({Also} 1... c6 2. d4)\n\ + 2. Nf3 *\n\n" + ); + } +} diff --git a/crates/chess-import/src/lib.rs b/crates/chess-import/src/lib.rs new file mode 100644 index 0000000..a0c90f0 --- /dev/null +++ b/crates/chess-import/src/lib.rs @@ -0,0 +1,286 @@ +//! Opening chess databases that are not plain PGN files: ChessBase databases +//! (`.cbh` with its companion files), ChessBase archives (`.cbv`), and `.zip` / +//! `.7z` archives holding any of these or PGN files. +//! +//! Everything is converted to PGN text in memory and indexed as a +//! [`PgnDatabase`], so the rest of the application works the same way for every +//! format. Sources are only read. + +mod archive; +pub mod cbv; +pub mod chessbase; + +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; + +use chess_core::{OpenError, PgnDatabase, ScanProgress, TextEncoding, detect_encoding}; + +/// File extensions the application can open (lower case). +pub const EXTENSIONS: [&str; 5] = ["pgn", "cbh", "cbv", "zip", "7z"]; + +#[derive(Debug, thiserror::Error)] +pub enum ImportError { + #[error("cannot read {path}: {source}")] + Io { + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error("{0}")] + Corrupt(String), + #[error("{0}")] + Unsupported(Unsupported), + #[error("no PGN or ChessBase database in the archive")] + Empty, + #[error("import cancelled")] + Cancelled, +} + +impl From for ImportError { + fn from(e: OpenError) -> Self { + match e { + OpenError::Io { path, source } => ImportError::Io { path, source }, + OpenError::Cancelled => ImportError::Cancelled, + } + } +} + +/// Sources that are recognized but cannot be read. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum Unsupported { + #[error("password-protected archives (.cbz, encrypted zip/7z) are not supported")] + Encrypted, + #[error("the ChessBase 2CBH format is not supported; export the database as CBH or PGN")] + ChessBase2, +} + +/// What a database was read from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Format { + Pgn, + ChessBase, + ChessBaseArchive, + Zip, + SevenZip, +} + +impl Format { + pub fn label(self) -> &'static str { + match self { + Format::Pgn => "PGN", + Format::ChessBase => "ChessBase", + Format::ChessBaseArchive => "ChessBase CBV", + Format::Zip => "ZIP", + Format::SevenZip => "7z", + } + } +} + +/// An opened database with what is worth telling the user about the conversion. +pub struct Opened { + pub db: PgnDatabase, + pub format: Format, + /// Problems and remarks, one line each (empty for a clean import). + pub notes: Vec, +} + +/// True if the file's extension is one [`open`] handles. +pub fn is_supported(path: &Path) -> bool { + path.extension() + .map(|e| e.to_string_lossy().to_lowercase()) + .is_some_and(|e| EXTENSIONS.contains(&e.as_str())) +} + +/// Opens `path`. Plain PGN files are read as before; other formats are recognized +/// by extension and by content. +pub fn open( + path: &Path, + progress: &mut dyn FnMut(ScanProgress), + cancel: &AtomicBool, +) -> Result { + let ext = path + .extension() + .map(|e| e.to_string_lossy().to_lowercase()) + .unwrap_or_default(); + let io_err = |source| ImportError::Io { + path: path.to_owned(), + source, + }; + match ext.as_str() { + "cbz" => return Err(ImportError::Unsupported(Unsupported::Encrypted)), + "2cbh" => return Err(ImportError::Unsupported(Unsupported::ChessBase2)), + "cbh" => { + let files = chessbase::Files::from_dir(path)?; + let part = convert_chessbase(&files)?; + return finish(part.pgn, Format::ChessBase, part.notes, progress, cancel); + } + _ => {} + } + // Content decides for archives (whatever their extension); anything else is PGN. + let mut head = [0u8; 8]; + { + use std::io::Read; + let mut f = std::fs::File::open(path).map_err(io_err)?; + let n = f.read(&mut head).map_err(io_err)?; + if n < head.len() { + head[n..].fill(0); + } + } + if let Some(kind) = archive::sniff(&head) { + let bytes = std::fs::read(path).map_err(io_err)?; + let format = match kind { + archive::Kind::Zip => Format::Zip, + archive::Kind::SevenZip => Format::SevenZip, + }; + let (pgn, notes) = open_archive(&bytes, kind, cancel)?; + return finish(pgn, format, notes, progress, cancel); + } + if ext == "cbv" || cbv::looks_like_cbv(&head) && ext != "pgn" { + let bytes = std::fs::read(path).map_err(io_err)?; + let part = open_cbv(&bytes)?; + return finish( + part.pgn, + Format::ChessBaseArchive, + part.notes, + progress, + cancel, + ); + } + let db = PgnDatabase::open(path, progress, cancel)?; + Ok(Opened { + db, + format: Format::Pgn, + notes: Vec::new(), + }) +} + +/// A converted part of a database: UTF-8 PGN and notes. +struct Part { + pgn: String, + notes: Vec, +} + +fn convert_chessbase(files: &chessbase::Files) -> Result { + let c = chessbase::convert(files)?; + Ok(Part { + pgn: c.pgn, + notes: c.notes, + }) +} + +fn open_cbv(bytes: &[u8]) -> Result { + let members = cbv::unpack(bytes)?; + let cbh: Vec<&str> = members + .iter() + .map(|m| m.name.as_str()) + .filter(|n| n.to_lowercase().ends_with(".cbh")) + .collect(); + let Some(first) = cbh.first() else { + return Err(ImportError::Corrupt( + "the ChessBase archive holds no database (.cbh)".into(), + )); + }; + let files = chessbase::Files::from_members( + first, + members.iter().map(|m| (m.name.as_str(), m.data.as_slice())), + ); + convert_chessbase(&files) +} + +/// Every database in an archive: PGN files, ChessBase databases and ChessBase +/// archives, in the order they are stored. A database whose games are exactly those +/// of one already taken (an archive often holds a ChessBase database both unpacked +/// and as `.cbv`) is left out. +fn open_archive( + bytes: &[u8], + kind: archive::Kind, + cancel: &AtomicBool, +) -> Result<(String, Vec), ImportError> { + let wanted = |name: &str| { + let ext = name.rsplit_once('.').map(|(_, e)| e).unwrap_or(""); + ext == "pgn" || ext == "cbv" || chessbase_member(ext) + }; + let entries = archive::read(bytes, kind, &wanted)?; + let mut parts: Vec<(String, Part)> = Vec::new(); + let mut skipped = Vec::new(); + for e in &entries { + if cancel.load(std::sync::atomic::Ordering::Relaxed) { + return Err(ImportError::Cancelled); + } + let lower = e.name.to_lowercase(); + let part = if lower.ends_with(".pgn") { + Ok(Part { + pgn: decode_pgn(&e.data), + notes: Vec::new(), + }) + } else if lower.ends_with(".cbv") { + open_cbv(&e.data) + } else if lower.ends_with(".cbh") { + let files = chessbase::Files::from_members( + &e.name, + entries.iter().map(|m| (m.name.as_str(), m.data.as_slice())), + ); + convert_chessbase(&files) + } else { + continue; + }; + match part { + Ok(p) if parts.iter().any(|(_, q)| q.pgn == p.pgn) => skipped.push(e.name.clone()), + Ok(p) => parts.push((e.name.clone(), p)), + Err(err) => parts.push(( + e.name.clone(), + Part { + pgn: String::new(), + notes: vec![err.to_string()], + }, + )), + } + } + if parts.iter().all(|(_, p)| p.pgn.is_empty()) { + if let Some((_, p)) = parts.into_iter().find(|(_, p)| !p.notes.is_empty()) { + return Err(ImportError::Corrupt(p.notes.join("; "))); + } + return Err(ImportError::Empty); + } + let several = parts.len() > 1; + let mut pgn = String::new(); + let mut notes = Vec::new(); + for (name, p) in parts { + for n in p.notes { + notes.push(if several { format!("{name}: {n}") } else { n }); + } + if !p.pgn.is_empty() { + pgn.push_str(&p.pgn); + if !pgn.ends_with("\n\n") { + pgn.push_str("\n\n"); + } + } + } + for s in skipped { + notes.push(format!( + "{s}: the same games as another database in the archive, skipped" + )); + } + Ok((pgn, notes)) +} + +fn chessbase_member(ext: &str) -> bool { + matches!(ext, "cbh" | "cbg" | "cba" | "cbp" | "cbt" | "cbc") +} + +/// PGN from an archive member, as UTF-8 (its own encoding detected). +fn decode_pgn(bytes: &[u8]) -> String { + let enc = detect_encoding(bytes).encoding; + enc.decode(bytes).0.into_owned() +} + +fn finish( + pgn: String, + format: Format, + notes: Vec, + progress: &mut dyn FnMut(ScanProgress), + cancel: &AtomicBool, +) -> Result { + let db = PgnDatabase::from_bytes(pgn.into_bytes(), Some(TextEncoding::Utf8), progress, cancel)?; + Ok(Opened { db, format, notes }) +} diff --git a/crates/chess-import/tests/formats.rs b/crates/chess-import/tests/formats.rs new file mode 100644 index 0000000..372fd92 --- /dev/null +++ b/crates/chess-import/tests/formats.rs @@ -0,0 +1,160 @@ +//! Every way into the importer: plain PGN, zip archives (with PGN in a legacy code +//! page and in folders), an unpacked ChessBase database on disk. + +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; + +use chess_import::{Format, ImportError, Opened}; + +/// A fresh directory under the system temp dir, removed on drop. +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> TempDir { + let p = std::env::temp_dir().join(format!( + "chess-import-{tag}-{}-{:?}", + std::process::id(), + std::time::SystemTime::now() + )); + std::fs::create_dir_all(&p).expect("temp dir"); + TempDir(p) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn open(path: &Path) -> Result { + let never = AtomicBool::new(false); + chess_import::open(path, &mut |_| {}, &never) +} + +const GAME: &str = "[Event \"Test\"]\n[White \"A\"]\n[Black \"B\"]\n[Result \"1-0\"]\n\n1. e4 e5 2. Qh5 Nc6 3. Bc4 Nf6 4. Qxf7# 1-0\n"; + +#[test] +fn plain_pgn_is_unchanged() { + let dir = TempDir::new("pgn"); + let p = dir.0.join("game.pgn"); + std::fs::write(&p, GAME).expect("write"); + let o = open(&p).expect("opens"); + assert_eq!(o.format, Format::Pgn); + assert_eq!(o.db.len(), 1); + assert!(o.notes.is_empty()); +} + +#[test] +fn zip_with_legacy_pgn_and_folders() { + let dir = TempDir::new("zip"); + let p = dir.0.join("games.zip"); + let file = std::fs::File::create(&p).expect("create"); + let mut zip = zip::ZipWriter::new(file); + let stored = + zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + zip.start_file("one.pgn", stored).expect("entry"); + zip.write_all(GAME.as_bytes()).expect("data"); + // A Russian comment in Windows-1251, inside a folder. + let (cp1251, _, _) = encoding_rs::WINDOWS_1251.encode( + "[Event \"Тест\"]\n[White \"Алехин\"]\n[Black \"Капабланка\"]\n[Result \"*\"]\n\n1. d4 {Хороший ход} d5 *\n", + ); + zip.add_directory("sub/", stored).expect("dir"); + zip.start_file("sub/two.PGN", stored).expect("entry"); + zip.write_all(&cp1251).expect("data"); + zip.start_file("readme.txt", stored).expect("entry"); + zip.write_all(b"not a database").expect("data"); + zip.finish().expect("finish"); + + let o = open(&p).expect("opens"); + assert_eq!(o.format, Format::Zip); + assert_eq!(o.db.len(), 2); + let second = o.db.raw_text(1).expect("text"); + assert!( + second.contains("Алехин") && second.contains("Хороший ход"), + "{second}" + ); + + // The same archive under another extension is still recognized by its content. + let renamed = dir.0.join("games.bin"); + std::fs::copy(&p, &renamed).expect("copy"); + assert_eq!(open(&renamed).expect("opens").format, Format::Zip); +} + +#[test] +fn zip_without_databases_and_unsupported_files() { + let dir = TempDir::new("empty"); + let p = dir.0.join("empty.zip"); + let mut zip = zip::ZipWriter::new(std::fs::File::create(&p).expect("create")); + zip.start_file("notes.txt", zip::write::SimpleFileOptions::default()) + .expect("entry"); + zip.write_all(b"hello").expect("data"); + zip.finish().expect("finish"); + assert!(matches!(open(&p), Err(ImportError::Empty))); + + let cbz = dir.0.join("locked.cbz"); + std::fs::write(&cbz, b"whatever").expect("write"); + assert!(matches!( + open(&cbz), + Err(ImportError::Unsupported( + chess_import::Unsupported::Encrypted + )) + )); + let broken = dir.0.join("broken.cbv"); + std::fs::write(&broken, [8u8, 0, 1, 0, 0x95, 0, 0, 0, 1, 2, 3]).expect("write"); + assert!(matches!(open(&broken), Err(ImportError::Corrupt(_)))); +} + +#[test] +fn unpacked_chessbase_database_matches_its_archive() { + // Unpack a book archive from the samples to disk and open its .cbh directly. + let samples = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../pgnFilesforExample"); + let Some(archive) = std::fs::read_dir(&samples).ok().and_then(|d| { + d.flatten() + .map(|e| e.path()) + .find(|p| p.extension().is_some_and(|e| e == "7z")) + }) else { + eprintln!("skipped: no .7z sample"); + return; + }; + let dir = TempDir::new("cbh"); + let mut cbh = None; + let mut reader = sevenz_rust2::ArchiveReader::new( + std::fs::File::open(&archive).expect("open"), + sevenz_rust2::Password::empty(), + ) + .expect("7z"); + reader + .for_each_entries(|entry, r| { + let mut data = Vec::new(); + r.read_to_end(&mut data)?; + let name = entry + .name() + .rsplit(['/', '\\']) + .next() + .unwrap_or("") + .to_owned(); + if !entry.is_directory() && !name.is_empty() && !name.ends_with(".cbv") { + let p = dir.0.join(&name); + std::fs::write(&p, data)?; + if name.ends_with(".cbh") { + cbh = Some(p); + } + } + Ok(true) + }) + .expect("unpack"); + let cbh = cbh.expect("archive holds a .cbh"); + let from_disk = open(&cbh).expect("opens"); + assert_eq!(from_disk.format, Format::ChessBase); + let from_archive = open(&archive).expect("opens"); + assert_eq!(from_disk.db.len(), from_archive.db.len()); + for i in 0..from_disk.db.len() { + assert_eq!( + from_disk.db.raw_text(i), + from_archive.db.raw_text(i), + "record {i}" + ); + } +} diff --git a/crates/chess-import/tests/samples.rs b/crates/chess-import/tests/samples.rs new file mode 100644 index 0000000..a626731 --- /dev/null +++ b/crates/chess-import/tests/samples.rs @@ -0,0 +1,123 @@ +//! Conversion of the real databases in `pgnFilesforExample/` (not in the repository: +//! the tests skip what is missing). +//! +//! Every converted game must parse back without warnings, a ChessBase database must +//! convert the same from its `.cbv` archive as unpacked, and texts must keep their +//! letters. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicBool; + +use chess_core::Severity; +use chess_import::{Format, Opened}; + +fn samples() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../pgnFilesforExample") +} + +fn open(name: &str) -> Option { + let path = samples().join(name); + if !path.exists() { + eprintln!("skipped: {} not found", path.display()); + return None; + } + let never = AtomicBool::new(false); + Some(chess_import::open(&path, &mut |_| {}, &never).expect("opens")) +} + +/// Parses every game; returns (games with moves, all PGN text joined). +fn check_all(o: &Opened) -> (usize, String) { + let mut with_moves = 0; + let mut text = String::new(); + for i in 0..o.db.len() { + let g = o.db.load_game(i).expect("game"); + assert!( + g.max_severity().is_none_or(|s| s < Severity::Warning), + "game {i}: {:?}\n{}", + g.diagnostics, + o.db.raw_text(i).unwrap_or_default() + ); + if !g.game.mainline().is_empty() { + with_moves += 1; + } + let raw = o.db.raw_text(i).unwrap_or_default(); + assert!( + !raw.chars() + .any(|c| c.is_control() && c != '\n' && c != '\t'), + "game {i}: control characters in {raw:?}" + ); + text.push_str(&raw); + } + (with_moves, text) +} + +#[test] +fn chessbase_archives_convert_cleanly() { + for (name, games, texts) in [ + ("Rubinstein russian.cbv", 129, 9), + ("Anand 01-14.cbv", 399, 0), + ("Endgame Manual.cbv", 847, 134), + ] { + let Some(o) = open(name) else { continue }; + assert_eq!(o.format, Format::ChessBaseArchive); + assert!(o.notes.is_empty(), "{name}: {:?}", o.notes); + assert_eq!(o.db.len(), games + texts, "{name}: records"); + let (with_moves, _) = check_all(&o); + // A few games of a book may be only a position with a comment. + assert!( + with_moves + texts + 5 >= games + texts, + "{name}: {with_moves} games with moves" + ); + } +} + +#[test] +fn texts_keep_their_letters() { + if let Some(o) = open("Rubinstein russian.cbv") { + let (_, text) = check_all(&o); + assert!(text.contains("Размены необходимы, чтобы уравнять игру.")); + assert!(!text.contains('\u{fffd}')); + } + if let Some(o) = open("Endgame Manual.cbv") { + let (_, text) = check_all(&o); + assert!( + text.contains("Nürnberg"), + "Western tournament names in a Russian database" + ); + assert!(!text.contains("Nьrnberg")); + } + if let Some(o) = open("Anand 01-14.cbv") { + let (_, text) = check_all(&o); + assert!(text.contains("3...Bg4"), "figurines become letters"); + // Only figurines before a square or a capture are converted; of the ~2600 in + // the book two are typos ("19 ¥5", "5...¥Ne7") and stay as they are. + assert!(text.matches('\u{a5}').count() <= 2); + assert!(!text.contains('\u{e027}')); + } +} + +#[test] +fn archives_with_both_forms_of_a_database() { + // Each book archive holds the database unpacked and as .cbv: the two conversions + // must be identical, so the archive yields one copy. + let dir = samples(); + let Ok(entries) = std::fs::read_dir(&dir) else { + eprintln!("skipped: no samples"); + return; + }; + for e in entries.flatten() { + let name = e.file_name().to_string_lossy().into_owned(); + if !name.ends_with(".7z") { + continue; + } + let o = open(&name).expect("present"); + assert_eq!(o.format, Format::SevenZip); + assert!( + o.notes.len() == 1 && o.notes[0].contains("skipped"), + "{name}: {:?}", + o.notes + ); + let (with_moves, _) = check_all(&o); + assert!(with_moves > 10, "{name}"); + } +} diff --git a/docs/decisions.md b/docs/decisions.md index 5fea721..bb45b46 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -25,6 +25,8 @@ 10. **Stockfish в комплекте** — 2026-10-18, решение пользователя: вкладываем во все пакеты (deb, rpm, Arch, AppImage, Flatpak, Windows, tar.gz), не полагаемся на системные пакеты. Официальный «universal»-бинарник Stockfish 19 без изменений (версия и SHA-256 закреплены в `packaging/stockfish.sh`), в пакетах — `/lib/chesspenguin/stockfish` или `stockfish/` рядом с exe; в настройках встроенный движок хранится признаком `builtin`, путь вычисляется при запуске (точка монтирования AppImage меняется). При первом запуске без движков добавляется встроенный, иначе системный `stockfish`. Лицензия GPL-3.0 выполняется: текст лицензии и AUTHORS в пакете, архив исходников прикладывается к каждому релизу. Пакеты выросли до ~95 МБ. +11. **Чтение ChessBase и архивов** — 2026-10-18, план принят пользователем («прям вдумчиво, грамотно»): собственный крейт `chess-import` (контейнер `.cbv` по uncbv, формат базы по открытому описанию Morphy; cbvault и uncbv — только эталоны при проверке), `.cbh` с файлами рядом, `.cbv`, `.zip` и `.7z` с PGN/ChessBase внутри. Всё переводится в PGN в памяти и открывается как обычная база, только для чтения; проблемы видны в «Замечаниях импорта». `.cbz` (пароль) и 2CBH — понятное сообщение. Подробности — `docs/dev/import.md`. + ## Следует из исходного ТЗ - Linux desktop; предпочтение стека Artcraft, подлежащего проверке по исходникам. diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index 9c7e460..6dba497 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -7,7 +7,7 @@ egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `i | Файл | Ответственность | | --- | --- | | `app.rs` | Состояние верхнего уровня: библиотека ⇄ партия, настройки, движок, фоновые диалоги (rfd в отдельных потоках), подтверждение закрытия изменённой партии | -| `library.rs` | Полка баз, фоновое сканирование (прогресс, отмена), таблица с поиском, сортировкой, клавиатурой | +| `library.rs` | Полка баз, фоновое открытие через `chess_import::open` (PGN, ChessBase, архивы; прогресс, отмена), формат и «Замечания импорта» по каждой базе, таблица с поиском, сортировкой, клавиатурой | | `game_view.rs` | Экран партии: доска, шкала оценки, панель анализа, предпросмотр PV, нотация, панель инструментов, клавиатура | | `notation.rs` | Нотация: основная линия таблицей в две колонки, комментарии/варианты блоками, вложенные варианты в скобках | | `board.rs` | Виджет доски: клик/drag, превращение, рокировка кликом на поле короля или ладью, стрелки, круги | diff --git a/docs/dev/import.md b/docs/dev/import.md new file mode 100644 index 0000000..2e5e809 --- /dev/null +++ b/docs/dev/import.md @@ -0,0 +1,59 @@ +# chess-import: ChessBase и архивы + +Статус: первая реализация, 2026-10-18. Крейт `crates/chess-import` открывает всё, что не является простым PGN, переводит в PGN-текст (UTF-8) в памяти и отдаёт обычный `PgnDatabase`. Дальше приложение работает одинаково для всех форматов: библиотека, нотация, анализ, «Сохранить как PGN». Исходные файлы только читаются. + +## Что открывается + +| Вход | Как распознаётся | Что происходит | +| --- | --- | --- | +| `.pgn` | всё, что не распознано иначе | как раньше: `PgnDatabase::open` (кодировка, ремонт букв, ленивый разбор) | +| `.cbh` | расширение | рядом лежащие файлы с тем же именем (`.cbg .cba .cbp .cbt .cbc`) читаются и конвертируются | +| `.cbv` | расширение или сигнатура `08 00` | архив ChessBase распаковывается в память, внутри ищется `.cbh` | +| `.zip`, `.7z` | сигнатура (`PK\3\4`, `7z\xBC\xAF\x27\x1C`), расширение не важно | берутся все `.pgn` (кодировка определяется для каждого), `.cbh`-базы и `.cbv`; результат склеивается в одну базу в порядке хранения | +| `.cbz`, архивы с паролем | расширение / флаг шифрования | `ImportError::Unsupported(Encrypted)` с понятным сообщением | +| `.2cbh` (новый формат CB) | расширение | `ImportError::Unsupported(ChessBase2)` | + +В архиве часто лежит одна и та же база дважды: распакованная и как `.cbv` (так в книгах Everyman). Повтор определяется по совпадению сконвертированного PGN и пропускается с заметкой. + +## Модули + +| Модуль | Назначение | +| --- | --- | +| `lib.rs` | `open(path, progress, cancel) -> Opened { db, format, notes }`, `Format`, `ImportError`, `Unsupported`, `EXTENSIONS`, `is_supported` | +| `cbv.rs` | контейнер `.cbv`: каталог, блоки, LZ77 с RLE, Хаффман | +| `archive.rs` | zip (крейт `zip`) и 7z (`sevenz-rust2`), ограничение 2 ГБ распакованного | +| `chessbase/headers.rs` | `.cbh`: записи партий и текстов (big-endian, 46 байт) | +| `chessbase/entities.rs` | `.cbp` `.cbt` `.cbc`: игроки, турниры (место, дата), комментаторы | +| `chessbase/moves.rs` | `.cbg`: стартовая позиция, кодировщики compact (режимы 0, 4) и simple (5), перестановочные таблицы, нумерация фигур, дерево вариантов | +| `chessbase/annotations.rs` | `.cba`: тексты до/после хода, знаки (NAG), цветные поля и стрелки, затраченное время | +| `chessbase/text.rs` | выбор кодировки, значки фигур, главы книг (тексты v1/v2/v3, HTML → текст) | +| `chessbase/writer.rs` | PGN: теги, нумерация, варианты, комментарии с `[%csl]/[%cal]/[%emt]`, перенос строк по 80 | + +## Источники + +- Формат контейнера `.cbv` — по uncbv (Antoni Boucher, GPL-3.0-or-later); код переписан заново без `unsafe` и с проверкой границ. +- Формат базы — по открытому описанию `format/v1` в github.com/Yarin78/morphy (как источник фактов; у проекта нет лицензии, код оттуда не берётся). +- Эталоны при разработке (не зависимости): cbvault 0.1.4 (MIT) и uncbv 0.3.1. На 7 базах из `pgnFilesforExample/` ходы и варианты совпадают с cbvault полностью; отличаются только порядок NAG «оценка + префикс» (у нас знак хода идёт первым), хвостовые пробелы в именах (мы их обрезаем) и тексты: cbvault теряет кириллицу и букву «ч», показывает значки фигур и метки диаграмм как есть. + +## Тексты + +- **Кодировка.** ChessBase её не хранит. Однобайтовая кодовая страница определяется один раз на базу (`detect_encoding` по всем именам и комментариям); текст, который является корректным UTF-8 с не-ASCII символами, берётся как UTF-8. Имена (игроки, турниры) в русской базе бывают в западной кодировке: для имён выбирается прочтение без смеси латиницы и кириллицы в одном слове («Nürnberg», а не «Nьrnberg»). В комментариях так не делается: русская запись «Кf3» законно смешивает алфавиты. +- **Значки фигур.** В однобайтовом тексте `0xA2–0xA7` = K Q N B R и пешка, в UTF-8 — `U+E024–U+E029` = K Q R B N и пешка; заменяются буквами только перед полем, `x` или `:` (опечатки вроде «¥5» остаются как есть). +- **Метки диаграмм** (`0x9E`, `U+E005`) удаляются. +- **Встроенные объекты** (`0x04`: диаграммы с подписями, ссылки на партии и главы) — их содержимое лежит в данных форматирования, устройство которых неизвестно. Серия `0x04` перед заглавной буквой или цифрой становится разрывом абзаца, иначе пробелом («games ( and )»). +- **Главы книг** (guiding texts) становятся записями без ходов: заголовок в `White`, пустой `Black`, текст — комментарий. Переводы строк бывают `\r`, `\r\n`, `\n`; каждая непустая строка — абзац (пустая строка между абзацами). Нотация показывает пустую строку в комментарии как разрыв абзаца. + +## Что не читается (и как это видно) + +- Партии в Chess960 (режимы 10, 11), «losing chess» (8, 9), режимы 1, 2, 3, 6, 7 (таблицы перестановки неизвестны) — партия попадает в базу с заголовком, а причина — в «Замечаниях импорта» (⚠ в шапке таблицы). +- Аннотации-тренировки, цитаты партий, картинки, видео, часы, оценки движка из `.cba` пропускаются. +- Медали, турнирная информация `.cbtt`, команды `.cbe`, теги `.cbl` не переносятся. + +На файлах пользователя (`pgnFilesforExample/`: 3 `.cbv` и 4 книги в `.7z`, всего ≈1900 записей) ни одной ошибки декодирования; все партии читаются обратно PGN-парсером без предупреждений (`tests/samples.rs`). + +## Проверка + +```sh +cargo test -p chess-import # модульные + форматы + реальные базы (пропускаются, если файлов нет) +cargo run -p chess-import --example convert -- "Book.cbv" > book.pgn # PGN в stdout, заметки в stderr +``` diff --git a/packaging/aur/chesspenguin-bin/.SRCINFO b/packaging/aur/chesspenguin-bin/.SRCINFO index fa97483..6c34b55 100644 --- a/packaging/aur/chesspenguin-bin/.SRCINFO +++ b/packaging/aur/chesspenguin-bin/.SRCINFO @@ -1,22 +1,22 @@ pkgbase = chesspenguin-bin - pkgdesc = Chess database: view, enter and analyse PGN games with UCI engines - pkgver = 0.1.0 + pkgdesc = Chess database: view, enter and analyse PGN games; Stockfish included + pkgver = 0.2.0 pkgrel = 1 url = https://github.com/vrubelroman/chessPenguin arch = x86_64 license = GPL-3.0-or-later + license = GPL-3.0-only depends = glibc depends = gcc-libs depends = alsa-lib depends = libxkbcommon depends = dbus depends = hicolor-icon-theme - optdepends = stockfish: chess engine for analysis optdepends = vulkan-icd-loader: GPU rendering via Vulkan provides = chesspenguin conflicts = chesspenguin options = !debug - source = https://github.com/vrubelroman/chessPenguin/releases/download/v0.1.0/ChessPenguin-0.1.0-linux-x86_64.tar.gz - sha256sums = 4d702fbe42cafad61166fc8eab9e76712b8c315bd3c6eca338b013b69cf71a29 + source = https://github.com/vrubelroman/chessPenguin/releases/download/v0.2.0/ChessPenguin-0.2.0-linux-x86_64.tar.gz + sha256sums = ce3ded091758152be7180f38179df47e33178afa651d622e47dc03e33b5d43c3 pkgname = chesspenguin-bin diff --git a/packaging/aur/chesspenguin-bin/PKGBUILD b/packaging/aur/chesspenguin-bin/PKGBUILD index 8fd658c..82a0eea 100644 --- a/packaging/aur/chesspenguin-bin/PKGBUILD +++ b/packaging/aur/chesspenguin-bin/PKGBUILD @@ -1,24 +1,27 @@ # Maintainer: vrubelroman pkgname=chesspenguin-bin _appid=io.github.vrubelroman.chessPenguin -pkgver=0.1.0 +pkgver=0.2.0 pkgrel=1 -pkgdesc="Chess database: view, enter and analyse PGN games with UCI engines" +pkgdesc="Chess database: view, enter and analyse PGN games; Stockfish included" arch=('x86_64') url="https://github.com/vrubelroman/chessPenguin" -license=('GPL-3.0-or-later') +license=('GPL-3.0-or-later' 'GPL-3.0-only') depends=('glibc' 'gcc-libs' 'alsa-lib' 'libxkbcommon' 'dbus' 'hicolor-icon-theme') -optdepends=('stockfish: chess engine for analysis' - 'vulkan-icd-loader: GPU rendering via Vulkan') +optdepends=('vulkan-icd-loader: GPU rendering via Vulkan') provides=('chesspenguin') conflicts=('chesspenguin') options=('!debug') source=("${url}/releases/download/v${pkgver}/ChessPenguin-${pkgver}-linux-x86_64.tar.gz") -sha256sums=('4d702fbe42cafad61166fc8eab9e76712b8c315bd3c6eca338b013b69cf71a29') +sha256sums=('ce3ded091758152be7180f38179df47e33178afa651d622e47dc03e33b5d43c3') package() { cd "ChessPenguin-${pkgver}-linux-x86_64" install -Dm755 chesspenguin "${pkgdir}/usr/bin/chesspenguin" + # Bundled Stockfish (GPL-3.0); the application looks for it in ../lib/chesspenguin. + install -Dm755 stockfish/stockfish "${pkgdir}/usr/lib/chesspenguin/stockfish" + install -Dm644 stockfish/Copying.txt "${pkgdir}/usr/share/licenses/${pkgname}/stockfish-Copying.txt" + install -Dm644 stockfish/AUTHORS "${pkgdir}/usr/share/doc/${pkgname}/stockfish-AUTHORS" install -Dm644 "${_appid}.desktop" "${pkgdir}/usr/share/applications/${_appid}.desktop" for size in 16 24 32 48 64 128 256 512; do install -Dm644 "icons/hicolor/${size}x${size}/apps/${_appid}.png" \