From 0f66486a2209a304f79632a54b5630ed674f8fbc Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sun, 25 Oct 2026 00:46:47 +0300 Subject: [PATCH] Own databases: create PGN bases, add, save, delete games; library logging MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Desktop: «✚ New database» on the shelf (Ctrl+Shift+N), «Add to database…» (Ctrl+Shift+S, 💾, ☰) for any game — new, pasted, from a ChessBase, online or legacy-encoded database — into a PGN of the user's choice; Ctrl+S saves the changes back into the game's own PGN (its record is replaced) or adds the game when the source is read-only; the game data editor (F2, the title, ☰) asked once when a new game is first added; duplicate check (same players, date, moves → replace / add as new, no Enter); delete from the table with a question and Undo (Ctrl+Z, 6 s, waits under the mouse); UTF-8 copy for legacy-encoded files with the restored letters; online and ChessBase stay read-only. Writes are explicit: append, or an atomic rewrite through a temporary file and a rename (through a symlink, keeping the mode, syncing the folder), refused when the file changed on the disk. chess_core::pgn::store: append/replace/remove/restore/write_utf8_copy, find_same_game, pgn_date; Game::remove_tag and order_roster. Settings: your name (annotator), the folder for new databases, the last target. Nine languages. Also: library warnings (wgpu, winit) go to chesspenguin.log, CP_LOG_FRAMES=1 traces egui_wgpu frames (the GNOME hang hunt); dev hooks CP_OWN, CP_PASTE, CP_COMMENT, CP_KEYS with Ctrl+, CP_SETTINGS=interface. Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 19 + Cargo.lock | 37 + README.md | 10 +- apps/desktop/Cargo.toml | 4 + apps/desktop/src/app.rs | 1244 +++++++++++++++++++++++++++- apps/desktop/src/game_view.rs | 135 ++- apps/desktop/src/graphics.rs | 58 ++ apps/desktop/src/i18n.rs | 1049 ++++++++++++++++++++++- apps/desktop/src/large_db.rs | 100 ++- apps/desktop/src/library.rs | 118 ++- apps/desktop/src/main.rs | 2 + apps/desktop/src/own_db.rs | 993 ++++++++++++++++++++++ apps/desktop/src/settings.rs | 9 + apps/desktop/src/settings_ui.rs | 35 + crates/chess-core/src/database.rs | 15 +- crates/chess-core/src/game.rs | 46 + crates/chess-core/src/pgn/mod.rs | 1 + crates/chess-core/src/pgn/store.rs | 616 ++++++++++++++ docs/dev/desktop.md | 3 +- docs/dev/tasks.md | 7 + 20 files changed, 4428 insertions(+), 73 deletions(-) create mode 100644 apps/desktop/src/own_db.rs create mode 100644 crates/chess-core/src/pgn/store.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 887850f..2c67be2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,25 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). +## [Unreleased] + +- Your own databases (desktop): «✚ New database» on the shelf makes an empty PGN file + (Documents/ChessPenguin by default, the folder is shown and can be changed); any game — + new, pasted, from a ChessBase, an online or any other database — is added to a PGN of + your choice with «Add to database…» (Ctrl+Shift+S, the 💾 button, the ☰ menu); Ctrl+S + saves the changes back into the game's own PGN (replacing its record) or, for a game + from a read-only source, adds it to a database. The data of a game (players, Elo, event, + site, date, round, result, annotator from «Your name» in Settings) are asked when a new + game is first added and can be edited any time (F2, the title, the ☰ menu). A game that + is already in the target (same players, date and moves) can replace its record or go in + as a new one. Games are deleted from the table (Delete, the row menu) after a question, + with Undo for six seconds (Ctrl+Z). Online databases and ChessBase files stay read-only; + a PGN in a legacy encoding is offered a UTF-8 copy next to it. Writes are explicit: + appending to the file, or rewriting it through a temporary file and a rename, with a + check that the file did not change on the disk meanwhile. The game's header names its + database and number (🔒 read-only, 🌐 online); the card menu has «Show in folder»; + «Remove from list» says where the file stays. A new game gets today's date. + ## [1.0.3] — 2026-10-24 - A new icon — a penguin in a crown — on the desktop, Android and the website. diff --git a/Cargo.lock b/Cargo.lock index 4125ddd..6625c1a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -797,6 +797,7 @@ dependencies = [ "base64 0.22.1", "chess-core", "chess-import", + "chrono", "directories", "eframe", "egui", @@ -806,6 +807,7 @@ dependencies = [ "game-review", "getrandom 0.3.4", "image", + "log", "online-games", "releases", "rfd", @@ -824,6 +826,17 @@ dependencies = [ "zip", ] +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + [[package]] name = "clap" version = "4.6.7" @@ -1949,6 +1962,30 @@ dependencies = [ "typenum", ] +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + [[package]] name = "icu_collections" version = "2.3.0" diff --git a/README.md b/README.md index 5dd65dc..c61e15a 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,12 @@ variation with one click (undoable). - **Editing** — enter moves and variations, promote or delete lines, undo/redo, copy PGN/FEN, save a game to a new file. +- **Your own databases** — create an empty PGN database, add any game to it (a new one, a + pasted one, a game from a ChessBase or online database), save your changes back + (Ctrl+S), edit the game data (players, event, date, result, annotator), delete games with + Undo. Any PGN file on the shelf takes games; writes happen only when you ask, by appending + to the file or rewriting it atomically. Online and ChessBase databases stay read-only; a + file in a legacy encoding gets a UTF-8 copy. - **Looks** — 17 piece sets, 37 boards (flat colours and textures), 7 sound sets, dark and light themes. - **Online games** — download anyone's games from Lichess and Chess.com by nickname (yours, a pupil's, an opponent's; no login) into a database, both sites merged or one per site, and fetch the new ones with one click. @@ -89,9 +95,9 @@ cargo run --release -p chesspenguin -- examples/classics.pgn | Where | Keys | | --- | --- | -| Library | ↑/↓ select · Enter open · Ctrl+O add PGN · Ctrl+N new game · Ctrl+F search | +| Library | ↑/↓ select · Enter open · Ctrl+O add database · Ctrl+Shift+N new database · Ctrl+N new game · Ctrl+F search · F2 game data · Ctrl+Shift+S add the game to another database · Delete delete the game (Ctrl+Z puts it back) | | Game | ←/→ move · ↑ end · ↓ start (also End/Home) · Shift+↑/↓ switch variation · F flip · L engine · Shift+A game analysis · Esc leave a preview, then back to the previous game or the library (unsaved edits: Esc again leaves without saving) | -| Editing | Ctrl+Z / Ctrl+Y undo/redo · Ctrl+Shift+C copy PGN · Ctrl+S save as · Ctrl+W back to library | +| Editing | Ctrl+Z / Ctrl+Y undo/redo · Ctrl+Shift+C copy PGN · Ctrl+S save to the game's database (or add to one) · Ctrl+Shift+S add to a database · F2 game data · Ctrl+W back to library | ## Project layout diff --git a/apps/desktop/Cargo.toml b/apps/desktop/Cargo.toml index 91feca7..c03c4cb 100644 --- a/apps/desktop/Cargo.toml +++ b/apps/desktop/Cargo.toml @@ -38,6 +38,10 @@ zip = { version = "9.0.5", default-features = false, features = ["deflate-flate2 sys-locale = "0.3" whatlang = "0.18.0" getrandom = "0.3" +# Today's date for a new game. +chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } +# Warnings of the window and graphics libraries into chesspenguin.log. +log = "0.4" base64 = "0.22" form_urlencoded = "1" diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 321b814..0db9975 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -13,7 +13,11 @@ use crate::analysis::Analysis; use crate::assets::Sound; use crate::game_view::{GameAction, GameSource, GameView}; use crate::library::{Library, LibraryAction}; -use crate::settings::{EngineConfig, Settings, write_atomic}; +use crate::own_db::{ + self, Answer, ChooserFor, ChooserOutcome, EditorMode, EditorOutcome, NewBaseOutcome, + QuestionKind, +}; +use crate::settings::{EngineConfig, Settings}; use crate::settings_ui::{SettingsAction, SettingsWindow, Tab}; use crate::sound::SoundPlayer; @@ -23,6 +27,118 @@ enum Async { SavePicked(PathBuf), SaveCancelled, EngineChecked(Result<(PathBuf, String), String>), + /// The folder for new databases (`None`: the dialog was cancelled). + FolderPicked(Option), +} + +/// A passing message at the bottom; `undo`: with the button that puts a deleted game back. +struct Toast { + text: String, + until: f64, + undo: bool, +} + +/// The dialogs and the pending steps of the user's own databases (own_db.rs). +#[derive(Default)] +struct Own { + new_base: Option, + chooser: Option, + editor: Option<(own_db::DataEditor, EditorThen)>, + question: Option<(own_db::Question, QuestionThen)>, + /// The advice about a big database was given this session. + big_advised: std::collections::HashSet, + /// Waits for its database to be read. + pending: Option, + /// A deleted record that can be put back (the toast's Undo, Ctrl+Z). + undo: Option, + /// Leaving the game once it is saved or added (the question about unsaved edits led + /// to the save or the chooser). + then_close: Option, +} + +enum EditorThen { + Done, + Add(PathBuf), +} + +enum QuestionThen { + Duplicate { + target: PathBuf, + index: usize, + }, + /// A record of a table is already in the target (record `at`). + DuplicateRecord { + from: PathBuf, + index: usize, + target: PathBuf, + at: usize, + }, + Delete { + path: PathBuf, + index: usize, + }, + Utf8Copy { + path: PathBuf, + dest: PathBuf, + purpose: ChooserFor, + }, + /// The write failed: the same write again. + Retry(Retry), + /// The file changed on the disk: the game can only go in as a new record. + Changed(Retry), + BigBase, +} + +/// A step that waits for a database to be read (it was just created, reloaded after a +/// write, or not opened yet). +enum Pending { + AddCurrent(PathBuf), + AppendRecord { + from: PathBuf, + index: usize, + target: PathBuf, + }, + Replace, + Undo, +} + +impl Pending { + fn path(&self, game: Option<&GameView>, undo: Option<&UndoDelete>) -> Option { + match self { + Pending::AddCurrent(p) => Some(p.clone()), + Pending::AppendRecord { target, .. } => Some(target.clone()), + Pending::Replace => game.and_then(|g| g.source.as_ref()).map(|s| s.path.clone()), + Pending::Undo => undo.map(|u| u.path.clone()), + } + } +} + +/// What to do again after a failed write. +#[derive(Clone)] +enum Retry { + Replace, + /// The duplicate's record in `target` is replaced. + ReplaceIn { + target: PathBuf, + index: usize, + }, + Append(PathBuf), + AppendRecord { + from: PathBuf, + index: usize, + target: PathBuf, + }, + Delete { + path: PathBuf, + index: usize, + }, +} + +struct UndoDelete { + path: PathBuf, + removed: chess_core::pgn::store::Removed, + /// The open game was this record: it gets its source back with the record. + open: Option, } /// The id of the toast: a passing message, never in the way of the keyboard. @@ -51,7 +167,7 @@ pub fn overlay_open_besides(ctx: &egui::Context, own: &[egui::Id]) -> bool { } #[derive(Clone, Copy, PartialEq)] -enum CloseIntent { +pub enum CloseIntent { BackToLibrary, QuitApp, /// Back to the game this one was opened from (reference tab). @@ -68,7 +184,8 @@ pub struct App { /// The live engine was stopped for a whole-game analysis and resumes after it. live_paused: bool, settings_ui: SettingsWindow, - toast: Option<(String, f64)>, + toast: Option, + own: Own, tx: Sender, rx: Receiver, confirm_close: Option, @@ -106,7 +223,7 @@ pub struct App { /// `CP_OPEN=` opens a game from the first database, `CP_PLY=` steps /// along the main line, `CP_ANALYZE=1` starts the engine, `CP_SETTINGS=1` opens settings (`=board`, `=about`: that tab), /// `CP_REVIEW=1` starts the whole-game analysis (`=dialog` only opens its dialog), -/// `CP_KEYS="ArrowDown Shift+ArrowUp Escape"` presses these keys, one every half second +/// `CP_KEYS="ArrowDown Shift+ArrowUp Ctrl+Z Escape"` presses these keys, one every half second /// from the second second. #[derive(Default)] struct DebugStartup { @@ -119,6 +236,10 @@ struct DebugStartup { screenshot_delay: f64, screenshot_requested: bool, open_settings: bool, + /// `CP_OWN=new|chooser|data|save|delete`: that dialog of the own databases + /// (own_db.rs) after a short delay; `delete` and `chooser` without a game: the + /// record `CP_OPEN` (default 0) of the first database. + own: Option, keys: std::collections::VecDeque<(Modifiers, Key)>, next_key: f64, } @@ -137,15 +258,26 @@ impl DebugStartup { .unwrap_or(4.0), screenshot_requested: false, open_settings: false, + own: std::env::var("CP_OWN").ok(), keys: std::env::var("CP_KEYS") .unwrap_or_default() .split_whitespace() .filter_map(|k| { - let (shift, name) = match k.strip_prefix("Shift+") { - Some(name) => (Modifiers::SHIFT, name), - None => (Modifiers::NONE, k), - }; - Key::from_name(name).map(|key| (shift, key)) + // "Shift+ArrowUp", "Ctrl+Z", "Ctrl+Shift+S". + let mut mods = Modifiers::NONE; + let mut name = k; + loop { + if let Some(rest) = name.strip_prefix("Shift+") { + mods |= Modifiers::SHIFT; + name = rest; + } else if let Some(rest) = name.strip_prefix("Ctrl+") { + mods |= Modifiers::COMMAND; + name = rest; + } else { + break; + } + } + Key::from_name(name).map(|key| (mods, key)) }) .collect(), next_key: 2.0, @@ -207,6 +339,7 @@ impl App { live_paused: false, settings_ui: SettingsWindow::new(), toast: None, + own: Own::default(), tx, rx, confirm_close: None, @@ -249,6 +382,7 @@ impl App { self.debug.open_settings = true; match tab.as_str() { "board" => self.settings_ui.tab = Tab::Board, + "interface" => self.settings_ui.tab = Tab::Interface, "about" => self.settings_ui.tab = Tab::About, "translation" => self.settings_ui.tab = Tab::Translation, _ => {} @@ -290,6 +424,28 @@ impl App { self.debug.open_settings = false; self.settings_ui.open = true; } + if self.debug.own.is_some() && ctx.input(|i| i.time) > 1.5 { + let what = self.debug.own.take().unwrap_or_default(); + // `CP_PASTE=`: this game is open first (a game from no database). + if let Ok(text) = std::env::var("CP_PASTE") { + self.open_pgn_text(ctx, text, false); + } + let first = self.settings.databases.first().cloned(); + let index = self.debug.open.unwrap_or(0); + match (what.as_str(), first) { + ("new", _) => self.new_base_dialog(own_db::AfterCreate::Shelf), + ("chooser", _) if self.game.is_some() => { + self.open_chooser(ctx, ChooserFor::CurrentGame) + } + ("chooser", Some(path)) => { + self.open_chooser(ctx, ChooserFor::Record { path, index }) + } + ("data", _) => self.edit_game_data(), + ("save", _) => self.save_current(ctx, None), + ("delete", Some(path)) => self.delete_game(ctx, path, index), + _ => {} + } + } let Some(path) = self.debug.screenshot.clone() else { return; }; @@ -336,6 +492,11 @@ impl App { self.open_game(ctx, path, index, None); if let Some(g) = &mut self.game { g.debug_advance(self.debug.ply); + // `CP_COMMENT=text`: a comment on the move reached, so the game counts as + // modified (to try saving it). + if let Ok(text) = std::env::var("CP_COMMENT") { + g.debug_comment(&text); + } if std::env::var("CP_ENGINE_PANEL").is_ok() { g.debug_open_engine_settings(); } @@ -356,7 +517,929 @@ impl App { } fn toast(&mut self, ctx: &egui::Context, msg: impl Into) { - self.toast = Some((msg.into(), ctx.input(|i| i.time) + 3.5)); + self.toast = Some(Toast { + text: msg.into(), + until: ctx.input(|i| i.time) + 3.5, + undo: false, + }); + } + + // ----- own databases (docs/design/own-databases.md) -------------------------------- + + /// The game on the screen, when there is one. + fn game_view(&mut self) -> Option<&mut GameView> { + self.game.as_mut() + } + + /// Ctrl+S: a game from a PGN that takes games is saved back into it; any other game + /// is added to a database of the user's choice. + fn save_current(&mut self, ctx: &egui::Context, then_close: Option) { + let Some(g) = &self.game else { return }; + self.own.then_close = then_close; + match &g.source { + Some(src) if src.block.is_none() => { + if !g.game.is_modified() { + self.toast(ctx, tr("No changes to save")); + self.finish_then_close(ctx); + return; + } + let path = src.path.clone(); + let bytes = self.library.file_size(&path); + if bytes > own_db::BIG_REWRITE_BYTES && !self.own.big_advised.contains(&path) { + self.own.big_advised.insert(path.clone()); + self.ask(QuestionKind::BigBase { path, bytes }, QuestionThen::BigBase); + return; + } + self.replace_current(ctx); + } + _ => self.open_chooser(ctx, ChooserFor::CurrentGame), + } + } + + /// Writes the game over its record in its own PGN. + fn replace_current(&mut self, ctx: &egui::Context) { + let Some(g) = &self.game else { return }; + let Some(src) = g.source.clone() else { return }; + let Some(db) = self.library.database(&src.path) else { + self.wait_for(ctx, &src.path, Pending::Replace); + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + let text = g.game.to_pgn(); + match chess_core::pgn::store::replace(pgn, src.index, &text) { + Ok(()) => { + let name = own_db::base_name(&src.path); + if let Some(g) = self.game.as_mut() { + g.game.mark_saved(); + } + self.after_written( + ctx, + &src.path, + src.index, + trf("Saved to «{name}»", &[("name", &name)]), + ); + } + Err(e) => self.write_failed(ctx, &src.path, e, Retry::Replace, false), + } + } + + /// The shelf for the chooser: each database with its count and what blocks it. + fn chooser_rows(&self) -> Vec { + self.settings + .databases + .iter() + .map(|p| own_db::ChooserRow { + path: p.clone(), + name: own_db::base_name(p), + games: self.library.database(p).map(|d| d.len()), + block: self.library.write_block(p), + }) + .collect() + } + + /// The list of databases to add a game to. + fn open_chooser(&mut self, ctx: &egui::Context, purpose: ChooserFor) { + let rows = self.chooser_rows(); + let title = match &purpose { + ChooserFor::CurrentGame => self.game.as_ref().map(|g| g.title()).unwrap_or_default(), + ChooserFor::Record { path, index } => self + .library + .database(path) + .and_then(|db| db.load_game(*index)) + .map(|p| GameView::new(p.game, None, Vec::new()).title()) + .unwrap_or_default(), + }; + let source = self + .game + .as_ref() + .and_then(|g| g.source.as_ref()) + .map(|s| s.path.clone()); + let preselect = self.settings.last_target.clone().or(source); + // Databases not read yet are read now, for their counts and encodings. + for p in self.settings.databases.clone() { + if self.library.database(&p).is_none() && p.exists() { + self.library.load(&p, ctx); + } + } + self.own.chooser = Some(own_db::Chooser::new( + rows, + preselect.as_deref(), + purpose, + title, + )); + } + + fn ask(&mut self, kind: QuestionKind, then: QuestionThen) { + self.own.question = Some((own_db::Question { kind }, then)); + } + + /// The game on the screen goes to `target`: its data are asked once for a game that + /// is in no database yet, then the duplicate check, then the write. + fn add_current_to(&mut self, ctx: &egui::Context, target: PathBuf) { + let Some(g) = &self.game else { return }; + if g.source.is_none() && !g.data_asked { + let editor = own_db::DataEditor::from_game( + &g.game, + &self.settings.your_name, + EditorMode::Add(target.clone()), + ); + self.own.editor = Some((editor, EditorThen::Add(target))); + return; + } + self.add_current_now(ctx, target); + } + + fn add_current_now(&mut self, ctx: &egui::Context, target: PathBuf) { + let Some(g) = &self.game else { return }; + let Some(db) = self.library.database(&target) else { + self.wait_for(ctx, &target, Pending::AddCurrent(target.clone())); + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + if let Some(index) = chess_core::pgn::store::find_same_game(pgn, &g.game) { + let title = g.title(); + self.ask( + QuestionKind::Duplicate { + target: target.clone(), + index, + title, + }, + QuestionThen::Duplicate { target, index }, + ); + return; + } + self.append_current(ctx, target); + } + + /// The PGN text of the game on the screen: the original record when it is an + /// unchanged game of a PGN file, else written anew. A source whose letters are + /// restored on reading (ч/ю written as `~~`/`o^`) is written anew too: the copy + /// gets the restored text. + fn current_pgn(&self) -> Option { + let g = self.game.as_ref()?; + if !g.game.is_modified() + && let Some(src) = &g.source + && let Some(db) = self.library.database(&src.path) + && let Some(pgn) = db.as_pgn() + && !pgn.repair_letters_enabled() + && let Some(text) = db.raw_text(src.index) + { + return Some(text); + } + Some(g.game.to_pgn()) + } + + /// The PGN text of record `index` of a database, as `current_pgn` would give it. + fn record_pgn(&self, from: &std::path::Path, index: usize) -> Option { + let db = self.library.database(from)?; + match db.as_pgn() { + Some(pgn) if !pgn.repair_letters_enabled() => db.raw_text(index), + _ => db.load_game(index).map(|p| p.game.to_pgn()), + } + } + + fn append_current(&mut self, ctx: &egui::Context, target: PathBuf) { + let Some(text) = self.current_pgn() else { + return; + }; + let Some(db) = self.library.database(&target) else { + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + match chess_core::pgn::store::append(pgn, &text) { + Ok(_) => { + let index = pgn.len(); + let name = own_db::base_name(&target); + if let Some(g) = self.game.as_mut() { + g.source = Some(GameSource { + path: target.clone(), + index, + block: None, + }); + g.game.mark_saved(); + } + self.settings.last_target = Some(target.clone()); + self.settings_dirty = true; + self.after_written( + ctx, + &target, + index, + trf( + "Added to «{name}» (No. {n})", + &[("name", &name), ("n", &(index + 1))], + ), + ); + } + Err(e) => self.write_failed(ctx, &target, e, Retry::Append(target.clone()), false), + } + } + + /// The game on the screen replaces record `index` of `target` (a duplicate). + fn replace_in(&mut self, ctx: &egui::Context, target: PathBuf, index: usize) { + let Some(text) = self.current_pgn() else { + return; + }; + let Some(db) = self.library.database(&target) else { + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + match chess_core::pgn::store::replace(pgn, index, &text) { + Ok(()) => { + let name = own_db::base_name(&target); + if let Some(g) = self.game.as_mut() { + g.source = Some(GameSource { + path: target.clone(), + index, + block: None, + }); + g.game.mark_saved(); + } + self.settings.last_target = Some(target.clone()); + self.settings_dirty = true; + self.after_written( + ctx, + &target, + index, + trf( + "Saved to «{name}» (No. {n})", + &[("name", &name), ("n", &(index + 1))], + ), + ); + } + Err(e) => self.write_failed( + ctx, + &target, + e, + Retry::ReplaceIn { + target: target.clone(), + index, + }, + false, + ), + } + } + + /// A record of a table goes into `target`: the duplicate check first. + fn append_record(&mut self, ctx: &egui::Context, from: PathBuf, index: usize, target: PathBuf) { + let Some(db) = self.library.database(&target) else { + self.wait_for( + ctx, + &target, + Pending::AppendRecord { + from, + index, + target: target.clone(), + }, + ); + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + let Some(parsed) = self + .library + .database(&from) + .and_then(|d| d.load_game(index)) + else { + self.toast(ctx, tr("Could not read the game")); + return; + }; + if let Some(at) = chess_core::pgn::store::find_same_game(pgn, &parsed.game) { + let title = GameView::new(parsed.game, None, Vec::new()).title(); + self.ask( + QuestionKind::Duplicate { + target: target.clone(), + index: at, + title, + }, + QuestionThen::DuplicateRecord { + from, + index, + target, + at, + }, + ); + return; + } + self.append_record_now(ctx, from, index, target); + } + + fn append_record_now( + &mut self, + ctx: &egui::Context, + from: PathBuf, + index: usize, + target: PathBuf, + ) { + let Some(text) = self.record_pgn(&from, index) else { + self.toast(ctx, tr("Could not read the game")); + return; + }; + let Some(db) = self.library.database(&target) else { + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + match chess_core::pgn::store::append(pgn, &text) { + Ok(_) => { + let n = pgn.len(); + let name = own_db::base_name(&target); + self.settings.last_target = Some(target.clone()); + self.settings_dirty = true; + self.library.reload(&target, ctx); + self.toast( + ctx, + trf( + "Added to «{name}» (No. {n})", + &[("name", &name), ("n", &(n + 1))], + ), + ); + } + Err(e) => self.write_failed( + ctx, + &target, + e, + Retry::AppendRecord { + from, + index, + target: target.clone(), + }, + false, + ), + } + } + + /// A record of a table replaces record `at` of `target` (its duplicate). + fn replace_record( + &mut self, + ctx: &egui::Context, + from: PathBuf, + index: usize, + target: PathBuf, + at: usize, + ) { + let Some(text) = self.record_pgn(&from, index) else { + self.toast(ctx, tr("Could not read the game")); + return; + }; + let Some(db) = self.library.database(&target) else { + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + match chess_core::pgn::store::replace(pgn, at, &text) { + Ok(()) => { + let name = own_db::base_name(&target); + self.settings.last_target = Some(target.clone()); + self.settings_dirty = true; + self.library.reload(&target, ctx); + self.toast( + ctx, + trf( + "Saved to «{name}» (No. {n})", + &[("name", &name), ("n", &(at + 1))], + ), + ); + } + Err(e) => self.write_failed( + ctx, + &target, + e, + Retry::ReplaceIn { + target: target.clone(), + index: at, + }, + false, + ), + } + } + + /// A step that needs the database read: it runs once the file is in (`run_pending`). + fn wait_for(&mut self, ctx: &egui::Context, path: &std::path::Path, step: Pending) { + if !self.library.loading(path) && self.library.database(path).is_none() { + self.library.load(path, ctx); + } + self.own.pending = Some(step); + } + + /// The database a step waits for is read: the step runs. Could not be read: said. + fn run_pending(&mut self, ctx: &egui::Context) { + let Some(step) = self.own.pending.as_ref() else { + return; + }; + let Some(path) = step.path(self.game.as_ref(), self.own.undo.as_ref()) else { + self.own.pending = None; + return; + }; + if self.library.database(&path).is_some() { + match self.own.pending.take().expect("pending") { + Pending::AddCurrent(target) => self.add_current_to(ctx, target), + Pending::AppendRecord { + from, + index, + target, + } => self.append_record(ctx, from, index, target), + Pending::Replace => self.replace_current(ctx), + Pending::Undo => self.undo_delete(ctx), + } + } else if !self.library.loading(&path) { + self.own.pending = None; + let why = self.library.failure(&path).unwrap_or("?").to_owned(); + self.toast(ctx, trf("Could not read the database: {e}", &[("e", &why)])); + } else { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } + } + + /// The file is written: the library reads it again and shows the record. + fn after_written( + &mut self, + ctx: &egui::Context, + path: &std::path::Path, + index: usize, + msg: String, + ) { + self.library.reload(path, ctx); + self.library.reveal(path, index); + self.toast(ctx, msg); + self.finish_then_close(ctx); + } + + fn finish_then_close(&mut self, ctx: &egui::Context) { + if let Some(intent) = self.own.then_close.take() { + self.finish_close(ctx, intent); + } + } + + fn write_failed( + &mut self, + ctx: &egui::Context, + path: &std::path::Path, + e: chess_core::pgn::store::WriteError, + retry: Retry, + deleting: bool, + ) { + use chess_core::pgn::store::WriteError; + match e { + WriteError::Changed => { + self.library.reload(path, ctx); + self.ask( + QuestionKind::ChangedOnDisk { + path: path.to_path_buf(), + deleting, + }, + QuestionThen::Changed(retry), + ); + } + e => self.ask( + QuestionKind::WriteFailed { + path: path.to_path_buf(), + error: e.to_string(), + deleting, + }, + QuestionThen::Retry(retry), + ), + } + } + + fn retry(&mut self, ctx: &egui::Context, retry: Retry) { + match retry { + Retry::Replace => self.replace_current(ctx), + Retry::ReplaceIn { target, index } => self.replace_in(ctx, target, index), + Retry::Append(target) => self.append_current(ctx, target), + Retry::AppendRecord { + from, + index, + target, + } => self.append_record(ctx, from, index, target), + Retry::Delete { path, index } => self.delete_now(ctx, path, index), + } + } + + fn delete_game(&mut self, ctx: &egui::Context, path: PathBuf, index: usize) { + if let Some(block) = self.library.write_block(&path) { + self.toast(ctx, block.long()); + return; + } + let title = self + .library + .database(&path) + .and_then(|db| db.load_game(index)) + .map(|p| GameView::new(p.game, None, Vec::new()).title()) + .unwrap_or_default(); + self.ask( + QuestionKind::Delete { + path: path.clone(), + index, + title, + }, + QuestionThen::Delete { path, index }, + ); + } + + fn delete_now(&mut self, ctx: &egui::Context, path: PathBuf, index: usize) { + let Some(db) = self.library.database(&path) else { + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + match chess_core::pgn::store::remove(pgn, index) { + Ok(removed) => { + // Games open from this file: their records moved up by one. + let mut open = None; + for g in self.game.iter_mut().chain(self.previous_games.iter_mut()) { + if let Some(s) = &mut g.source + && s.path == path + { + if s.index == index { + open = g.source.take(); + } else if s.index > index { + s.index -= 1; + } + } + } + self.own.undo = Some(UndoDelete { + path: path.clone(), + removed, + open, + }); + self.library.reload(&path, ctx); + self.library.reveal(&path, index); + self.toast = Some(Toast { + text: trf( + "Deleted from «{name}»", + &[("name", &own_db::base_name(&path))], + ), + until: ctx.input(|i| i.time) + 6.0, + undo: true, + }); + } + Err(e) => self.write_failed( + ctx, + &path, + e, + Retry::Delete { + path: path.clone(), + index, + }, + true, + ), + } + } + + /// Puts the last deleted record back (the toast's Undo, Ctrl+Z on the library). + fn undo_delete(&mut self, ctx: &egui::Context) { + let Some(undo) = self.own.undo.take() else { + return; + }; + let Some(db) = self.library.database(&undo.path) else { + // The file is still being read after the delete: as soon as it is in. + let path = undo.path.clone(); + self.own.undo = Some(undo); + self.wait_for(ctx, &path, Pending::Undo); + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + match chess_core::pgn::store::restore(pgn, &undo.removed) { + Ok(()) => { + let index = undo.removed.index; + for g in self.game.iter_mut().chain(self.previous_games.iter_mut()) { + if let Some(s) = &mut g.source + && s.path == undo.path + && s.index >= index + { + s.index += 1; + } + } + // The open game was the deleted record: it is that record again. + if let Some(src) = undo.open + && let Some(g) = self.game.as_mut() + && g.source.is_none() + { + g.source = Some(src); + } + self.library.reload(&undo.path, ctx); + self.library.reveal(&undo.path, index); + self.toast(ctx, tr("The game is back")); + } + Err(e) => self.toast(ctx, trf("Could not put the game back: {e}", &[("e", &e)])), + } + } + + fn new_base_dialog(&mut self, after: own_db::AfterCreate) { + let dir = own_db::default_base_dir(self.settings.new_database_dir.as_deref()); + self.own.new_base = Some(own_db::NewBaseDialog::new(dir, after)); + } + + /// Makes the empty file and puts it on the shelf, selected and as the database the + /// next game goes to. + fn create_base(&mut self, ctx: &egui::Context, path: PathBuf) -> Result<(), String> { + path.parent() + .map(std::fs::create_dir_all) + .unwrap_or(Ok(())) + .and_then(|()| { + std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + }) + .and_then(|f| f.sync_all()) + .map_err(|e| trf("Could not create the file: {e}", &[("e", &e)]))?; + self.settings.touch_database(&path); + self.settings.last_target = Some(path.clone()); + self.settings_dirty = true; + self.library.select_db(&path, ctx); + Ok(()) + } + + /// A new game to enter, with today's date (it is probably being played or entered + /// now). + fn new_game(&mut self) { + let mut g = Game::new(); + g.set_tag("Date", &chrono::Local::now().format("%Y.%m.%d").to_string()); + g.mark_saved(); + self.game = Some(GameView::new(g, None, Vec::new())); + } + + /// The game's data for editing (F2, the title, the menu). + fn edit_game_data(&mut self) { + let Some(g) = &self.game else { return }; + let editor = + own_db::DataEditor::from_game(&g.game, &self.settings.your_name, EditorMode::Done); + self.own.editor = Some((editor, EditorThen::Done)); + } + + fn pick_folder(&self, ctx: &egui::Context, start: PathBuf) { + self.spawn_dialog(ctx, move || { + let picked = rfd::FileDialog::new() + .set_title(tr("Folder for new databases")) + .set_directory(start) + .pick_folder(); + Some(Async::FolderPicked(picked)) + }); + } + + /// Draws the dialog that is open and acts on what was chosen. + fn own_dialogs(&mut self, ctx: &egui::Context) { + self.run_pending(ctx); + if let Some((q, _)) = self.own.question.as_mut() + && let Some(answer) = q.show(ctx) + { + let (_, then) = self.own.question.take().expect("question"); + match (then, answer) { + (QuestionThen::Duplicate { target, index }, Answer::Primary) => { + self.replace_in(ctx, target, index) + } + (QuestionThen::Duplicate { target, .. }, Answer::Secondary) => { + self.append_current(ctx, target) + } + ( + QuestionThen::DuplicateRecord { + from, + index, + target, + at, + }, + Answer::Primary, + ) => self.replace_record(ctx, from, index, target, at), + ( + QuestionThen::DuplicateRecord { + from, + index, + target, + .. + }, + Answer::Secondary, + ) => self.append_record_now(ctx, from, index, target), + (QuestionThen::Delete { path, index }, Answer::Primary) => { + self.delete_now(ctx, path, index) + } + ( + QuestionThen::Utf8Copy { + path, + dest, + purpose, + }, + Answer::Primary, + ) => { + let Some(db) = self.library.database(&path) else { + return; + }; + let Some(pgn) = db.as_pgn() else { return }; + match chess_core::pgn::store::write_utf8_copy(pgn, &dest) { + Ok(()) => { + // The copy goes on the shelf right after the original. + let at = self + .settings + .databases + .iter() + .position(|p| *p == path) + .map_or(0, |i| i + 1); + self.settings.databases.retain(|p| *p != dest); + self.settings + .databases + .insert(at.min(self.settings.databases.len()), dest.clone()); + // The copy is the one to add to: chosen in the list, which + // comes back for the same game or record. + self.settings.last_target = Some(dest.clone()); + self.settings_dirty = true; + self.library.load(&dest, ctx); + self.toast(ctx, trf("Copy made: {path}", &[("path", &dest.display())])); + self.own.chooser = None; + self.open_chooser(ctx, purpose); + } + Err(e) => { + self.toast(ctx, trf("Could not make the copy: {e}", &[("e", &e)])) + } + } + } + (QuestionThen::Retry(retry), Answer::Primary) => self.retry(ctx, retry), + (QuestionThen::Retry(_), Answer::Secondary) => { + self.open_chooser(ctx, ChooserFor::CurrentGame) + } + // After a change on the disk a record cannot be replaced: the game goes + // in as a new one ("Add as new"); a delete is only reread ("Reread"). + (QuestionThen::Changed(retry), Answer::Primary) => match retry { + Retry::Replace => { + if let Some(src) = self.game.as_ref().and_then(|g| g.source.clone()) { + self.append_current(ctx, src.path); + } + } + Retry::ReplaceIn { target, .. } | Retry::Append(target) => { + self.append_current(ctx, target) + } + Retry::AppendRecord { + from, + index, + target, + } => self.append_record(ctx, from, index, target), + Retry::Delete { .. } => {} + }, + (QuestionThen::Changed(_), Answer::Secondary) => {} + (QuestionThen::BigBase, Answer::Primary) => self.replace_current(ctx), + (QuestionThen::BigBase, Answer::Secondary) => { + self.open_chooser(ctx, ChooserFor::CurrentGame) + } + (_, Answer::Cancel) + | (QuestionThen::Delete { .. }, _) + | (QuestionThen::Utf8Copy { .. }, _) => { + if let Some(intent) = self.own.then_close.take() { + self.confirm_close = Some(intent); + } + } + } + return; + } + if let Some((editor, _)) = self.own.editor.as_mut() + && let Some(outcome) = editor.show(ctx) + { + let (editor, then) = self.own.editor.take().expect("editor"); + match (outcome, then) { + (EditorOutcome::Done, EditorThen::Done) => { + if let Some(g) = self.game_view() { + editor.apply(&mut g.game); + } + } + (EditorOutcome::Done, EditorThen::Add(target)) => { + if let Some(g) = self.game_view() { + editor.apply(&mut g.game); + g.data_asked = true; + } + self.add_current_now(ctx, target); + } + (EditorOutcome::Cancel, EditorThen::Add(_)) => { + if let Some(intent) = self.own.then_close.take() { + self.confirm_close = Some(intent); + } + } + (EditorOutcome::Cancel, EditorThen::Done) => {} + } + return; + } + if self.own.chooser.is_some() { + let rows = self.chooser_rows(); + if let Some(c) = self.own.chooser.as_mut() { + c.refresh(rows); + } + } + if let Some(chooser) = self.own.chooser.as_mut() + && let Some(outcome) = chooser.show(ctx) + { + let chooser = self.own.chooser.take().expect("chooser"); + match outcome { + ChooserOutcome::Pick(target) => match chooser.purpose { + ChooserFor::CurrentGame => self.add_current_to(ctx, target), + ChooserFor::Record { path, index } => { + self.append_record(ctx, path, index, target) + } + }, + ChooserOutcome::NewBase => { + let after = match chooser.purpose { + ChooserFor::CurrentGame => own_db::AfterCreate::AddGame, + ChooserFor::Record { path, index } => { + own_db::AfterCreate::AddRecord { path, index } + } + }; + self.new_base_dialog(after); + } + ChooserOutcome::SaveAsFile => { + self.close_after_save = self.own.then_close.take(); + self.pick_save(ctx); + } + ChooserOutcome::Utf8Copy(path) => { + let encoding = match self.library.write_block(&path) { + Some(own_db::Block::Encoding(e)) => e, + _ => "?", + }; + // "X (UTF-8).pgn", or "X (UTF-8 2).pgn" when that is taken. + let stem = own_db::base_name(&path); + let dest = (1..) + .map(|k| { + let n = if k == 1 { + String::new() + } else { + format!(" {k}") + }; + path.with_file_name(format!("{stem} (UTF-8{n}).pgn")) + }) + .find(|p| !p.exists()) + .expect("a free name"); + let purpose = chooser.purpose.clone(); + self.own.chooser = Some(chooser); + self.ask( + QuestionKind::Utf8Copy { + path: path.clone(), + dest: dest.clone(), + encoding, + }, + QuestionThen::Utf8Copy { + path, + dest, + purpose, + }, + ); + } + ChooserOutcome::Cancel => { + if let Some(intent) = self.own.then_close.take() { + self.confirm_close = Some(intent); + } + } + } + return; + } + if let Some(dialog) = self.own.new_base.as_mut() + && let Some(outcome) = dialog.show(ctx) + { + match outcome { + NewBaseOutcome::PickFolder => { + let start = dialog.dir.clone(); + self.pick_folder(ctx, start); + } + NewBaseOutcome::Cancel => { + self.own.new_base = None; + if let Some(intent) = self.own.then_close.take() { + self.confirm_close = Some(intent); + } + } + NewBaseOutcome::Create(_) | NewBaseOutcome::AddExisting(_) => { + let (create, path) = match outcome { + NewBaseOutcome::Create(p) => (true, p), + NewBaseOutcome::AddExisting(p) => (false, p), + _ => unreachable!(), + }; + let made = if create { + self.create_base(ctx, path.clone()) + } else { + self.settings.touch_database(&path); + self.settings_dirty = true; + self.library.select_db(&path, ctx); + Ok(()) + }; + match made { + // The dialog stays, with the reason, and the name typed. + Err(e) => { + if let Some(d) = self.own.new_base.as_mut() { + d.error = Some(e); + } + } + Ok(()) => { + let dialog = self.own.new_base.take().expect("dialog"); + self.settings.new_database_dir = Some(dialog.dir.clone()); + self.settings_dirty = true; + match dialog.after { + own_db::AfterCreate::Shelf => {} + own_db::AfterCreate::AddGame => { + self.wait_for(ctx, &path, Pending::AddCurrent(path.clone())) + } + own_db::AfterCreate::AddRecord { path: from, index } => { + let step = Pending::AppendRecord { + from, + index, + target: path.clone(), + }; + self.wait_for(ctx, &path, step) + } + } + } + } + } + } + } } fn play(&self, s: Sound) { @@ -461,6 +1544,14 @@ impl App { self.close_after_save = None; self.restart_to = None; } + Async::FolderPicked(Some(dir)) => { + self.settings.new_database_dir = Some(dir.clone()); + self.settings_dirty = true; + if let Some(d) = self.own.new_base.as_mut() { + d.dir = dir; + } + } + Async::FolderPicked(None) => {} Async::EngineChecked(res) => { self.settings_ui.checking_engine = false; match res { @@ -506,7 +1597,8 @@ impl App { } let Some(g) = &mut self.game else { return }; let pgn = g.game.to_pgn(); - match write_atomic(&path, pgn.as_bytes()) { + // The user's game file: synced to the disk before the rename, like a database. + match chess_core::pgn::store::write_atomic(&path, pgn.as_bytes()) { Ok(()) => { g.game.mark_saved(); self.toast(ctx, trf("Saved: {path}", &[("path", &path.display())])); @@ -538,6 +1630,7 @@ impl App { Some(GameSource { path: path.clone(), index, + block: self.library.write_block(&path), }), parsed.diagnostics, )); @@ -758,18 +1851,42 @@ impl App { return; }; let mut choice = None; + // Where the game can go (own-databases.md §3.4): back into its own PGN, or into a + // database of the user's choice. + let source = self.game.as_ref().and_then(|g| g.source.clone()); + let own = source + .as_ref() + .filter(|s| s.block.is_none()) + .map(|s| own_db::base_name(&s.path)); egui::Modal::new(egui::Id::new("confirm_close")).show(ctx, |ui| { ui.set_width(380.0); ui.heading(tr("Game modified")); if let Some(g) = &self.game { ui.label(RichText::new(g.title()).strong()); } - ui.label(tr( - "The source PGN is not changed. Save the changes to a separate file?", - )); + match (&own, &source) { + (Some(name), _) => { + ui.label(trf("Save the changes to «{name}»?", &[("name", name)])); + } + (None, Some(s)) => { + if let Some(b) = &s.block { + ui.label(b.long()); + } + ui.label(tr( + "Add the game with the changes to a database of your own?", + )); + } + (None, None) => { + ui.label(tr("The game is in no database yet. Add it to one?")); + } + } ui.add_space(8.0); ui.horizontal(|ui| { - if ui.button(tr("Save as…")).clicked() { + let primary = match &own { + Some(name) => trf("Save to «{name}»", &[("name", name)]), + None => tr("Add to database…").to_owned(), + }; + if crate::widgets::primary(ui, &primary).clicked() { choice = Some(0); } // Escape goes on where the user was going back to (the owner's choice): @@ -800,8 +1917,12 @@ impl App { match choice { Some(0) => { self.confirm_close = None; - self.close_after_save = Some(intent); - self.pick_save(ctx); + if own.is_some() { + self.save_current(ctx, Some(intent)); + } else { + self.own.then_close = Some(intent); + self.open_chooser(ctx, ChooserFor::CurrentGame); + } } Some(1) => { self.confirm_close = None; @@ -874,8 +1995,18 @@ impl eframe::App for App { if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::O))) { self.pick_databases(&ctx); } + if ctx.input_mut(|i| { + i.consume_shortcut(&KeyboardShortcut::new( + Modifiers::COMMAND | Modifiers::SHIFT, + Key::N, + )) + }) && self.game.is_none() + { + self.own.then_close = None; + self.new_base_dialog(own_db::AfterCreate::Shelf); + } if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::N))) && self.game.is_none() { - self.game = Some(GameView::new(Game::new(), None, Vec::new())); + self.new_game(); } if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::Comma))) { self.settings_ui.open = !self.settings_ui.open; @@ -950,7 +2081,12 @@ impl eframe::App for App { ctx.copy_text(text); self.toast(&ctx, msg); } - GameAction::SaveAs => self.pick_save(&ctx), + GameAction::Save => self.save_current(&ctx, None), + GameAction::AddToDatabase => { + self.own.then_close = None; + self.open_chooser(&ctx, ChooserFor::CurrentGame); + } + GameAction::EditGameData => self.edit_game_data(), GameAction::ToggleEngine => self.toggle_engine(&ctx), GameAction::EngineReconfigure => { self.settings_dirty = true; @@ -1010,9 +2146,7 @@ impl eframe::App for App { self.toast(&ctx, msg); } LibraryAction::OpenPgn(text) => self.open_pgn_text(&ctx, text, true), - LibraryAction::NewGame => { - self.game = Some(GameView::new(Game::new(), None, Vec::new())) - } + LibraryAction::NewGame => self.new_game(), LibraryAction::PastePgn => self.paste_pgn(&ctx), LibraryAction::AddDatabases => self.pick_databases(&ctx), LibraryAction::OnlineGames => self.online.open(), @@ -1022,8 +2156,32 @@ impl eframe::App for App { self.settings.databases.retain(|d| *d != p); self.library.forget(&p); self.settings_dirty = true; + // The file stays where it is; said so, with the place. + self.toast = Some(Toast { + text: trf( + "Removed from the shelf; the file stays: {path}", + &[("path", &p.display())], + ), + until: ctx.input(|i| i.time) + 6.0, + undo: false, + }); } LibraryAction::OpenSettings => self.settings_ui.open = true, + LibraryAction::NewDatabase => { + self.own.then_close = None; + self.new_base_dialog(own_db::AfterCreate::Shelf); + } + LibraryAction::DeleteGame { path, index } => { + self.delete_game(&ctx, path, index) + } + LibraryAction::AddGameToDatabase { path, index } => { + self.own.then_close = None; + self.open_chooser(&ctx, ChooserFor::Record { path, index }); + } + LibraryAction::EditGameData { path, index } => { + self.open_game(&ctx, path, index, None); + self.edit_game_data(); + } } } } @@ -1113,6 +2271,10 @@ impl eframe::App for App { SettingsAction::CheckUpdates => { self.update_check = self.update_check.again(&ctx); } + SettingsAction::PickBaseFolder => { + let start = own_db::default_base_dir(self.settings.new_database_dir.as_deref()); + self.pick_folder(&ctx, start); + } SettingsAction::OpenUpdate => self.update_ui.open = true, SettingsAction::DownloadEngine => self.engine_offer.start(&ctx), SettingsAction::CancelDownload => self.engine_offer.cancel(), @@ -1144,23 +2306,53 @@ impl eframe::App for App { } self.confirm_dialog(&ctx); + self.own_dialogs(&ctx); + // Ctrl+Z on the library while the deleted game can still come back. + if self.game.is_none() + && self.own.undo.is_some() + && self.toast.as_ref().is_some_and(|t| t.undo) + && ctx.input_mut(|i| { + i.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::Z)) + }) + { + self.undo_delete(&ctx); + } - if let Some((msg, until)) = &self.toast { + let mut undo_clicked = false; + if let Some(t) = &self.toast { let now = ctx.input(|i| i.time); - if now > *until { + if now > t.until { self.toast = None; + self.own.undo = None; } else { - egui::Area::new(egui::Id::new(TOAST)) + let (msg, undo) = (t.text.clone(), t.undo && self.own.undo.is_some()); + let area = egui::Area::new(egui::Id::new(TOAST)) .anchor(egui::Align2::CENTER_BOTTOM, egui::vec2(0.0, -24.0)) .order(egui::Order::Foreground) .show(&ctx, |ui| { egui::Frame::popup(ui.style()).show(ui, |ui| { - ui.label(RichText::new(msg.as_str()).size(14.0)); + ui.horizontal(|ui| { + ui.label(RichText::new(msg.as_str()).size(14.0)); + if undo && ui.button(tr("Undo")).on_hover_text("Ctrl+Z").clicked() { + undo_clicked = true; + } + }); }); }); + // Under the mouse the toast waits (the button is being reached for). + if undo + && area.response.contains_pointer() + && let Some(t) = self.toast.as_mut() + { + t.until = t.until.max(now + 1.5); + } ctx.request_repaint_after(std::time::Duration::from_millis(250)); } } + if undo_clicked { + self.toast = None; + self.undo_delete(&ctx); + } if self.settings_dirty && !ctx.input(|i| i.pointer.any_down()) { self.settings_dirty = false; diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 7a9e80b..8935ab2 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -18,11 +18,13 @@ use crate::notation::{Notation, NotationCommand}; use crate::review::{DialogAction, ReportAction, Review}; use crate::settings::Settings; -/// Where an opened game came from (to return to the same library row). +/// Where an opened game came from (to return to the same library row, to save into). #[derive(Clone, Debug)] pub struct GameSource { pub path: PathBuf, pub index: usize, + /// Why the game cannot be saved back there (`None`: a PGN that takes games). + pub block: Option, } /// A frozen engine line being stepped through on the board. Never changes the game. @@ -59,6 +61,8 @@ pub struct GameView { side_tab: SideTab, /// The game this one was opened from (reference tab): the title for "← back to". pub previous: Option, + /// The game's data were asked once (on its first add); not again. + pub data_asked: bool, /// A newer version to offer (its number), next to Settings. pub update: Option, /// Comments in another language, translated for reading (never into the PGN). @@ -79,7 +83,12 @@ pub enum GameAction { Back, Sound(Sound), CopyText(String, &'static str), - SaveAs, + /// Ctrl+S: into the game's own database, else "Add to database…". + Save, + /// Ctrl+Shift+S: choose the database to add the game to. + AddToDatabase, + /// F2: players, event, date, result… + EditGameData, ToggleEngine, /// Threads/Hash/MultiPV/search time of the active engine changed (settings already updated). EngineReconfigure, @@ -131,6 +140,7 @@ impl GameView { SideTab::Notation }, previous: None, + data_asked: false, update: None, translation: Default::default(), translate_now: false, @@ -163,6 +173,33 @@ impl GameView { format!("{white} — {black}") } + /// Where the game lives: «🗄 Petrov · No. 13» (🌐 an online database, 🔒 a read-only + /// one); nothing for a game that is in no database yet. + pub fn source_line(&self) -> Option { + let s = self.source.as_ref()?; + let icon = match &s.block { + None => "🗄", + Some(crate::own_db::Block::Online) => "🌐", + Some(_) => "🔒", + }; + Some(format!( + "{icon} {} · № {}", + crate::own_db::base_name(&s.path), + s.index + 1 + )) + } + + /// What Ctrl+S does to this game, for the button's tooltip. + pub fn save_hint(&self) -> String { + match &self.source { + Some(s) if s.block.is_none() => trf( + "Save to «{name}» (Ctrl+S)", + &[("name", &crate::own_db::base_name(&s.path))], + ), + _ => tr("Add to database… (Ctrl+S)").to_owned(), + } + } + fn subtitle(&self) -> String { let g = &self.game; let mut parts = Vec::new(); @@ -569,15 +606,31 @@ impl GameView { egui::Layout::top_down(egui::Align::Min), |ui| { ui.set_width(title_room); - let modified = if self.game.is_modified() { " •" } else { "" }; ui.horizontal(|ui| { ui.set_max_width(title_room); - let title = format!("{}{modified}", self.title()); - ui.allocate_ui(vec2((title_room - result_w).max(0.0), height), |ui| { - ui.add( - egui::Label::new(RichText::new(&title).strong().size(16.0)) - .truncate(), - ); + // The unsaved mark first: it must not be truncated away. + let mut mark_w = 0.0; + if self.game.is_modified() { + let mark = ui + .label(RichText::new("•").strong().size(16.0)) + .on_hover_text(tr("Unsaved changes")); + mark_w = mark.rect.width() + ui.spacing().item_spacing.x; + } + let title = self.title(); + ui.allocate_ui(vec2((title_room - result_w - mark_w).max(0.0), height), |ui| { + // The title opens the game's data (players, event, date…). + if ui + .add( + egui::Label::new(RichText::new(&title).strong().size(16.0)) + .truncate() + .sense(Sense::click()), + ) + .on_hover_text(tr("Game data (F2)")) + .on_hover_cursor(egui::CursorIcon::PointingHand) + .clicked() + { + actions.push(GameAction::EditGameData); + } }); if let Some(result) = result { ui.label( @@ -589,9 +642,13 @@ impl GameView { .on_hover_text(result_hint(self.game.result())); } }); - let sub = self.subtitle(); + let sub: Vec = self + .source_line() + .into_iter() + .chain(Some(self.subtitle()).filter(|s| !s.is_empty())) + .collect(); if !sub.is_empty() { - ui.add(egui::Label::new(RichText::new(sub).weak()).truncate()); + ui.add(egui::Label::new(RichText::new(sub.join(" · ")).weak()).truncate()); } }, ); @@ -1317,8 +1374,28 @@ impl GameView { { self.redo(); } - next_group(ui, &["☰", "📋"], 0.0); + next_group(ui, &["☰", "💾", "📋"], 0.0); ui.menu_button(big("☰"), |ui| { + if ui.button(tr("Game data… (F2)")).clicked() { + actions.push(GameAction::EditGameData); + ui.close(); + } + if let Some(s) = self.source.as_ref().filter(|s| s.block.is_none()) + && ui + .button(trf( + "Save to «{name}» (Ctrl+S)", + &[("name", &crate::own_db::base_name(&s.path))], + )) + .clicked() + { + actions.push(GameAction::Save); + ui.close(); + } + if ui.button(tr("Add to database… (Ctrl+Shift+S)")).clicked() { + actions.push(GameAction::AddToDatabase); + ui.close(); + } + ui.separator(); if ui.button(tr("Copy PGN")).clicked() { actions.push(self.copy_pgn()); ui.close(); @@ -1329,10 +1406,6 @@ impl GameView { } ui.close(); } - if ui.button(tr("Save game as…")).clicked() { - actions.push(GameAction::SaveAs); - ui.close(); - } if !self.diagnostics.is_empty() && ui.button(tr("Compatibility notes")).clicked() { self.show_diagnostics = true; ui.close(); @@ -1360,6 +1433,13 @@ impl GameView { ui.close(); } }); + if ui + .button(big("💾")) + .on_hover_text(self.save_hint()) + .clicked() + { + actions.push(GameAction::Save); + } if ui .button(big("📋")) .on_hover_text(tr("Copy PGN (Ctrl+Shift+C)")) @@ -1489,6 +1569,16 @@ impl GameView { } } + /// Dev hook (`CP_COMMENT`): a comment after the current move. + pub fn debug_comment(&mut self, text: &str) { + let nags = self + .game + .node(self.cursor) + .map(|n| n.nags().to_vec()) + .unwrap_or_default(); + let _ = self.game.annotate(self.cursor, nags, vec![text.to_owned()]); + } + fn step_back(&mut self) { if let Some(p) = &mut self.preview { self.scroll_to_cursor = true; @@ -1549,9 +1639,18 @@ impl GameView { if i.consume_shortcut(&ctrl_shift(Key::C)) { cmds.push("copy"); } + if i.consume_shortcut(&ctrl_shift(Key::S)) { + cmds.push("add_to_db"); + } if i.consume_shortcut(&ctrl(Key::S)) { cmds.push("save"); } + // F2 as in ChessBase; on a Mac F2 is the brightness key, ⌘I too. + if i.consume_key(Modifiers::NONE, Key::F2) + || (cfg!(target_os = "macos") && i.consume_shortcut(&ctrl(Key::I))) + { + cmds.push("game_data"); + } if i.consume_shortcut(&ctrl(Key::W)) { cmds.push("back"); } @@ -1593,7 +1692,9 @@ impl GameView { "undo" => self.undo(), "redo" => self.redo(), "copy" => actions.push(self.copy_pgn()), - "save" => actions.push(GameAction::SaveAs), + "save" => actions.push(GameAction::Save), + "add_to_db" => actions.push(GameAction::AddToDatabase), + "game_data" => actions.push(GameAction::EditGameData), "back" => actions.push(GameAction::Back), "find" if self.search_line().is_some() => { actions.push(GameAction::FindPosition(None)) diff --git a/apps/desktop/src/graphics.rs b/apps/desktop/src/graphics.rs index a3b277d..9ac715e 100644 --- a/apps/desktop/src/graphics.rs +++ b/apps/desktop/src/graphics.rs @@ -158,6 +158,64 @@ pub fn options(mode: Mode) -> WgpuConfiguration { } } +/// The warnings of the window and graphics libraries (wgpu, eframe, winit…) go to the log +/// and to stderr: a window that stops drawing says why there. One message repeated (a +/// dropped frame each frame) is written once a minute with how many times it came. +struct LibraryLog { + last: std::sync::Mutex>, + /// `CP_LOG_FRAMES=1`: also how each frame reaches the screen (egui_wgpu's debug and + /// trace messages: a frame skipped as "occluded" is said only there). + frames: bool, +} + +impl log::Log for LibraryLog { + fn enabled(&self, metadata: &log::Metadata) -> bool { + metadata.level() <= log::Level::Warn + || (self.frames && metadata.target().starts_with("egui_wgpu")) + } + + fn log(&self, record: &log::Record) { + if !self.enabled(record.metadata()) { + return; + } + let text = format!("{} {}: {}", record.level(), record.target(), record.args()); + let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((prev, since, count)) = last.as_mut() + && *prev == text + && since.elapsed() < std::time::Duration::from_secs(60) + { + *count += 1; + return; + } + if let Some((prev, _, count)) = last.take() + && count > 0 + { + log(&format!("{prev} (and {count} times more)")); + } + eprintln!("{text}"); + log(&text); + *last = Some((text, std::time::Instant::now(), 0)); + } + + fn flush(&self) {} +} + +/// Starts writing the libraries' warnings (see [`LibraryLog`]). +pub fn init_library_log() { + static LOGGER: OnceLock = OnceLock::new(); + let logger = LOGGER.get_or_init(|| LibraryLog { + last: std::sync::Mutex::new(None), + frames: std::env::var_os("CP_LOG_FRAMES").is_some(), + }); + if log::set_logger(logger).is_ok() { + log::set_max_level(if logger.frames { + log::LevelFilter::Trace + } else { + log::LevelFilter::Warn + }); + } +} + /// Appends a line to the log (kept under a megabyte). pub fn log(line: &str) { let Some(f) = log_file() else { diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index a79e572..4f2ddfa 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -4301,7 +4301,7 @@ const ROWS: &[[&str; 9]] = &[ ], [ "Remove from list", - "Убрать из списка", + "Убрать с полки", "Retirer de la liste", "Aus der Liste entfernen", "Quitar de la lista", @@ -8733,6 +8733,1053 @@ const ROWS: &[[&str; 9]] = &[ "GPL-3.0-or-later litsenziyasidagi erkin dastur. Figuralar to‘plamlari, taxtalar va ovozlar Lichessdan, o‘z erkin litsenziyalari asosida olingan.", "GPL-3.0-or-later лицензиясымен таратылатын еркін бағдарлама. Фигуралар жиындары, тақталар мен дыбыстар Lichess-тен, өз еркін лицензияларымен алынған.", ], + // --- own databases --- + [ + "No changes to save", + "Изменений нет", + "Aucune modification à enregistrer", + "Keine Änderungen zu speichern", + "No hay cambios que guardar", + "Nessuna modifica da salvare", + "Nenhuma alteração para salvar", + "Saqlanadigan o‘zgarish yo‘q", + "Сақтайтын өзгеріс жоқ", + ], + [ + "The database is being read — try again in a moment", + "База ещё читается — попробуйте через секунду", + "La base est en cours de lecture — réessayez dans un instant", + "Die Datenbank wird noch gelesen — versuchen Sie es gleich noch einmal", + "La base todavía se está leyendo; inténtelo de nuevo en un momento", + "Il database è ancora in lettura: riprova tra un attimo", + "A base ainda está sendo lida — tente de novo em instantes", + "Baza hali o‘qilmoqda — birozdan so‘ng qayta urinib ko‘ring", + "База әлі оқылып жатыр — сәлден соң қайталап көріңіз", + ], + [ + "Saved to «{name}»", + "Сохранено в «{name}»", + "Enregistré dans « {name} »", + "In „{name}“ gespeichert", + "Guardado en «{name}»", + "Salvato in «{name}»", + "Salvo em “{name}”", + "“{name}” bazasiga saqlandi", + "«{name}» базасына сақталды", + ], + [ + "Added to «{name}» (No. {n})", + "Добавлено в «{name}» (№ {n})", + "Ajoutée à « {name} » (n° {n})", + "Zu „{name}“ hinzugefügt (Nr. {n})", + "Añadida a «{name}» (n.º {n})", + "Aggiunta a «{name}» (n. {n})", + "Adicionada a “{name}” (nº {n})", + "“{name}” bazasiga qo‘shildi (№ {n})", + "«{name}» базасына қосылды (№ {n})", + ], + [ + "Saved to «{name}» (No. {n})", + "Сохранено в «{name}» (№ {n})", + "Enregistrée dans « {name} » (n° {n})", + "In „{name}“ gespeichert (Nr. {n})", + "Guardada en «{name}» (n.º {n})", + "Salvata in «{name}» (n. {n})", + "Salva em “{name}” (nº {n})", + "“{name}” bazasiga saqlandi (№ {n})", + "«{name}» базасына сақталды (№ {n})", + ], + [ + "Deleted from «{name}»", + "Удалено из «{name}»", + "Supprimée de « {name} »", + "Aus „{name}“ gelöscht", + "Eliminada de «{name}»", + "Eliminata da «{name}»", + "Excluída de “{name}”", + "“{name}” bazasidan o‘chirildi", + "«{name}» базасынан жойылды", + ], + [ + "The game is back", + "Партия возвращена", + "La partie est rétablie", + "Die Partie ist wieder da", + "La partida se ha restaurado", + "La partita è stata ripristinata", + "A partida foi restaurada", + "Partiya qaytarildi", + "Партия қайтарылды", + ], + [ + "Could not put the game back: {e}", + "Не удалось вернуть партию: {e}", + "Impossible de rétablir la partie : {e}", + "Die Partie konnte nicht wiederhergestellt werden: {e}", + "No se pudo restaurar la partida: {e}", + "Impossibile ripristinare la partita: {e}", + "Não foi possível restaurar a partida: {e}", + "Partiyani qaytarib bo‘lmadi: {e}", + "Партияны қайтару мүмкін болмады: {e}", + ], + [ + "Could not create the file: {e}", + "Не удалось создать файл: {e}", + "Impossible de créer le fichier : {e}", + "Die Datei konnte nicht erstellt werden: {e}", + "No se pudo crear el archivo: {e}", + "Impossibile creare il file: {e}", + "Não foi possível criar o arquivo: {e}", + "Faylni yaratib bo‘lmadi: {e}", + "Файлды жасау мүмкін болмады: {e}", + ], + [ + "Folder for new databases", + "Папка новых баз", + "Dossier des nouvelles bases", + "Ordner für neue Datenbanken", + "Carpeta para bases nuevas", + "Cartella dei nuovi database", + "Pasta para novas bases", + "Yangi bazalar jildi", + "Жаңа базалар қалтасы", + ], + [ + "Copy made: {path}", + "Копия создана: {path}", + "Copie créée : {path}", + "Kopie erstellt: {path}", + "Copia creada: {path}", + "Copia creata: {path}", + "Cópia criada: {path}", + "Nusxa yaratildi: {path}", + "Көшірме жасалды: {path}", + ], + [ + "Could not make the copy: {e}", + "Не удалось создать копию: {e}", + "Impossible de créer la copie : {e}", + "Die Kopie konnte nicht erstellt werden: {e}", + "No se pudo crear la copia: {e}", + "Impossibile creare la copia: {e}", + "Não foi possível criar a cópia: {e}", + "Nusxa yaratib bo‘lmadi: {e}", + "Көшірме жасау мүмкін болмады: {e}", + ], + [ + "Save the changes to «{name}»?", + "Сохранить изменения в «{name}»?", + "Enregistrer les modifications dans « {name} » ?", + "Änderungen in „{name}“ speichern?", + "¿Guardar los cambios en «{name}»?", + "Salvare le modifiche in «{name}»?", + "Salvar as alterações em “{name}”?", + "O‘zgarishlar “{name}” bazasiga saqlansinmi?", + "Өзгерістер «{name}» базасына сақталсын ба?", + ], + [ + "The game is in no database yet. Add it to one?", + "Партия пока не в базе. Добавить её в базу?", + "La partie n’est encore dans aucune base. L’ajouter à une base ?", + "Die Partie ist noch in keiner Datenbank. In eine aufnehmen?", + "La partida aún no está en ninguna base. ¿Añadirla a una?", + "La partita non è ancora in nessun database. Aggiungerla a uno?", + "A partida ainda não está em nenhuma base. Adicioná-la a uma?", + "Partiya hali hech qaysi bazada emas. Bazaga qo‘shilsinmi?", + "Партия әлі ешбір базада жоқ. Базаға қосылсын ба?", + ], + [ + "Save to «{name}»", + "Сохранить в «{name}»", + "Enregistrer dans « {name} »", + "In „{name}“ speichern", + "Guardar en «{name}»", + "Salva in «{name}»", + "Salvar em “{name}”", + "“{name}” bazasiga saqlash", + "«{name}» базасына сақтау", + ], + [ + "Add to database…", + "Добавить в базу…", + "Ajouter à une base…", + "Zur Datenbank hinzufügen…", + "Añadir a una base…", + "Aggiungi a un database…", + "Adicionar a uma base…", + "Bazaga qo‘shish…", + "Базаға қосу…", + ], + [ + "Removed from the shelf; the file stays: {path}", + "Убрано с полки; файл остался: {path}", + "Retirée de l’étagère ; le fichier reste : {path}", + "Aus dem Regal entfernt; die Datei bleibt erhalten: {path}", + "Quitada del estante; el archivo se conserva: {path}", + "Rimosso dallo scaffale; il file resta: {path}", + "Removida da estante; o arquivo continua em: {path}", + "Javondan olindi; fayl joyida qoldi: {path}", + "Сөреден алынды; файл орнында қалды: {path}", + ], + [ + "Save to «{name}» (Ctrl+S)", + "Сохранить в «{name}» (Ctrl+S)", + "Enregistrer dans « {name} » (Ctrl+S)", + "In „{name}“ speichern (Ctrl+S)", + "Guardar en «{name}» (Ctrl+S)", + "Salva in «{name}» (Ctrl+S)", + "Salvar em “{name}” (Ctrl+S)", + "“{name}” bazasiga saqlash (Ctrl+S)", + "«{name}» базасына сақтау (Ctrl+S)", + ], + [ + "Add to database… (Ctrl+S)", + "Добавить в базу… (Ctrl+S)", + "Ajouter à une base… (Ctrl+S)", + "Zur Datenbank hinzufügen… (Ctrl+S)", + "Añadir a una base… (Ctrl+S)", + "Aggiungi a un database… (Ctrl+S)", + "Adicionar a uma base… (Ctrl+S)", + "Bazaga qo‘shish… (Ctrl+S)", + "Базаға қосу… (Ctrl+S)", + ], + [ + "Game data (F2)", + "Данные партии (F2)", + "Données de la partie (F2)", + "Partiedaten (F2)", + "Datos de la partida (F2)", + "Dati della partita (F2)", + "Dados da partida (F2)", + "Partiya maʼlumotlari (F2)", + "Партия деректері (F2)", + ], + [ + "Game data… (F2)", + "Данные партии… (F2)", + "Données de la partie… (F2)", + "Partiedaten… (F2)", + "Datos de la partida… (F2)", + "Dati della partita… (F2)", + "Dados da partida… (F2)", + "Partiya maʼlumotlari… (F2)", + "Партия деректері… (F2)", + ], + [ + "Add to database… (Ctrl+Shift+S)", + "Добавить в базу… (Ctrl+Shift+S)", + "Ajouter à une base… (Ctrl+Shift+S)", + "Zur Datenbank hinzufügen… (Ctrl+Shift+S)", + "Añadir a una base… (Ctrl+Shift+S)", + "Aggiungi a un database… (Ctrl+Shift+S)", + "Adicionar a uma base… (Ctrl+Shift+S)", + "Bazaga qo‘shish… (Ctrl+Shift+S)", + "Базаға қосу… (Ctrl+Shift+S)", + ], + [ + "No games in «{name}» yet", + "В базе «{name}» пока нет партий", + "Aucune partie dans « {name} » pour l’instant", + "Noch keine Partien in „{name}“", + "Aún no hay partidas en «{name}»", + "Ancora nessuna partita in «{name}»", + "Ainda não há partidas em “{name}”", + "“{name}” bazasida hali partiya yo‘q", + "«{name}» базасында әзірге партия жоқ", + ], + [ + "Add one: ♟ New game, or «Add to database…» (Ctrl+Shift+S) from any game.", + "Добавьте: ♟ Новая партия или «Добавить в базу…» (Ctrl+Shift+S) из любой партии.", + "Ajoutez-en une : ♟ Nouvelle partie, ou « Ajouter à une base… » (Ctrl+Shift+S) depuis n’importe quelle partie.", + "Fügen Sie eine hinzu: ♟ Neue Partie oder „Zur Datenbank hinzufügen…“ (Ctrl+Shift+S) aus einer beliebigen Partie.", + "Añada una: ♟ Nueva partida, o «Añadir a una base…» (Ctrl+Shift+S) desde cualquier partida.", + "Aggiungine una: ♟ Nuova partita, oppure «Aggiungi a un database…» (Ctrl+Shift+S) da qualsiasi partita.", + "Adicione uma: ♟ Nova partida, ou “Adicionar a uma base…” (Ctrl+Shift+S) a partir de qualquer partida.", + "Partiya qo‘shing: ♟ Yangi partiya yoki istalgan partiyadan “Bazaga qo‘shish…” (Ctrl+Shift+S).", + "Партия қосыңыз: ♟ Жаңа партия немесе кез келген партиядан «Базаға қосу…» (Ctrl+Shift+S).", + ], + [ + "Open", + "Открыть", + "Ouvrir", + "Öffnen", + "Abrir", + "Apri", + "Abrir", + "Ochish", + "Ашу", + ], + [ + "Delete from the database… (Delete)", + "Удалить из базы… (Delete)", + "Supprimer de la base… (Delete)", + "Aus der Datenbank löschen… (Delete)", + "Eliminar de la base… (Delete)", + "Elimina dal database… (Delete)", + "Excluir da base… (Delete)", + "Bazadan o‘chirish… (Delete)", + "Базадан жою… (Delete)", + ], + [ + "✚ New database", + "✚ Новая база", + "✚ Nouvelle base", + "✚ Neue Datenbank", + "✚ Nueva base", + "✚ Nuovo database", + "✚ Nova base", + "✚ Yangi baza", + "✚ Жаңа база", + ], + [ + "Add database…", + "Добавить базу…", + "Ajouter une base…", + "Datenbank hinzufügen…", + "Añadir base…", + "Aggiungi database…", + "Adicionar base…", + "Baza qo‘shish…", + "База қосу…", + ], + [ + "New database…", + "Новая база…", + "Nouvelle base…", + "Neue Datenbank…", + "Nueva base…", + "Nuovo database…", + "Nova base…", + "Yangi baza…", + "Жаңа база…", + ], + [ + "An empty PGN file for your own games (Ctrl+Shift+N)", + "Пустой PGN-файл для своих партий (Ctrl+Shift+N)", + "Un fichier PGN vide pour vos propres parties (Ctrl+Shift+N)", + "Eine leere PGN-Datei für Ihre eigenen Partien (Ctrl+Shift+N)", + "Un archivo PGN vacío para sus propias partidas (Ctrl+Shift+N)", + "Un file PGN vuoto per le tue partite (Ctrl+Shift+N)", + "Um arquivo PGN vazio para suas próprias partidas (Ctrl+Shift+N)", + "O‘z partiyalaringiz uchun bo‘sh PGN fayl (Ctrl+Shift+N)", + "Өз партияларыңызға арналған бос PGN файлы (Ctrl+Shift+N)", + ], + [ + "Show in folder", + "Показать в папке", + "Afficher dans le dossier", + "Im Ordner zeigen", + "Mostrar en la carpeta", + "Mostra nella cartella", + "Mostrar na pasta", + "Jildda ko‘rsatish", + "Қалтада көрсету", + ], + [ + "updates itself from Lichess and Chess.com", + "обновляется сама с Lichess и Chess.com", + "mise à jour automatique depuis Lichess et Chess.com", + "wird automatisch von Lichess und Chess.com aktualisiert", + "se actualiza sola desde Lichess y Chess.com", + "si aggiorna da solo da Lichess e Chess.com", + "é atualizada sozinha pelo Lichess e pelo Chess.com", + "Lichess va Chess.com orqali o‘zi yangilanadi", + "Lichess пен Chess.com арқылы өзі жаңарады", + ], + [ + "read only", + "только чтение", + "lecture seule", + "schreibgeschützt", + "solo lectura", + "sola lettura", + "somente leitura", + "faqat o‘qish uchun", + "тек оқуға арналған", + ], + [ + "encoding {enc} — a UTF-8 copy can take games", + "кодировка {enc} — партии можно добавлять в копию в UTF-8", + "encodage {enc} — une copie en UTF-8 peut recevoir des parties", + "Kodierung {enc} — Partien können in eine UTF-8-Kopie aufgenommen werden", + "codificación {enc} — las partidas se pueden añadir a una copia en UTF-8", + "codifica {enc} — le partite si possono aggiungere a una copia in UTF-8", + "codificação {enc} — as partidas podem ser adicionadas a uma cópia em UTF-8", + "kodlash {enc} — partiyalarni UTF-8 dagi nusxaga qo‘shish mumkin", + "кодтау {enc} — партияларды UTF-8 көшірмесіне қосуға болады", + ], + [ + "no permission to write the file", + "нет прав на запись файла", + "pas de droit d’écriture sur le fichier", + "keine Schreibrechte für die Datei", + "sin permiso para escribir el archivo", + "nessun permesso di scrittura sul file", + "sem permissão para gravar o arquivo", + "faylga yozishga ruxsat yo‘q", + "файлға жазуға рұқсат жоқ", + ], + [ + "This database is downloaded from Lichess and Chess.com and updates itself: a game added by hand would be lost at the next update. Add the game to a database of your own.", + "Эта база скачана с Lichess и Chess.com и обновляется сама: партия, добавленная вручную, пропадёт при следующем обновлении. Добавьте партию в свою базу.", + "Cette base est téléchargée depuis Lichess et Chess.com et se met à jour toute seule : une partie ajoutée à la main serait perdue à la prochaine mise à jour. Ajoutez la partie à l’une de vos propres bases.", + "Diese Datenbank wird von Lichess und Chess.com heruntergeladen und aktualisiert sich selbst: Eine von Hand hinzugefügte Partie ginge beim nächsten Update verloren. Fügen Sie die Partie einer eigenen Datenbank hinzu.", + "Esta base se descarga de Lichess y Chess.com y se actualiza sola: una partida añadida a mano se perdería en la próxima actualización. Añada la partida a una base propia.", + "Questo database viene scaricato da Lichess e Chess.com e si aggiorna da solo: una partita aggiunta a mano andrebbe persa al prossimo aggiornamento. Aggiungi la partita a un tuo database.", + "Esta base é baixada do Lichess e do Chess.com e se atualiza sozinha: uma partida adicionada à mão seria perdida na próxima atualização. Adicione a partida a uma base sua.", + "Bu baza Lichess va Chess.com saytlaridan yuklab olinadi va o‘zi yangilanadi: qo‘lda qo‘shilgan partiya keyingi yangilanishda yo‘qoladi. Partiyani o‘z bazangizga qo‘shing.", + "Бұл база Lichess пен Chess.com сайттарынан жүктеледі және өзі жаңарады: қолмен қосылған партия келесі жаңартуда жоғалады. Партияны өз базаңызға қосыңыз.", + ], + [ + "ChessBase databases and archives are only read. Add the game to a PGN database of your own.", + "Базы ChessBase и архивы только читаются. Добавьте партию в свою PGN-базу.", + "Les bases ChessBase et les archives sont en lecture seule. Ajoutez la partie à l’une de vos bases PGN.", + "ChessBase-Datenbanken und Archive werden nur gelesen. Fügen Sie die Partie einer eigenen PGN-Datenbank hinzu.", + "Las bases de ChessBase y los archivos comprimidos solo se leen. Añada la partida a una base PGN propia.", + "I database ChessBase e gli archivi vengono solo letti. Aggiungi la partita a un tuo database PGN.", + "Bases do ChessBase e arquivos compactados são apenas lidos. Adicione a partida a uma base PGN sua.", + "ChessBase bazalari va arxivlar faqat o‘qiladi. Partiyani o‘z PGN bazangizga qo‘shing.", + "ChessBase базалары мен архивтер тек оқылады. Партияны өз PGN базаңызға қосыңыз.", + ], + [ + "This file is in the {enc} encoding; games are written in UTF-8. Make a copy of it in UTF-8 and add games to the copy — the original stays as it is.", + "Этот файл в кодировке {enc}, а партии записываются в UTF-8. Создайте его копию в UTF-8 и добавляйте партии в копию — исходный файл останется как есть.", + "Ce fichier est en encodage {enc} ; les parties sont écrites en UTF-8. Créez-en une copie en UTF-8 et ajoutez les parties à la copie — l’original reste intact.", + "Diese Datei hat die Kodierung {enc}; Partien werden in UTF-8 geschrieben. Erstellen Sie eine UTF-8-Kopie und fügen Sie die Partien der Kopie hinzu — das Original bleibt unverändert.", + "Este archivo está en la codificación {enc}, y las partidas se escriben en UTF-8. Cree una copia en UTF-8 y añada las partidas a la copia; el original queda como está.", + "Questo file è nella codifica {enc}, mentre le partite vengono scritte in UTF-8. Creane una copia in UTF-8 e aggiungi le partite alla copia: l’originale resta com’è.", + "Este arquivo está na codificação {enc}, e as partidas são gravadas em UTF-8. Crie uma cópia dele em UTF-8 e adicione as partidas à cópia — o original fica como está.", + "Bu fayl {enc} kodlashida, partiyalar esa UTF-8 da yoziladi. Uning UTF-8 dagi nusxasini yarating va partiyalarni nusxaga qo‘shing — asl fayl o‘zgarmaydi.", + "Бұл файл {enc} кодтауында, ал партиялар UTF-8 форматында жазылады. Оның UTF-8 көшірмесін жасап, партияларды көшірмеге қосыңыз — түпнұсқа файл өзгермейді.", + ], + [ + "The file cannot be written: no permission.", + "Файл нельзя записать: нет прав.", + "Impossible d’écrire dans le fichier : pas de droits.", + "Die Datei kann nicht geschrieben werden: keine Berechtigung.", + "No se puede escribir el archivo: no hay permiso.", + "Impossibile scrivere il file: permesso negato.", + "Não é possível gravar o arquivo: sem permissão.", + "Faylga yozib bo‘lmaydi: ruxsat yo‘q.", + "Файлға жазу мүмкін емес: рұқсат жоқ.", + ], + [ + "The file is not on the disk any more.", + "Файла больше нет на диске.", + "Le fichier n’est plus sur le disque.", + "Die Datei ist nicht mehr auf dem Datenträger.", + "El archivo ya no está en el disco.", + "Il file non è più sul disco.", + "O arquivo não está mais no disco.", + "Fayl endi diskda yo‘q.", + "Файл енді дискіде жоқ.", + ], + [ + "A name cannot have / \\ : * ? \" < > |", + "В имени нельзя использовать / \\ : * ? \" < > |", + "Un nom ne peut pas contenir / \\ : * ? \" < > |", + "Im Namen sind nicht erlaubt: / \\ : * ? \" < > |", + "Un nombre no puede contener / \\ : * ? \" < > |", + "Un nome non può contenere / \\ : * ? \" < > |", + "Um nome não pode conter / \\ : * ? \" < > |", + "Nomda bo‘lishi mumkin emas: / \\ : * ? \" < > |", + "Атауда болмауы керек: / \\ : * ? \" < > |", + ], + [ + "New database", + "Новая база", + "Nouvelle base", + "Neue Datenbank", + "Nueva base", + "Nuovo database", + "Nova base", + "Yangi baza", + "Жаңа база", + ], + [ + "e.g. Petrov, My games, Sicilian", + "например, Петров, Мои партии, Сицилианская", + "par ex. Dupont, Mes parties, Sicilienne", + "z. B. Müller, Meine Partien, Sizilianisch", + "p. ej., García, Mis partidas, Siciliana", + "ad es. Rossi, Le mie partite, Siciliana", + "ex.: Silva, Minhas partidas, Siciliana", + "masalan, Karimov, Mening partiyalarim, Sitsiliya", + "мысалы, Ахметов, Менің партияларым, Сицилия", + ], + [ + "File:", + "Файл:", + "Fichier :", + "Datei:", + "Archivo:", + "File:", + "Arquivo:", + "Fayl:", + "Файл:", + ], + [ + "A file with this name is already there.", + "Файл с таким именем уже есть.", + "Un fichier portant ce nom existe déjà.", + "Eine Datei mit diesem Namen gibt es bereits.", + "Ya existe un archivo con este nombre.", + "Esiste già un file con questo nome.", + "Já existe um arquivo com este nome.", + "Bunday nomli fayl allaqachon bor.", + "Бұл атаумен файл бұрыннан бар.", + ], + [ + "Create", + "Создать", + "Créer", + "Erstellen", + "Crear", + "Crea", + "Criar", + "Yaratish", + "Жасау", + ], + [ + "Put it on the shelf", + "Поставить на полку", + "Mettre sur l’étagère", + "Ins Regal stellen", + "Poner en el estante", + "Metti sullo scaffale", + "Colocar na estante", + "Javonga qo‘yish", + "Сөреге қою", + ], + [ + "Add to database", + "Добавить в базу", + "Ajouter à une base", + "Zur Datenbank hinzufügen", + "Añadir a una base", + "Aggiungi a un database", + "Adicionar a uma base", + "Bazaga qo‘shish", + "Базаға қосу", + ], + [ + "🔍 Find a database", + "🔍 Найти базу", + "🔍 Trouver une base", + "🔍 Datenbank suchen", + "🔍 Buscar una base", + "🔍 Cerca un database", + "🔍 Procurar uma base", + "🔍 Baza qidirish", + "🔍 База іздеу", + ], + [ + "No PGN databases on the shelf yet — create one below.", + "На полке пока нет PGN-баз — создайте ниже.", + "Pas encore de base PGN sur l’étagère — créez-en une ci-dessous.", + "Noch keine PGN-Datenbanken im Regal — legen Sie unten eine an.", + "Aún no hay bases PGN en el estante; cree una abajo.", + "Ancora nessun database PGN sullo scaffale: creane uno qui sotto.", + "Ainda não há bases PGN na estante — crie uma abaixo.", + "Javonda hali PGN bazalar yo‘q — quyida yarating.", + "Сөреде әзірге PGN базалары жоқ — төменде жасаңыз.", + ], + [ + "Make a copy in UTF-8 and add the game to it", + "Создать копию в UTF-8 и добавить партию в неё", + "Créer une copie en UTF-8 et y ajouter la partie", + "Eine UTF-8-Kopie erstellen und die Partie dort hinzufügen", + "Crear una copia en UTF-8 y añadirle la partida", + "Crea una copia in UTF-8 e aggiungici la partita", + "Criar uma cópia em UTF-8 e adicionar a partida a ela", + "UTF-8 da nusxa yaratib, partiyani unga qo‘shish", + "UTF-8 көшірмесін жасап, партияны соған қосу", + ], + [ + "✚ New database…", + "✚ Новая база…", + "✚ Nouvelle base…", + "✚ Neue Datenbank…", + "✚ Nueva base…", + "✚ Nuovo database…", + "✚ Nova base…", + "✚ Yangi baza…", + "✚ Жаңа база…", + ], + [ + "Save as a file…", + "Сохранить как файл…", + "Enregistrer dans un fichier…", + "Als Datei speichern…", + "Guardar como archivo…", + "Salva come file…", + "Salvar como arquivo…", + "Fayl sifatida saqlash…", + "Файл ретінде сақтау…", + ], + [ + "A separate PGN file with this game only; it is not put on the shelf", + "Отдельный PGN-файл только с этой партией; на полку не ставится", + "Un fichier PGN distinct avec cette seule partie ; il n’est pas mis sur l’étagère", + "Eine eigene PGN-Datei nur mit dieser Partie; sie kommt nicht ins Regal", + "Un archivo PGN aparte solo con esta partida; no se pone en el estante", + "Un file PGN a parte con solo questa partita; non viene messo sullo scaffale", + "Um arquivo PGN separado só com esta partida; ele não vai para a estante", + "Faqat shu partiya bo‘lgan alohida PGN fayl; javonga qo‘yilmaydi", + "Тек осы партиясы бар бөлек PGN файлы; сөреге қойылмайды", + ], + [ + "Game data", + "Данные партии", + "Données de la partie", + "Partiedaten", + "Datos de la partida", + "Dati della partita", + "Dados da partida", + "Partiya maʼlumotlari", + "Партия деректері", + ], + [ + "Surname, Name", + "Фамилия, Имя", + "Nom, Prénom", + "Nachname, Vorname", + "Apellido, Nombre", + "Cognome, Nome", + "Sobrenome, Nome", + "Familiya, Ism", + "Тегі, Аты", + ], + [ + "Site", + "Место", + "Lieu", + "Ort", + "Lugar", + "Luogo", + "Local", + "Joy", + "Орны", + ], + [ + "2026.10.18, 18.10.2026, 2026.10, 2026 or empty", + "2026.10.18, 18.10.2026, 2026.10, 2026 или пусто", + "2026.10.18, 18.10.2026, 2026.10, 2026 ou vide", + "2026.10.18, 18.10.2026, 2026.10, 2026 oder leer", + "2026.10.18, 18.10.2026, 2026.10, 2026 o vacío", + "2026.10.18, 18.10.2026, 2026.10, 2026 o vuoto", + "2026.10.18, 18.10.2026, 2026.10, 2026 ou vazio", + "2026.10.18, 18.10.2026, 2026.10, 2026 yoki bo‘sh", + "2026.10.18, 18.10.2026, 2026.10, 2026 немесе бос", + ], + [ + "Done", + "Готово", + "Terminé", + "Fertig", + "Listo", + "Fatto", + "Concluído", + "Tayyor", + "Дайын", + ], + [ + "Add to «{name}»", + "Добавить в «{name}»", + "Ajouter à « {name} »", + "Zu „{name}“ hinzufügen", + "Añadir a «{name}»", + "Aggiungi a «{name}»", + "Adicionar a “{name}”", + "“{name}” bazasiga qo‘shish", + "«{name}» базасына қосу", + ], + [ + "This game is already there", + "Такая партия уже есть", + "Cette partie y est déjà", + "Diese Partie ist schon vorhanden", + "Esta partida ya está ahí", + "Questa partita c’è già", + "Esta partida já está lá", + "Bu partiya allaqachon bor", + "Бұл партия бұрыннан бар", + ], + [ + "Replace No. {n}", + "Заменить № {n}", + "Remplacer le n° {n}", + "Nr. {n} ersetzen", + "Reemplazar n.º {n}", + "Sostituisci n. {n}", + "Substituir nº {n}", + "Almashtirish: № {n}", + "Ауыстыру: № {n}", + ], + [ + "Add as new", + "Добавить как новую", + "Ajouter comme nouvelle", + "Als neue hinzufügen", + "Añadir como nueva", + "Aggiungi come nuova", + "Adicionar como nova", + "Yangi sifatida qo‘shish", + "Жаңа ретінде қосу", + ], + [ + "A copy in UTF-8", + "Копия в UTF-8", + "Une copie en UTF-8", + "Eine Kopie in UTF-8", + "Una copia en UTF-8", + "Una copia in UTF-8", + "Uma cópia em UTF-8", + "UTF-8 dagi nusxa", + "UTF-8 көшірмесі", + ], + [ + "«{name}» is in the {enc} encoding, and games are written in UTF-8. A copy «{copy}» will be made next to it with all its games; the game is added to the copy, the original stays as it is.", + "«{name}» в кодировке {enc}, а партии записываются в UTF-8. Рядом будет создана копия «{copy}» со всеми партиями; партия добавится в копию, исходный файл останется как есть.", + "« {name} » est en encodage {enc}, alors que les parties sont écrites en UTF-8. Une copie « {copy} » contenant toutes ses parties sera créée à côté ; la partie est ajoutée à la copie, l’original reste intact.", + "„{name}“ hat die Kodierung {enc}, Partien werden aber in UTF-8 geschrieben. Daneben wird eine Kopie „{copy}“ mit allen Partien erstellt; die Partie kommt in die Kopie, das Original bleibt unverändert.", + "«{name}» está en la codificación {enc}, y las partidas se escriben en UTF-8. Al lado se creará una copia «{copy}» con todas sus partidas; la partida se añade a la copia y el original queda como está.", + "«{name}» è nella codifica {enc}, mentre le partite vengono scritte in UTF-8. Accanto verrà creata una copia «{copy}» con tutte le sue partite; la partita viene aggiunta alla copia, l’originale resta com’è.", + "“{name}” está na codificação {enc}, e as partidas são gravadas em UTF-8. Ao lado será criada uma cópia “{copy}” com todas as partidas; a partida é adicionada à cópia, o original fica como está.", + "“{name}” {enc} kodlashida, partiyalar esa UTF-8 da yoziladi. Yonida barcha partiyalari bilan “{copy}” nusxasi yaratiladi; partiya nusxaga qo‘shiladi, asl fayl o‘zgarmaydi.", + "«{name}» {enc} кодтауында, ал партиялар UTF-8 форматында жазылады. Қасында барлық партиялары бар «{copy}» көшірмесі жасалады; партия көшірмеге қосылады, түпнұсқа файл өзгермейді.", + ], + [ + "Make the copy", + "Создать копию", + "Créer la copie", + "Kopie erstellen", + "Crear la copia", + "Crea la copia", + "Criar a cópia", + "Nusxa yaratish", + "Көшірме жасау", + ], + [ + "Could not delete", + "Не удалось удалить", + "Impossible de supprimer", + "Löschen fehlgeschlagen", + "No se pudo eliminar", + "Impossibile eliminare", + "Não foi possível excluir", + "O‘chirib bo‘lmadi", + "Жою мүмкін болмады", + ], + [ + "Could not save", + "Не удалось сохранить", + "Impossible d’enregistrer", + "Speichern fehlgeschlagen", + "No se pudo guardar", + "Impossibile salvare", + "Não foi possível salvar", + "Saqlab bo‘lmadi", + "Сақтау мүмкін болмады", + ], + [ + "Add to another database…", + "Добавить в другую базу…", + "Ajouter à une autre base…", + "Zu einer anderen Datenbank hinzufügen…", + "Añadir a otra base…", + "Aggiungi a un altro database…", + "Adicionar a outra base…", + "Boshqa bazaga qo‘shish…", + "Басқа базаға қосу…", + ], + [ + "The file changed on disk", + "Файл изменился на диске", + "Le fichier a changé sur le disque", + "Die Datei wurde auf dem Datenträger geändert", + "El archivo cambió en el disco", + "Il file è cambiato sul disco", + "O arquivo mudou no disco", + "Fayl diskda o‘zgardi", + "Файл дискіде өзгерді", + ], + [ + "«{name}» was changed by another program since it was read. Reread it and look again.", + "«{name}» изменила другая программа после чтения. Перечитайте и посмотрите снова.", + "Un autre programme a modifié « {name} » depuis sa lecture. Relisez le fichier et vérifiez de nouveau.", + "„{name}“ wurde seit dem Lesen von einem anderen Programm geändert. Lesen Sie die Datei neu ein und sehen Sie noch einmal nach.", + "Otro programa modificó «{name}» después de la lectura. Vuelva a leer el archivo y revíselo de nuevo.", + "Un altro programma ha modificato «{name}» dopo la lettura. Rileggi il file e controlla di nuovo.", + "Outro programa alterou “{name}” depois da leitura. Releia o arquivo e confira de novo.", + "“{name}” o‘qilgandan keyin boshqa dastur tomonidan o‘zgartirildi. Faylni qayta o‘qing va yana bir bor qarang.", + "«{name}» оқылғаннан кейін оны басқа бағдарлама өзгертті. Файлды қайта оқып, тағы бір қараңыз.", + ], + [ + "«{name}» was changed by another program since it was read. The game can be added to it as a new one; replacing a record in it would need a fresh read first.", + "«{name}» изменила другая программа после чтения. Партию можно добавить как новую; чтобы заменить запись, файл надо сначала перечитать.", + "Un autre programme a modifié « {name} » depuis sa lecture. La partie peut y être ajoutée comme nouvelle ; pour remplacer une partie existante, il faut d’abord relire le fichier.", + "„{name}“ wurde seit dem Lesen von einem anderen Programm geändert. Die Partie kann als neue hinzugefügt werden; um einen Eintrag zu ersetzen, muss die Datei zuerst neu eingelesen werden.", + "Otro programa modificó «{name}» después de la lectura. La partida puede añadirse como nueva; para reemplazar un registro, primero hay que volver a leer el archivo.", + "Un altro programma ha modificato «{name}» dopo la lettura. La partita può essere aggiunta come nuova; per sostituire una voce bisogna prima rileggere il file.", + "Outro programa alterou “{name}” depois da leitura. A partida pode ser adicionada como nova; para substituir um registro, é preciso reler o arquivo primeiro.", + "“{name}” o‘qilgandan keyin boshqa dastur tomonidan o‘zgartirildi. Partiyani yangi sifatida qo‘shish mumkin; yozuvni almashtirish uchun avval faylni qayta o‘qish kerak.", + "«{name}» оқылғаннан кейін оны басқа бағдарлама өзгертті. Партияны жаңа ретінде қосуға болады; жазбаны ауыстыру үшін алдымен файлды қайта оқу керек.", + ], + [ + "Reread", + "Перечитать", + "Relire", + "Neu einlesen", + "Volver a leer", + "Rileggi", + "Reler", + "Qayta o‘qish", + "Қайта оқу", + ], + [ + "A big database", + "Большая база", + "Une grande base", + "Eine große Datenbank", + "Una base grande", + "Un database grande", + "Uma base grande", + "Katta baza", + "Үлкен база", + ], + [ + "«{name}» is {mb} MB: saving a game into it rewrites the whole file, which takes a while. Your own games are handier in a smaller database of their own.", + "«{name}» весит {mb} МБ: сохранение партии переписывает весь файл, это занимает время. Свои партии удобнее держать в отдельной небольшой базе.", + "« {name} » pèse {mb} Mo : y enregistrer une partie réécrit tout le fichier, ce qui prend du temps. Vos propres parties sont plus pratiques dans une petite base à part.", + "„{name}“ ist {mb} MB groß: Das Speichern einer Partie schreibt die ganze Datei neu, das dauert eine Weile. Eigene Partien sind in einer kleineren, eigenen Datenbank besser aufgehoben.", + "«{name}» ocupa {mb} MB: guardar una partida en ella reescribe todo el archivo, lo que lleva un tiempo. Sus propias partidas son más cómodas en una base aparte más pequeña.", + "«{name}» occupa {mb} MB: salvarvi una partita riscrive l’intero file, il che richiede tempo. Le tue partite sono più comode in un database a parte, più piccolo.", + "“{name}” tem {mb} MB: salvar uma partida nela regrava o arquivo inteiro, o que leva um tempo. Suas próprias partidas ficam mais práticas em uma base separada e menor.", + "“{name}” hajmi {mb} MB: unga partiya saqlash butun faylni qayta yozadi, bu vaqt oladi. O‘z partiyalaringizni alohida kichik bazada saqlash qulayroq.", + "«{name}» көлемі {mb} МБ: оған партия сақтау бүкіл файлды қайта жазады, бұл уақыт алады. Өз партияларыңызды бөлек шағын базада сақтаған ыңғайлы.", + ], + [ + "Save anyway", + "Всё равно сохранить", + "Enregistrer quand même", + "Trotzdem speichern", + "Guardar de todos modos", + "Salva comunque", + "Salvar mesmo assim", + "Baribir saqlash", + "Бәрібір сақтау", + ], + [ + "Your databases", + "Свои базы", + "Vos bases", + "Ihre Datenbanken", + "Sus bases", + "I tuoi database", + "Suas bases", + "Sizning bazalaringiz", + "Өз базаларыңыз", + ], + [ + "Your name:", + "Ваше имя:", + "Votre nom :", + "Ihr Name:", + "Su nombre:", + "Il tuo nome:", + "Seu nome:", + "Ismingiz:", + "Атыңыз:", + ], + [ + "Written as the annotator of the games you add", + "Записывается комментатором добавляемых партий", + "Inscrit comme commentateur des parties que vous ajoutez", + "Wird als Kommentator der hinzugefügten Partien eingetragen", + "Se anota como comentarista de las partidas que añada", + "Viene scritto come commentatore delle partite che aggiungi", + "É registrado como comentarista das partidas que você adicionar", + "Qo‘shiladigan partiyalarning izohlovchisi sifatida yoziladi", + "Қосылатын партиялардың түсініктеме авторы ретінде жазылады", + ], + [ + "Folder for new databases:", + "Папка новых баз:", + "Dossier des nouvelles bases :", + "Ordner für neue Datenbanken:", + "Carpeta para bases nuevas:", + "Cartella dei nuovi database:", + "Pasta para novas bases:", + "Yangi bazalar jildi:", + "Жаңа базалар қалтасы:", + ], + [ + "Change…", + "Изменить…", + "Modifier…", + "Ändern…", + "Cambiar…", + "Cambia…", + "Alterar…", + "O‘zgartirish…", + "Өзгерту…", + ], + // --- own databases, second batch --- + [ + "Add the game with the changes to a database of your own?", + "Добавить партию с изменениями в свою базу?", + "Ajouter la partie avec les modifications à l’une de vos bases ?", + "Die Partie mit den Änderungen in eine eigene Datenbank aufnehmen?", + "¿Añadir la partida con los cambios a una base propia?", + "Aggiungere la partita con le modifiche a un tuo database?", + "Adicionar a partida com as alterações a uma base própria?", + "Partiyani o‘zgarishlar bilan o‘z bazangizga qo‘shasizmi?", + "Партияны өзгерістерімен өз базаңызға қосасыз ба?", + ], + [ + "Unsaved changes", + "Несохранённые изменения", + "Modifications non enregistrées", + "Nicht gespeicherte Änderungen", + "Cambios sin guardar", + "Modifiche non salvate", + "Alterações não salvas", + "Saqlanmagan o‘zgarishlar", + "Сақталмаған өзгерістер", + ], + [ + "File: {path}", + "Файл: {path}", + "Fichier : {path}", + "Datei: {path}", + "Archivo: {path}", + "File: {path}", + "Arquivo: {path}", + "Fayl: {path}", + "Файл: {path}", + ], + [ + "Title", + "Название", + "Nom", + "Name", + "Nombre", + "Nome", + "Nome", + "Nomi", + "Атауы", + ], + [ + "Change folder…", + "Изменить папку…", + "Changer de dossier…", + "Ordner ändern…", + "Cambiar carpeta…", + "Cambia cartella…", + "Alterar pasta…", + "Papkani o‘zgartirish…", + "Қалтаны өзгерту…", + ], + [ + "reading…", + "читается…", + "lecture…", + "wird gelesen…", + "leyendo…", + "in lettura…", + "lendo…", + "o‘qilmoqda…", + "оқылуда…", + ], + [ + "Make a copy in UTF-8…", + "Сделать копию в UTF-8…", + "Créer une copie en UTF-8…", + "UTF-8-Kopie erstellen…", + "Crear una copia en UTF-8…", + "Crea una copia in UTF-8…", + "Criar uma cópia em UTF-8…", + "UTF-8 da nusxa yaratish…", + "UTF-8 көшірмесін жасау…", + ], + [ + "Game data → «{name}»", + "Данные партии → «{name}»", + "Données de la partie → « {name} »", + "Partiedaten → „{name}“", + "Datos de la partida → «{name}»", + "Dati della partita → «{name}»", + "Dados da partida → “{name}”", + "Partiya maʼlumotlari → “{name}”", + "Партия деректері → «{name}»", + ], + [ + "YYYY.MM.DD", + "ГГГГ.ММ.ДД", + "AAAA.MM.JJ", + "JJJJ.MM.TT", + "AAAA.MM.DD", + "AAAA.MM.GG", + "AAAA.MM.DD", + "YYYY.OO.KK", + "ЖЖЖЖ.АА.КК", + ], + [ + "Other tags stay as they are: {tags}", + "Другие теги сохранятся: {tags}", + "Les autres balises restent inchangées : {tags}", + "Andere Tags bleiben unverändert: {tags}", + "Las demás etiquetas se mantienen: {tags}", + "Gli altri tag restano invariati: {tags}", + "As outras tags permanecem como estão: {tags}", + "Boshqa teglar o‘zgarmaydi: {tags}", + "Басқа тегтер өзгермейді: {tags}", + ], + [ + "«{name}» already has this game: No. {n}, {title} — the same players, date and moves.", + "В «{name}» уже есть эта партия: № {n}, {title} — те же игроки, дата и ходы.", + "« {name} » contient déjà cette partie : n° {n}, {title} — mêmes joueurs, même date et mêmes coups.", + "„{name}“ enthält diese Partie bereits: Nr. {n}, {title} — dieselben Spieler, dasselbe Datum und dieselben Züge.", + "«{name}» ya tiene esta partida: n.º {n}, {title} — los mismos jugadores, la misma fecha y las mismas jugadas.", + "«{name}» contiene già questa partita: n. {n}, {title} — stessi giocatori, stessa data e stesse mosse.", + "“{name}” já tem esta partida: nº {n}, {title} — os mesmos jogadores, a mesma data e os mesmos lances.", + "“{name}” bazasida bu partiya allaqachon bor: № {n}, {title} — o‘yinchilar, sana va yurishlar bir xil.", + "«{name}» базасында бұл партия бұрыннан бар: № {n}, {title} — ойыншылары, күні және жүрістері бірдей.", + ], + [ + "Delete the game from the database?", + "Удалить партию из базы?", + "Supprimer la partie de la base ?", + "Die Partie aus der Datenbank löschen?", + "¿Eliminar la partida de la base?", + "Eliminare la partita dal database?", + "Excluir a partida da base?", + "Partiyani bazadan o‘chirasizmi?", + "Партияны базадан жоясыз ба?", + ], + [ + "«{title}» (No. {n}) is removed from the file «{file}»; other databases are not touched. Undo is offered for a few seconds.", + "«{title}» (№ {n}) будет удалена из файла «{file}»; другие базы не затрагиваются. Несколько секунд можно отменить.", + "« {title} » (n° {n}) sera supprimée du fichier « {file} » ; les autres bases ne sont pas touchées. Vous pourrez annuler pendant quelques secondes.", + "„{title}“ (Nr. {n}) wird aus der Datei „{file}“ gelöscht; andere Datenbanken bleiben unberührt. Einige Sekunden lang lässt sich das rückgängig machen.", + "«{title}» (n.º {n}) se eliminará del archivo «{file}»; las demás bases no se modifican. Durante unos segundos se podrá deshacer.", + "«{title}» (n. {n}) verrà eliminata dal file «{file}»; gli altri database non vengono toccati. Per qualche secondo si potrà annullare.", + "“{title}” (nº {n}) será excluída do arquivo “{file}”; as outras bases não são afetadas. Por alguns segundos, será possível desfazer.", + "“{title}” (№ {n}) “{file}” faylidan o‘chiriladi; boshqa bazalarga tegilmaydi. Bir necha soniya davomida bekor qilish mumkin.", + "«{title}» (№ {n}) «{file}» файлынан жойылады; басқа базаларға әсер етпейді. Бірнеше секунд бойы болдырмауға болады.", + ], + [ + "Could not read the database: {e}", + "Не удалось прочитать базу: {e}", + "Impossible de lire la base : {e}", + "Die Datenbank konnte nicht gelesen werden: {e}", + "No se pudo leer la base: {e}", + "Impossibile leggere il database: {e}", + "Não foi possível ler a base: {e}", + "Bazani o‘qib bo‘lmadi: {e}", + "Базаны оқу мүмкін болмады: {e}", + ], ]; #[cfg(test)] diff --git a/apps/desktop/src/large_db.rs b/apps/desktop/src/large_db.rs index 2e689f1..94dd1dc 100644 --- a/apps/desktop/src/large_db.rs +++ b/apps/desktop/src/large_db.rs @@ -319,6 +319,11 @@ pub struct LargeView { blocked: Option, /// Ctrl+F asked for the quick search. focus_search: bool, + /// The database takes games (delete, add a copy): set by `table`. + writable: bool, + /// The file was read again: the next list is the same list, not a new filter (the + /// place in the table and the selection stay). + rereading: bool, /// The window is too narrow for the filters beside the table: they open over it /// (`drawer_open`), and too narrow for the board beside it: one at a time (§2). narrow_filters: bool, @@ -406,6 +411,8 @@ impl LargeView { books: false, blocked: None, focus_search: false, + writable: false, + rereading: false, search_focused: false, narrow_filters: drawer, narrow_board: false, @@ -431,6 +438,7 @@ impl LargeView { pub fn reread(&mut self, db: &Database) { self.job = None; self.shown = None; + self.rereading = true; self.outcome = None; self.in_order = None; self.cache.clear(); @@ -585,13 +593,15 @@ impl LargeView { { let job = self.job.take().expect("job"); if let Some(answer) = result { - let new_filter = self.shown.as_ref().is_none_or(|s| { - s.filter != job.request.filter - || s.use_position != job.request.use_position - || (job.request.use_position - && s.position.as_ref().map(|p| p.0) - != job.request.position.as_ref().map(|p| p.0)) - }); + let rereading = std::mem::take(&mut self.rereading); + let new_filter = !rereading + && self.shown.as_ref().is_none_or(|s| { + s.filter != job.request.filter + || s.use_position != job.request.use_position + || (job.request.use_position + && s.position.as_ref().map(|p| p.0) + != job.request.position.as_ref().map(|p| p.0)) + }); if let (Some(out), Some(pos)) = (&answer.outcome, &job.request.position) { let kept: usize = self.cache.values().map(|o| o.matches.len()).sum(); if kept + out.matches.len() > CACHE_MATCHES { @@ -1599,13 +1609,39 @@ impl LargeView { viewed: &mut Viewed, notes: usize, settings: &Settings, + writable: bool, actions: &mut Vec, ) -> bool { let mut open_notes = false; self.update(db, ui.ctx()); + self.writable = writable; let now = ui.input(|i| i.time); let progress = self.slow_progress(now, db.len()); let total = db.games() + db.texts(); + // A database with no games yet (own-databases.md §2.3): how to put one in. + if total == 0 && writable { + let name = crate::own_db::base_name(path); + ui.vertical_centered(|ui| { + ui.add_space(60.0); + ui.label( + RichText::new(trf("No games in «{name}» yet", &[("name", &name)])).size(16.0), + ); + ui.add_space(6.0); + ui.label( + RichText::new(tr( + "Add one: ♟ New game, or «Add to database…» (Ctrl+Shift+S) from any game.", + )) + .weak(), + ); + ui.add_space(6.0); + ui.label(RichText::new(trf("File: {path}", &[("path", &path.display())])).weak()); + ui.add_space(10.0); + if ui.button(tr("♟ New game")).clicked() { + actions.push(LibraryAction::NewGame); + } + }); + return open_notes; + } // The header (docs/design/narrow-windows.md §2.4), by importance: the pane switch, // the quick search (220, down to 140), the counter, "⟳ New games", the import @@ -2119,6 +2155,18 @@ impl LargeView { let resp = row.response(); let resp = if about.is_empty() { resp } else { resp.on_hover_text(about.join(" · ")) }; resp.context_menu(|ui| { + if ui.button(tr("Open")).clicked() { + opened = Some(index); + ui.close(); + } + if ui.button(tr("Game data… (F2)")).clicked() { + actions.push(LibraryAction::EditGameData { path: path.to_path_buf(), index }); + ui.close(); + } + if ui.button(tr("Add to database… (Ctrl+Shift+S)")).clicked() { + actions.push(LibraryAction::AddGameToDatabase { path: path.to_path_buf(), index }); + ui.close(); + } let label = if seen { tr("Mark as not viewed") } else { @@ -2128,6 +2176,13 @@ impl LargeView { toggle_viewed = Some((key, !seen)); ui.close(); } + if self.writable { + ui.separator(); + if ui.button(tr("Delete from the database… (Delete)")).clicked() { + actions.push(LibraryAction::DeleteGame { path: path.to_path_buf(), index }); + ui.close(); + } + } }); if resp.hovered() { hovered = Some(index); @@ -2190,6 +2245,37 @@ impl LargeView { i.key_pressed(egui::Key::Enter), ) }); + // The selected record: F2 opens it with its data, Ctrl+Shift+S adds a copy of it + // to another database, Delete removes it (a question first). + if !typing && let Some(index) = self.selected { + let (data, add, delete) = ui.input_mut(|i| { + ( + i.consume_key(egui::Modifiers::NONE, egui::Key::F2), + i.consume_key( + egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, + egui::Key::S, + ), + i.consume_key(egui::Modifiers::NONE, egui::Key::Delete), + ) + }); + let p = path.to_path_buf(); + if data { + actions.push(LibraryAction::EditGameData { + path: p.clone(), + index, + }); + } + if add { + actions.push(LibraryAction::AddGameToDatabase { + path: p.clone(), + index, + }); + } + // Also for a database that takes no games: the app says why. + if delete { + actions.push(LibraryAction::DeleteGame { path: p, index }); + } + } // Enter belongs to a filter field, but in the quick search it opens the game. let enter = enter && (!typing || self.search_focused); let step = if page_up || page_down { 20 } else { 1 }; diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index 1c3b44b..c5afc4f 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -48,6 +48,22 @@ pub enum LibraryAction { OpenUpdate, RemoveDatabase(PathBuf), OpenSettings, + /// A new, empty PGN database (own-databases.md §2). + NewDatabase, + /// A record of a table: delete it, add a copy of it to another database, open it + /// with its data for editing. + DeleteGame { + path: PathBuf, + index: usize, + }, + AddGameToDatabase { + path: PathBuf, + index: usize, + }, + EditGameData { + path: PathBuf, + index: usize, + }, } /// How a database was imported, and what is worth knowing about it. @@ -83,9 +99,9 @@ fn shelf_buttons_w(ui: &Ui, update: Option<&str>, icons: bool) -> f32 { texts.iter().map(|t| button_w(ui, t)).sum::() + update.map_or(0.0, |v| button_w(ui, v)) } -/// The shelf's "+ Add database" and "Online games" cards: 150 wide, wider when their -/// label needs it (some languages say it longer). -fn side_card_widths(ui: &Ui) -> (f32, f32) { +/// The shelf's "+ Add database", "✚ New database" and "Online games" cards: 150 wide, +/// wider when their label needs it (some languages say it longer). +fn side_card_widths(ui: &Ui) -> (f32, f32, f32) { let w = |t: &str, size: f32| { ui.painter() .layout_no_wrap( @@ -99,6 +115,7 @@ fn side_card_widths(ui: &Ui) -> (f32, f32) { let fit = |inner: f32| (inner + 32.0).max(150.0).ceil(); ( fit(w(tr("+ Add database"), 15.0)), + fit(w(tr("✚ New database"), 15.0)), fit(w(&format!("🌐 {}", tr("Online games")), 15.0).max(w("Lichess · Chess.com", 13.0))), ) } @@ -235,6 +252,45 @@ impl Library { } } + /// Why a database on the shelf cannot take games (own-databases.md §5); `None`: a + /// PGN that can. + pub fn write_block(&self, path: &Path) -> Option { + use crate::own_db::Block; + if crate::online::is_online(path) { + return Some(Block::Online); + } + if !path.exists() { + return Some(Block::Missing); + } + match self.info.get(path).map(|i| i.format) { + Some(Format::Pgn) => {} + Some(_) => return Some(Block::ReadOnly), + None => { + let pgn = path + .extension() + .is_some_and(|e| e.to_string_lossy().eq_ignore_ascii_case("pgn")); + if !pgn { + return Some(Block::ReadOnly); + } + } + } + if let Some(db) = self.database(path) { + match db.as_pgn() { + Some(p) => { + let enc = p.encoding(); + if enc != chess_core::TextEncoding::Utf8 && !p.detected_encoding().ascii_only { + return Some(Block::Encoding(enc.label())); + } + } + None => return Some(Block::ReadOnly), + } + } + if std::fs::metadata(path).is_ok_and(|m| m.permissions().readonly()) { + return Some(Block::NoPermission); + } + None + } + pub fn forget(&mut self, path: &Path) { self.info.remove(path); self.large.remove(path); @@ -261,6 +317,11 @@ impl Library { .or_insert_with(|| std::fs::metadata(path).map_or(0, |m| m.len())) } + /// The database is being read now. + pub fn loading(&self, path: &Path) -> bool { + matches!(self.slots.get(path), Some(Slot::Loading { .. })) + } + /// Why the database could not be opened, if it could not. pub fn failure(&self, path: &Path) -> Option<&str> { match self.slots.get(path) { @@ -368,8 +429,8 @@ impl Library { .selected_db .as_ref() .is_some_and(|p| self.large.get(p).is_some_and(|v| v.pane() == Pane::Board)); - let (add_w, online_w) = side_card_widths(ui); - let cards = databases.len() + 1 + usize::from(self.online); + let (add_w, new_w, online_w) = side_card_widths(ui); + let cards = databases.len() + 2 + usize::from(self.online); let card_rows = { let mut rows = 1; let mut x = 0.0; @@ -377,6 +438,7 @@ impl Library { let w = match k.checked_sub(databases.len()) { None => 190.0, Some(0) => add_w, + Some(1) => new_w, Some(_) => online_w, }; if x > 0.0 && x + w > width - 16.0 { @@ -565,15 +627,18 @@ impl Library { if let Some(p) = pick { self.select_db(&p, ui.ctx()); } - if ui - .button("+") - .on_hover_text(tr( + ui.menu_button("+", |ui| { + if ui.button(tr("Add database…")).on_hover_text(tr( "Open PGN, ChessBase (.cbh, .cbv) or an archive (.zip, .7z) (Ctrl+O)", - )) - .clicked() - { - actions.push(LibraryAction::AddDatabases); - } + )).clicked() { + actions.push(LibraryAction::AddDatabases); + ui.close(); + } + if ui.button(tr("New database…")).on_hover_text(tr("An empty PGN file for your own games (Ctrl+Shift+N)")).clicked() { + actions.push(LibraryAction::NewDatabase); + ui.close(); + } + }); if self.online && ui .button("🌐") @@ -653,7 +718,7 @@ impl Library { for path in databases { self.db_card(ui, path, actions); } - let (add_w, online_w) = side_card_widths(ui); + let (add_w, new_w, online_w) = side_card_widths(ui); let (rect, resp) = ui.allocate_exact_size(vec2(add_w, 64.0), Sense::click()); let visuals = ui.style().interact(&resp); ui.painter() @@ -673,6 +738,23 @@ impl Library { { actions.push(LibraryAction::AddDatabases); } + let (rect, resp) = ui.allocate_exact_size(vec2(new_w, 64.0), Sense::click()); + let visuals = ui.style().interact(&resp); + ui.painter() + .rect_stroke(rect, 6.0, visuals.fg_stroke, egui::StrokeKind::Inside); + ui.painter().text( + rect.center(), + egui::Align2::CENTER_CENTER, + tr("✚ New database"), + egui::FontId::proportional(15.0), + visuals.text_color(), + ); + if resp + .on_hover_text(tr("An empty PGN file for your own games (Ctrl+Shift+N)")) + .clicked() + { + actions.push(LibraryAction::NewDatabase); + } if self.online { let (rect, resp) = ui.allocate_exact_size(vec2(online_w, 64.0), Sense::click()); let visuals = ui.style().interact(&resp); @@ -722,7 +804,7 @@ impl Library { &[("n", &large_db::short_count(b.games() + b.texts()))], ) ), - None => trf("{n} games", &[("n", &db.len())]), + None => crate::i18n::games(db.len()), }, Some(Slot::Loading { progress, .. }) => { let p = progress.lock().map(|g| *g).unwrap_or(ScanProgress { @@ -787,6 +869,10 @@ impl Library { self.select_db(path, ui.ctx()); } resp.context_menu(|ui| { + if ui.button(tr("Show in folder")).clicked() { + crate::own_db::show_in_folder(path); + ui.close(); + } if ui.button(tr("Remove from list")).clicked() { actions.push(LibraryAction::RemoveDatabase(path.to_path_buf())); ui.close(); @@ -867,6 +953,7 @@ impl Library { let online = crate::online::is_online(&path); let header = self.header(&path, &db, online); + let writable = self.write_block(&path).is_none(); let view = self .large .entry(path.clone()) @@ -880,6 +967,7 @@ impl Library { &mut self.viewed, notes, settings, + writable, actions, ) { self.notes_open = Some(path.clone()); diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index cd56a2a..1fd6972 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -19,6 +19,7 @@ mod library; mod notation; mod online; mod online_ui; +mod own_db; mod reference; mod review; mod san; @@ -55,6 +56,7 @@ fn main() -> eframe::Result { } crate::i18n::set_lang(settings::Settings::load().language); graphics::install_panic_hook(); + graphics::init_library_log(); let mode = graphics::choose(); let options = eframe::NativeOptions { viewport: egui::ViewportBuilder::default() diff --git a/apps/desktop/src/own_db.rs b/apps/desktop/src/own_db.rs new file mode 100644 index 0000000..4e46e70 --- /dev/null +++ b/apps/desktop/src/own_db.rs @@ -0,0 +1,993 @@ +//! The user's own databases (docs/design/own-databases.md): the dialogs of creating a +//! PGN database, choosing one to add a game to, the game's data, a duplicate, deleting +//! a game, a copy in UTF-8, errors of writing. Each dialog draws itself and tells what +//! was chosen; the flows between them live in `app.rs`. + +use std::path::{Path, PathBuf}; + +use chess_core::{Game, GameResult}; +use egui::{Key, RichText, Ui}; + +use crate::i18n::{tr, trf}; + +/// Files bigger than this are rewritten with a progress window and, once a session, +/// the advice to keep one's own games in a smaller database (§6.4). +pub const BIG_REWRITE_BYTES: u64 = 50 << 20; + +/// Why a database cannot take a game (§5). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Block { + /// Downloaded from Lichess and Chess.com: updating it would drop added games. + Online, + /// A ChessBase database or an archive: read only. + ReadOnly, + /// A PGN in another encoding: a UTF-8 copy can take games. + Encoding(&'static str), + /// The file cannot be written (permissions). + NoPermission, + /// The file is not on the disk any more. + Missing, +} + +impl Block { + /// One line, for a list row or a tooltip. + pub fn short(&self) -> String { + match self { + Block::Online => tr("updates itself from Lichess and Chess.com").to_owned(), + Block::ReadOnly => tr("read only").to_owned(), + Block::Encoding(enc) => trf( + "encoding {enc} — a UTF-8 copy can take games", + &[("enc", enc)], + ), + Block::NoPermission => tr("no permission to write the file").to_owned(), + Block::Missing => tr("file not found").to_owned(), + } + } + + /// The explanation when the user tries anyway. + pub fn long(&self) -> String { + match self { + Block::Online => tr("This database is downloaded from Lichess and Chess.com and updates itself: a game added by hand would be lost at the next update. Add the game to a database of your own.").to_owned(), + Block::ReadOnly => tr("ChessBase databases and archives are only read. Add the game to a PGN database of your own.").to_owned(), + Block::Encoding(enc) => trf("This file is in the {enc} encoding; games are written in UTF-8. Make a copy of it in UTF-8 and add games to the copy — the original stays as it is.", &[("enc", enc)]), + Block::NoPermission => tr("The file cannot be written: no permission.").to_owned(), + Block::Missing => tr("The file is not on the disk any more.").to_owned(), + } + } +} + +/// The user's Documents folder (else the home folder). +pub fn documents_dir() -> PathBuf { + let dirs = directories::UserDirs::new(); + dirs.as_ref() + .and_then(|u| u.document_dir().map(Path::to_owned)) + .or_else(|| dirs.as_ref().map(|u| u.home_dir().to_owned())) + .unwrap_or_else(std::env::temp_dir) +} + +/// Where new databases go unless the user chose another folder. +pub fn default_base_dir(chosen: Option<&Path>) -> PathBuf { + chosen + .map(Path::to_owned) + .unwrap_or_else(|| documents_dir().join("ChessPenguin")) +} + +/// The name of a database as the shelf shows it: the file's stem. +pub fn base_name(path: &Path) -> String { + path.file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default() +} + +/// Characters a file name cannot have (on any of the three systems). +const FORBIDDEN: &[char] = &['/', '\\', ':', '*', '?', '"', '<', '>', '|']; + +// --- New database ------------------------------------------------------------------------ + +/// What to do once the database is created. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AfterCreate { + /// Just put it on the shelf. + Shelf, + /// Add the current game to it (the chooser led here). + AddGame, + /// Add a copy of a record of a table to it. + AddRecord { path: PathBuf, index: usize }, +} + +pub struct NewBaseDialog { + pub name: String, + pub dir: PathBuf, + pub after: AfterCreate, + /// Creating the file failed: said under the name, the dialog stays open. + pub error: Option, + focus: bool, +} + +pub enum NewBaseOutcome { + Create(PathBuf), + /// The file exists: put it on the shelf as it is. + AddExisting(PathBuf), + PickFolder, + Cancel, +} + +impl NewBaseDialog { + pub fn new(dir: PathBuf, after: AfterCreate) -> Self { + Self { + name: String::new(), + dir, + after, + error: None, + focus: true, + } + } + + /// The name as typed, without a ".pgn" the user may have added. + fn stem(&self) -> &str { + let name = self.name.trim(); + match name.get(name.len().saturating_sub(4)..) { + Some(ext) if ext.eq_ignore_ascii_case(".pgn") => name[..name.len() - 4].trim_end(), + _ => name, + } + } + + fn path(&self) -> PathBuf { + self.dir.join(format!("{}.pgn", self.stem())) + } + + /// What is wrong with the name, if anything; `Ok(true)` when a file with this name + /// exists already. + fn check(&self) -> Result { + let name = self.stem(); + if name.is_empty() { + return Err(String::new()); + } + if name.contains(FORBIDDEN) || name.chars().all(|c| c == '.') { + return Err(tr("A name cannot have / \\ : * ? \" < > |").to_owned()); + } + Ok(self.path().exists()) + } + + pub fn show(&mut self, ctx: &egui::Context) -> Option { + let mut out = None; + egui::Modal::new(egui::Id::new("new_base")).show(ctx, |ui| { + ui.set_width(440.0); + ui.heading(tr("New database")); + ui.add_space(8.0); + ui.label(tr("Title")); + let check = self.check(); + let mut edit = egui::TextEdit::singleline(&mut self.name) + .hint_text(tr("e.g. Petrov, My games, Sicilian")) + .desired_width(f32::INFINITY); + if matches!(&check, Err(e) if !e.is_empty()) { + edit = edit.text_color(ui.visuals().error_fg_color); + } + let edit = ui.add(edit); + if edit.changed() { + self.error = None; + } + if std::mem::take(&mut self.focus) { + edit.request_focus(); + } + ui.add_space(6.0); + ui.horizontal_wrapped(|ui| { + ui.label(RichText::new(tr("File:")).weak()); + // The folder alone until a name is typed. + let shown = if self.name.trim().is_empty() { + format!("{}{}", self.dir.display(), std::path::MAIN_SEPARATOR) + } else { + self.path().display().to_string() + }; + ui.label(RichText::new(shown).weak()); + if ui.small_button(tr("Change folder…")).clicked() { + out = Some(NewBaseOutcome::PickFolder); + } + }); + match &check { + Err(e) if !e.is_empty() => { + ui.label(RichText::new(e).color(ui.visuals().error_fg_color)); + } + Ok(true) => { + ui.label( + RichText::new(tr("A file with this name is already there.")) + .color(ui.visuals().warn_fg_color), + ); + } + _ => {} + } + if let Some(e) = &self.error { + ui.label(RichText::new(e).color(ui.visuals().error_fg_color)); + } + ui.add_space(8.0); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let enter = ui.input(|i| i.key_pressed(Key::Enter)); + match &check { + Ok(false) => { + if crate::widgets::primary(ui, tr("Create")).clicked() || enter { + out = Some(NewBaseOutcome::Create(self.path())); + } + } + Ok(true) => { + if crate::widgets::primary(ui, tr("Put it on the shelf")).clicked() + || enter + { + out = Some(NewBaseOutcome::AddExisting(self.path())); + } + } + Err(_) => { + ui.add_enabled(false, egui::Button::new(tr("Create"))); + } + } + if ui.button(tr("Cancel")).clicked() { + out = Some(NewBaseOutcome::Cancel); + } + }); + }); + }); + if out.is_none() && ctx.input(|i| i.key_pressed(Key::Escape)) { + out = Some(NewBaseOutcome::Cancel); + } + out + } +} + +// --- Add to database -------------------------------------------------------------------- + +/// A database on the shelf, as the chooser lists it. +pub struct ChooserRow { + pub path: PathBuf, + pub name: String, + /// `None`: not read yet (its encoding is not known either). + pub games: Option, + pub block: Option, +} + +impl ChooserRow { + /// Read, and nothing blocks it: can be chosen. + pub fn takes_games(&self) -> bool { + self.games.is_some() && self.block.is_none() + } +} + +/// What the chooser is for: the game on the screen, or a record of a table. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ChooserFor { + CurrentGame, + Record { path: PathBuf, index: usize }, +} + +pub struct Chooser { + pub rows: Vec, + pub selected: Option, + pub search: String, + pub purpose: ChooserFor, + /// The game's title, for the heading. + pub title: String, + focus: bool, +} + +pub enum ChooserOutcome { + Pick(PathBuf), + NewBase, + SaveAsFile, + /// A PGN in another encoding: make the copy and add to it. + Utf8Copy(PathBuf), + Cancel, +} + +impl Chooser { + pub fn new( + rows: Vec, + preselect: Option<&Path>, + purpose: ChooserFor, + title: String, + ) -> Self { + let selected = preselect + .and_then(|p| rows.iter().position(|r| r.path == p && r.takes_games())) + .or_else(|| rows.iter().position(ChooserRow::takes_games)); + Self { + rows, + selected, + search: String::new(), + purpose, + title, + focus: true, + } + } + + /// The shelf as it is now (databases get read while the dialog is open): the + /// chosen row stays chosen by its path. + pub fn refresh(&mut self, rows: Vec) { + let chosen = self + .selected + .and_then(|i| self.rows.get(i)) + .map(|r| r.path.clone()); + self.rows = rows; + self.selected = chosen + .and_then(|p| { + self.rows + .iter() + .position(|r| r.path == p && r.takes_games()) + }) + .or_else(|| self.rows.iter().position(ChooserRow::takes_games)); + } + + pub fn show(&mut self, ctx: &egui::Context) -> Option { + let mut out = None; + egui::Modal::new(egui::Id::new("add_to_base")).show(ctx, |ui| { + ui.set_width(440.0); + ui.heading(tr("Add to database")); + if !self.title.is_empty() { + ui.label(RichText::new(&self.title).weak()); + } + ui.add_space(6.0); + let many = self.rows.len() > 8; + if many { + let edit = ui.add( + egui::TextEdit::singleline(&mut self.search) + .hint_text(tr("🔍 Find a database")) + .desired_width(f32::INFINITY), + ); + if std::mem::take(&mut self.focus) { + edit.request_focus(); + } + } + let needle = self.search.trim().to_lowercase(); + let shown: Vec = (0..self.rows.len()) + .filter(|&i| { + needle.is_empty() || self.rows[i].name.to_lowercase().contains(&needle) + }) + .collect(); + // Writable ones first, in shelf order; the others, greyed, after them. + let order: Vec = shown + .iter() + .copied() + .filter(|&i| self.rows[i].takes_games()) + .chain( + shown + .iter() + .copied() + .filter(|&i| !self.rows[i].takes_games()), + ) + .collect(); + let (up, down, enter) = ui.input(|i| { + ( + i.key_pressed(Key::ArrowUp), + i.key_pressed(Key::ArrowDown), + i.key_pressed(Key::Enter), + ) + }); + if up || down { + let writable: Vec = order + .iter() + .copied() + .filter(|&i| self.rows[i].takes_games()) + .collect(); + let pos = self + .selected + .and_then(|s| writable.iter().position(|&i| i == s)); + let next = match (pos, down) { + (None, _) => 0, + (Some(p), true) => (p + 1).min(writable.len().saturating_sub(1)), + (Some(p), false) => p.saturating_sub(1), + }; + self.selected = writable.get(next).copied(); + } + egui::ScrollArea::vertical() + .max_height(320.0) + .show(ui, |ui| { + if order.is_empty() { + ui.label( + RichText::new(tr( + "No PGN databases on the shelf yet — create one below.", + )) + .weak(), + ); + } + let width = ui.available_width(); + for i in order { + let row = &self.rows[i]; + let selected = self.selected == Some(i); + let text = match row.games { + Some(n) => format!("{} · {}", row.name, crate::i18n::games(n)), + None => format!("{} · {}", row.name, tr("reading…")), + }; + let folder = row + .path + .parent() + .map(|p| p.display().to_string()) + .unwrap_or_default(); + match (&row.block, row.games) { + (None, Some(_)) => { + let resp = ui + .add_sized( + [width, 0.0], + egui::Button::selectable(selected, text), + ) + .on_hover_text(&folder); + if resp.clicked() { + self.selected = Some(i); + } + if resp.double_clicked() { + out = Some(ChooserOutcome::Pick(row.path.clone())); + } + } + (None, None) => { + ui.label(RichText::new(text).weak()); + } + (Some(Block::Encoding(enc)), _) => { + // The copy is the way in: a link at the end of the row. + ui.horizontal(|ui| { + ui.label(RichText::new(format!("{text} · {enc} ·")).weak()); + if ui + .link(tr("Make a copy in UTF-8…")) + .on_hover_text(tr( + "Make a copy in UTF-8 and add the game to it", + )) + .clicked() + { + out = Some(ChooserOutcome::Utf8Copy(row.path.clone())); + } + }); + } + (Some(b), _) => { + ui.add_enabled( + false, + egui::Button::new(format!("{text} — {}", b.short())) + .frame(false), + ) + .on_disabled_hover_text(b.long()); + } + } + } + }); + ui.separator(); + if ui.button(tr("✚ New database…")).clicked() { + out = Some(ChooserOutcome::NewBase); + } + if self.purpose == ChooserFor::CurrentGame + && ui + .button(tr("Save as a file…")) + .on_hover_text(tr( + "A separate PGN file with this game only; it is not put on the shelf", + )) + .clicked() + { + out = Some(ChooserOutcome::SaveAsFile); + } + ui.add_space(8.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let pick = self.selected.map(|i| self.rows[i].path.clone()); + let add = ui + .add_enabled_ui(pick.is_some(), |ui| crate::widgets::primary(ui, tr("Add"))) + .inner; + if (add.clicked() || enter) + && let Some(p) = pick + { + out = Some(ChooserOutcome::Pick(p)); + } + if ui.button(tr("Cancel")).clicked() { + out = Some(ChooserOutcome::Cancel); + } + }); + }); + if out.is_none() && ctx.input(|i| i.key_pressed(Key::Escape)) { + out = Some(ChooserOutcome::Cancel); + } + out + } +} + +// --- Game data -------------------------------------------------------------------------- + +/// What the main button of the editor does. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EditorMode { + /// Changes the game (Ctrl+S saves them). + Done, + /// Then the game is added to this database. + Add(PathBuf), +} + +pub struct DataEditor { + pub white: String, + pub white_elo: String, + pub black: String, + pub black_elo: String, + pub event: String, + pub site: String, + pub date: String, + pub round: String, + pub result: GameResult, + pub annotator: String, + /// The tags the editor does not show (kept as they are). + pub others: Vec, + pub mode: EditorMode, + /// The fields as the editor opened (nothing changed: nothing written). + initial: String, + focus: bool, +} + +pub enum EditorOutcome { + Done, + Cancel, +} + +fn shown(value: Option<&str>) -> String { + value + .filter(|v| !v.is_empty() && !v.chars().all(|c| c == '?' || c == '.')) + .unwrap_or("") + .to_owned() +} + +impl DataEditor { + pub fn from_game(game: &Game, your_name: &str, mode: EditorMode) -> Self { + let t = |n: &str| shown(game.tag(n)); + let known = [ + "Event", + "Site", + "Date", + "Round", + "White", + "Black", + "Result", + "WhiteElo", + "BlackElo", + "Annotator", + "FEN", + "SetUp", + "PlyCount", + ]; + let others: Vec = game + .tags() + .iter() + .filter(|(k, _)| !known.contains(&k.as_str())) + .map(|(k, _)| k.clone()) + .collect(); + let annotator = { + let a = t("Annotator"); + if a.is_empty() && game.tag("Annotator").is_none() { + your_name.to_owned() + } else { + a + } + }; + let mut editor = Self { + white: t("White"), + white_elo: t("WhiteElo"), + black: t("Black"), + black_elo: t("BlackElo"), + event: t("Event"), + site: t("Site"), + date: t("Date"), + round: t("Round"), + result: game.result(), + annotator, + others, + mode, + initial: String::new(), + focus: true, + }; + editor.initial = editor.state(); + editor + } + + fn state(&self) -> String { + [ + &self.white, + &self.white_elo, + &self.black, + &self.black_elo, + &self.event, + &self.site, + &self.date, + &self.round, + &self.annotator, + ] + .iter() + .map(|s| s.trim()) + .collect::>() + .join("\u{1}") + + self.result.as_str() + } + + /// Something was edited. + pub fn changed(&self) -> bool { + self.state() != self.initial + } + + fn date_ok(&self) -> bool { + chess_core::pgn::store::pgn_date(&self.date).is_some() + } + + /// Writes the fields into the game (empty fields as PGN's "?"). Opened and closed + /// without an edit, it writes nothing — unless the game is being added: then the + /// annotator and the standard tags go in. + pub fn apply(&self, game: &mut Game) { + if !self.changed() && self.mode == EditorMode::Done { + return; + } + let set = |game: &mut Game, name: &str, value: &str, unknown: &str| { + let v = value.trim(); + if v.is_empty() { + // A cleared field: the seven PGN tags say "?", an optional one goes away. + if unknown.is_empty() { + game.remove_tag(name); + } else if game.tag(name) != Some(unknown) { + game.set_tag(name, unknown); + } + } else if game.tag(name) != Some(v) { + game.set_tag(name, v); + } + }; + set(game, "White", &self.white, "?"); + set(game, "Black", &self.black, "?"); + set(game, "Event", &self.event, "?"); + set(game, "Site", &self.site, "?"); + set(game, "Round", &self.round, "?"); + let date = + chess_core::pgn::store::pgn_date(&self.date).unwrap_or_else(|| "????.??.??".to_owned()); + if game.tag("Date") != Some(date.as_str()) { + game.set_tag("Date", &date); + } + set(game, "WhiteElo", &self.white_elo, ""); + set(game, "BlackElo", &self.black_elo, ""); + set(game, "Annotator", &self.annotator, ""); + if game.result() != self.result { + game.set_result(self.result); + } + game.order_roster(); + } + + pub fn show(&mut self, ctx: &egui::Context) -> Option { + let mut out = None; + egui::Modal::new(egui::Id::new("game_data")).show(ctx, |ui| { + ui.set_width(460.0); + match &self.mode { + EditorMode::Done => ui.heading(tr("Game data")), + EditorMode::Add(p) => { + ui.heading(trf("Game data → «{name}»", &[("name", &base_name(p))])) + } + }; + ui.add_space(8.0); + let label_w = 90.0; + let field = |ui: &mut Ui, text: &mut String, hint: &str, width: f32| { + ui.add( + egui::TextEdit::singleline(text) + .hint_text(hint) + .desired_width(width), + ) + }; + let row = |ui: &mut Ui, label: &str, add: &mut dyn FnMut(&mut Ui)| { + ui.horizontal(|ui| { + ui.add_sized([label_w, 20.0], egui::Label::new(label)); + add(ui); + }); + }; + let wide = 460.0 - label_w - 24.0; + let mut first = None; + let elo_w = 56.0; + let elo_label = crate::game_view::text_width(ui, "Elo", egui::TextStyle::Body) + 16.0; + row(ui, tr("White"), &mut |ui| { + let r = field( + ui, + &mut self.white, + tr("Surname, Name"), + wide - elo_w - elo_label, + ); + first = Some(r); + ui.label("Elo"); + field(ui, &mut self.white_elo, "", elo_w); + }); + row(ui, tr("Black"), &mut |ui| { + field( + ui, + &mut self.black, + tr("Surname, Name"), + wide - elo_w - elo_label, + ); + ui.label("Elo"); + field(ui, &mut self.black_elo, "", elo_w); + }); + row(ui, tr("Event"), &mut |ui| { + field(ui, &mut self.event, "", wide); + }); + row(ui, tr("Site"), &mut |ui| { + field(ui, &mut self.site, "", wide); + }); + let date_ok = self.date_ok(); + row(ui, tr("Date"), &mut |ui| { + let mut edit = egui::TextEdit::singleline(&mut self.date) + .hint_text(tr("YYYY.MM.DD")) + .desired_width(120.0); + if !date_ok { + edit = edit.text_color(ui.visuals().error_fg_color); + } + ui.add(edit) + .on_hover_text(tr("2026.10.18, 18.10.2026, 2026.10, 2026 or empty")); + ui.add_space(8.0); + ui.label(tr("Round")); + field(ui, &mut self.round, "", 60.0); + }); + row(ui, tr("Result"), &mut |ui| { + for (r, label) in [ + (GameResult::WhiteWins, "1-0"), + (GameResult::Draw, "½-½"), + (GameResult::BlackWins, "0-1"), + (GameResult::Unknown, "*"), + ] { + ui.selectable_value(&mut self.result, r, label); + } + }); + row(ui, tr("Annotator"), &mut |ui| { + field(ui, &mut self.annotator, "", wide); + }); + if !self.others.is_empty() { + ui.add_space(4.0); + ui.label( + RichText::new(trf( + "Other tags stay as they are: {tags}", + &[("tags", &self.others.join(", "))], + )) + .weak(), + ); + } + if std::mem::take(&mut self.focus) + && let Some(r) = first + { + // White's name selected: typing replaces it. + r.request_focus(); + if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), r.id) { + let range = egui::text::CCursorRange::two( + egui::text::CCursor::new(0), + egui::text::CCursor::new(self.white.chars().count()), + ); + state.cursor.set_char_range(Some(range)); + state.store(ui.ctx(), r.id); + } + } + ui.add_space(10.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let label = match &self.mode { + EditorMode::Done => tr("Done").to_owned(), + EditorMode::Add(p) => trf("Add to «{name}»", &[("name", &base_name(p))]), + }; + let enter = ui.input(|i| i.key_pressed(Key::Enter)); + let ok = ui + .add_enabled_ui(date_ok, |ui| crate::widgets::primary(ui, &label)) + .inner; + if ok.clicked() || (enter && date_ok) { + out = Some(EditorOutcome::Done); + } + if ui.button(tr("Cancel")).clicked() { + out = Some(EditorOutcome::Cancel); + } + }); + }); + if out.is_none() && ctx.input(|i| i.key_pressed(Key::Escape)) { + out = Some(EditorOutcome::Cancel); + } + out + } +} + +// --- Small questions -------------------------------------------------------------------- + +/// "Yes / no / cancel" questions, each with its own heading, text and buttons. +pub struct Question { + pub kind: QuestionKind, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum QuestionKind { + /// The same game is in the target already (record `index`). + Duplicate { + target: PathBuf, + index: usize, + title: String, + }, + /// Delete record `index` of `path`. + Delete { + path: PathBuf, + index: usize, + title: String, + }, + /// Make a UTF-8 copy of `path` at `dest` and add the game to it. + Utf8Copy { + path: PathBuf, + dest: PathBuf, + encoding: &'static str, + }, + /// Writing failed. + WriteFailed { + path: PathBuf, + error: String, + deleting: bool, + }, + /// The file was changed by another program since it was read. + ChangedOnDisk { path: PathBuf, deleting: bool }, + /// The file is big: replacing a record rewrites it all. + BigBase { path: PathBuf, bytes: u64 }, +} + +/// What was chosen in a question, by its meaning. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Answer { + /// Replace the duplicate / delete / make the copy / retry / save anyway / reread. + Primary, + /// Add as a new game / add to another database. + Secondary, + Cancel, +} + +impl Question { + pub fn show(&mut self, ctx: &egui::Context) -> Option { + let mut out = None; + egui::Modal::new(egui::Id::new("own_db_question")).show(ctx, |ui| { + ui.set_width(420.0); + let (heading, text, primary, secondary, cancel): (String, String, Option, Option, &str) = match &self.kind { + QuestionKind::Duplicate { target, index, title } => ( + tr("This game is already there").to_owned(), + trf("«{name}» already has this game: No. {n}, {title} — the same players, date and moves.", &[("title", title), ("name", &base_name(target)), ("n", &(index + 1))]), + Some(trf("Replace No. {n}", &[("n", &(index + 1))])), + Some(tr("Add as new").to_owned()), + tr("Cancel"), + ), + QuestionKind::Delete { path, index, title } => ( + tr("Delete the game from the database?").to_owned(), + trf("«{title}» (No. {n}) is removed from the file «{file}»; other databases are not touched. Undo is offered for a few seconds.", &[("title", title), ("n", &(index + 1)), ("file", &path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default())]), + Some(tr("Delete").to_owned()), + None, + tr("Cancel"), + ), + QuestionKind::Utf8Copy { path, dest, encoding } => ( + tr("A copy in UTF-8").to_owned(), + trf("«{name}» is in the {enc} encoding, and games are written in UTF-8. A copy «{copy}» will be made next to it with all its games; the game is added to the copy, the original stays as it is.", &[("name", &base_name(path)), ("enc", encoding), ("copy", &dest.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default())]), + Some(tr("Make the copy").to_owned()), + None, + tr("Cancel"), + ), + QuestionKind::WriteFailed { path, error, deleting } => ( + if *deleting { tr("Could not delete").to_owned() } else { tr("Could not save").to_owned() }, + format!("{}\n{}", path.display(), error), + Some(tr("Try again").to_owned()), + (!deleting).then(|| tr("Add to another database…").to_owned()), + tr("Close"), + ), + QuestionKind::ChangedOnDisk { path, deleting } => ( + tr("The file changed on disk").to_owned(), + if *deleting { + trf("«{name}» was changed by another program since it was read. Reread it and look again.", &[("name", &base_name(path))]) + } else { + trf("«{name}» was changed by another program since it was read. The game can be added to it as a new one; replacing a record in it would need a fresh read first.", &[("name", &base_name(path))]) + }, + if *deleting { Some(tr("Reread").to_owned()) } else { Some(tr("Add as new").to_owned()) }, + None, + tr("Cancel"), + ), + QuestionKind::BigBase { path, bytes } => ( + tr("A big database").to_owned(), + trf("«{name}» is {mb} MB: saving a game into it rewrites the whole file, which takes a while. Your own games are handier in a smaller database of their own.", &[("name", &base_name(path)), ("mb", &(bytes >> 20))]), + Some(tr("Save anyway").to_owned()), + Some(tr("Add to another database…").to_owned()), + tr("Cancel"), + ), + }; + ui.heading(heading); + ui.add_space(6.0); + ui.label(text); + ui.add_space(10.0); + // Replacing a record is never one Enter away: the duplicate question has no + // main button (own-databases.md §5.5). + let plain = matches!(self.kind, QuestionKind::Duplicate { .. }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let enter = !plain && ui.input(|i| i.key_pressed(Key::Enter)); + if let Some(p) = primary { + let clicked = if plain { + ui.add(egui::Button::new(&p).min_size(egui::vec2(0.0, 30.0))) + .clicked() + } else { + crate::widgets::primary(ui, &p).clicked() + }; + if clicked || enter { + out = Some(Answer::Primary); + } + } + if let Some(s) = secondary + && ui.button(s).clicked() + { + out = Some(Answer::Secondary); + } + if ui.button(cancel).clicked() { + out = Some(Answer::Cancel); + } + }); + }); + if out.is_none() && ctx.input(|i| i.key_pressed(Key::Escape)) { + out = Some(Answer::Cancel); + } + out + } +} + +/// Shows the file in the system's file manager. +pub fn show_in_folder(path: &Path) { + let path = path.to_path_buf(); + let _ = std::thread::Builder::new() + .name("show-in-folder".into()) + .spawn(move || { + #[cfg(target_os = "windows")] + { + let _ = std::process::Command::new("explorer") + .arg(format!("/select,{}", path.display())) + .spawn(); + } + #[cfg(target_os = "macos")] + { + let _ = std::process::Command::new("open") + .arg("-R") + .arg(&path) + .spawn(); + } + #[cfg(not(any(target_os = "windows", target_os = "macos")))] + { + // The file manager selects the file when it can (the portal's ShowItems), + // else its folder opens. + let shown = std::process::Command::new("dbus-send") + .args([ + "--session", + "--print-reply", + "--dest=org.freedesktop.FileManager1", + "/org/freedesktop/FileManager1", + "org.freedesktop.FileManager1.ShowItems", + &format!("array:string:file://{}", path.display()), + "string:", + ]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .is_ok_and(|s| s.success()); + if !shown && let Some(dir) = path.parent() { + let _ = std::process::Command::new("xdg-open").arg(dir).spawn(); + } + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn editor_writes_tags_and_result() { + let mut g = chess_core::parse_str("[Event \"?\"]\n[White \"?\"]\n\n1. e4 *\n").game; + let mut e = DataEditor::from_game(&g, "Coach", EditorMode::Done); + assert_eq!(e.annotator, "Coach"); + e.white = "Petrov, Ivan".into(); + e.white_elo = "1500".into(); + e.date = "18.10.2026".into(); + e.result = GameResult::WhiteWins; + e.apply(&mut g); + assert_eq!(g.tag("White"), Some("Petrov, Ivan")); + assert_eq!(g.tag("WhiteElo"), Some("1500")); + assert_eq!(g.tag("Date"), Some("2026.10.18")); + assert_eq!(g.tag("Black"), Some("?")); + assert_eq!(g.tag("Annotator"), Some("Coach")); + assert_eq!(g.result(), GameResult::WhiteWins); + // The seven standard tags first, in their order; Result among them. + let names: Vec<&str> = g.tags().iter().map(|(k, _)| k.as_str()).collect(); + assert_eq!( + &names[..7], + &["Event", "Site", "Date", "Round", "White", "Black", "Result"] + ); + assert_eq!(g.tag("Result"), Some("1-0")); + assert!(g.is_modified()); + // Nothing changed: the game is not marked modified again. + g.mark_saved(); + let e2 = DataEditor::from_game(&g, "Coach", EditorMode::Done); + e2.apply(&mut g); + assert!(!g.is_modified()); + } +} diff --git a/apps/desktop/src/settings.rs b/apps/desktop/src/settings.rs index c55babb..9b6c2fd 100644 --- a/apps/desktop/src/settings.rs +++ b/apps/desktop/src/settings.rs @@ -133,6 +133,12 @@ pub struct Settings { pub install_id: String, /// The database of the reference tab (`None`: the largest one on the shelf). pub reference_db: Option, + /// The user's name: the annotator of games they add (own-databases.md §7). + pub your_name: String, + /// Where new databases are made (`None`: Documents/ChessPenguin). + pub new_database_dir: Option, + /// The database a game was last added to (preselected in the chooser). + pub last_target: Option, } /// Options of the whole-game analysis (the engine is the active one). @@ -194,6 +200,9 @@ impl Default for Settings { last_version: None, install_id: String::new(), reference_db: None, + your_name: String::new(), + new_database_dir: None, + last_target: None, } } } diff --git a/apps/desktop/src/settings_ui.rs b/apps/desktop/src/settings_ui.rs index db8f1ab..b1fd5d8 100644 --- a/apps/desktop/src/settings_ui.rs +++ b/apps/desktop/src/settings_ui.rs @@ -30,6 +30,8 @@ pub enum SettingsAction { EngineChanged, /// Ask now whether a newer version is out. CheckUpdates, + /// Choose the folder for new databases. + PickBaseFolder, /// Open the update window. OpenUpdate, } @@ -154,6 +156,39 @@ impl SettingsWindow { .selectable_value(&mut s.dark_mode, false, tr("Light")) .changed(); }); + ui.add_space(12.0); + ui.label(RichText::new(tr("Your databases")).strong()); + ui.horizontal(|ui| { + ui.label(tr("Your name:")); + changed |= ui + .add( + egui::TextEdit::singleline(&mut s.your_name) + .desired_width(220.0), + ) + .changed(); + }); + ui.label( + RichText::new(tr("Written as the annotator of the games you add")) + .weak(), + ); + ui.horizontal(|ui| { + ui.label(tr("Folder for new databases:")); + let dir = + crate::own_db::default_base_dir(s.new_database_dir.as_deref()); + // Short, under the home folder; the whole path on hover. + let home = directories::UserDirs::new() + .map(|u| u.home_dir().to_path_buf()); + let short = match home.as_ref().and_then(|h| dir.strip_prefix(h).ok()) + { + Some(rest) => format!("~{}{}", std::path::MAIN_SEPARATOR, rest.display()), + None => dir.display().to_string(), + }; + ui.label(RichText::new(short).weak()) + .on_hover_text(dir.display().to_string()); + if ui.button(tr("Change…")).clicked() { + actions.push(SettingsAction::PickBaseFolder); + } + }); } }); }); diff --git a/crates/chess-core/src/database.rs b/crates/chess-core/src/database.rs index 8a54a7c..731fe23 100644 --- a/crates/chess-core/src/database.rs +++ b/crates/chess-core/src/database.rs @@ -1,7 +1,7 @@ -//! A read-only PGN source: original bytes, encoding, index and lazy parsing. +//! A PGN source: original bytes, encoding, index and lazy parsing. //! -//! The source file is only read, never written. Saving is a separate explicit -//! operation of the application (write a new file from `Game::to_pgn`). +//! Reading never writes the file. Writing a record into it is a separate explicit +//! operation (`crate::pgn::store`), and the file is read again after it. use std::io; use std::path::{Path, PathBuf}; @@ -75,8 +75,10 @@ impl PgnDatabase { path: path.to_owned(), source, }; - let bytes = std::fs::read(path).map_err(io_err)?; + // The time first: a write that lands while the bytes are read is then seen as + // a change (the time moved on). let modified = std::fs::metadata(path).and_then(|m| m.modified()).ok(); + let bytes = std::fs::read(path).map_err(io_err)?; let mut db = Self::from_bytes(bytes, None, progress, cancel)?; db.path = Some(path.to_owned()); db.fingerprint.modified = modified; @@ -119,6 +121,11 @@ impl PgnDatabase { &self.entries } + /// The file's bytes as read. + pub fn bytes(&self) -> &[u8] { + &self.bytes + } + /// Size of the PGN text, in bytes. pub fn byte_len(&self) -> usize { self.bytes.len() diff --git a/crates/chess-core/src/game.rs b/crates/chess-core/src/game.rs index c8f7e73..c2b9a43 100644 --- a/crates/chess-core/src/game.rs +++ b/crates/chess-core/src/game.rs @@ -282,6 +282,16 @@ impl Game { .map(|(_, v)| v.as_str()) } + /// Drops a tag (not part of undo history); nothing when it is not there. + pub fn remove_tag(&mut self, name: &str) { + let before = self.tags.len(); + self.tags.retain(|(k, _)| k != name); + if self.tags.len() != before { + self.unsaved_meta = true; + self.touch(); + } + } + /// Sets or appends a tag (not part of undo history). pub fn set_tag(&mut self, name: &str, value: &str) { match self.tags.iter_mut().find(|(k, _)| k == name) { @@ -308,6 +318,42 @@ impl Game { self.set_tag("Result", result.as_str()); } + /// The seven tags of the PGN standard, first and in their order, with "?" for the + /// unknown ones (a game written by hand gets a proper tag roster); the other tags + /// follow as they were. Not part of undo history. + pub fn order_roster(&mut self) { + let result = self.result().as_str().to_owned(); + let roster = [ + ("Event", "?"), + ("Site", "?"), + ("Date", "????.??.??"), + ("Round", "?"), + ("White", "?"), + ("Black", "?"), + ("Result", result.as_str()), + ]; + let mut tags: Vec<(String, String)> = Vec::with_capacity(self.tags.len() + 7); + for (name, unknown) in roster { + let value = self + .tags + .iter() + .find(|(k, _)| k == name) + .map_or(unknown, |(_, v)| v.as_str()); + tags.push((name.to_owned(), value.to_owned())); + } + tags.extend( + self.tags + .iter() + .filter(|(k, _)| !roster.iter().any(|(name, _)| k == name)) + .cloned(), + ); + if tags != self.tags { + self.tags = tags; + self.unsaved_meta = true; + self.touch(); + } + } + // ----- node access ------------------------------------------------------ pub fn root(&self) -> NodeId { diff --git a/crates/chess-core/src/pgn/mod.rs b/crates/chess-core/src/pgn/mod.rs index 8d9b59a..e04865c 100644 --- a/crates/chess-core/src/pgn/mod.rs +++ b/crates/chess-core/src/pgn/mod.rs @@ -3,6 +3,7 @@ mod lexer; pub mod parse; pub mod scan; +pub mod store; pub mod write; pub use parse::{ diff --git a/crates/chess-core/src/pgn/store.rs b/crates/chess-core/src/pgn/store.rs new file mode 100644 index 0000000..69b4111 --- /dev/null +++ b/crates/chess-core/src/pgn/store.rs @@ -0,0 +1,616 @@ +//! Writing records into a PGN file the user keeps (docs/design/own-databases.md): one +//! record appended to the end, a record replaced or removed, a removed record put +//! back (undo). Every write is explicit, and the other records stay byte for byte as +//! they were: an append only adds at the end; a replacement or a removal writes the +//! whole file anew into a temporary file beside it and renames it over the old one, +//! after `sync_all`. A file that changed on disk since it was read is not touched. +//! +//! Only files the program decodes as UTF-8 (or plain ASCII) are written: a record is +//! written as UTF-8, so a file in another encoding would end up mixed. The line endings +//! of a new record follow the file's (CRLF when its first line ends so). + +use std::io::{self, Write as _}; +use std::path::Path; + +use crate::database::PgnDatabase; + +/// Why a write did not happen. +#[derive(Debug, thiserror::Error)] +pub enum WriteError { + /// The file on disk is not what was read: another program wrote it meanwhile. + #[error("the file changed on disk since it was read")] + Changed, + /// The database was opened from memory, not from a file. + #[error("the database has no file")] + NoFile, + /// The database's text is not UTF-8: appending UTF-8 would mix encodings. + #[error("the file is not in UTF-8")] + Encoding, + #[error("no record {0}")] + NoRecord(usize), + #[error(transparent)] + Io(#[from] io::Error), +} + +/// What an append tells about the record it wrote: where it starts in the file (after +/// the file is read again, the record whose range starts here is the new one). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Appended { + pub offset: u64, +} + +/// A record removed from the file, enough to put it back where it was (undo). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Removed { + pub index: usize, + pub bytes: Vec, +} + +/// `"\r\n"` when the first line of `bytes` ends so, else `"\n"`. +fn line_ending(bytes: &[u8]) -> &'static str { + match bytes.iter().position(|b| *b == b'\n') { + Some(i) if i > 0 && bytes[i - 1] == b'\r' => "\r\n", + _ => "\n", + } +} + +/// `record` with its line endings as the file has them, ending with one blank line. +fn record_bytes(record: &str, eol: &str) -> Vec { + let text = record.trim_end(); + let mut out = String::with_capacity(text.len() + 4); + for line in text.split('\n') { + out.push_str(line.trim_end_matches('\r')); + out.push_str(eol); + } + out.push_str(eol); + out.into_bytes() +} + +/// What to put between the end of `bytes` and an appended record, so that the record +/// starts after a blank line: nothing, one or two line endings. +fn separator(bytes: &[u8], eol: &str) -> &'static str { + let ends_with = |suffix: &str| bytes.ends_with(suffix.as_bytes()); + if bytes.is_empty() || ends_with(&format!("{eol}{eol}")) { + "" + } else if ends_with(eol) { + if eol == "\r\n" { "\r\n" } else { "\n" } + } else if eol == "\r\n" { + "\r\n\r\n" + } else { + "\n\n" + } +} + +fn check_writable(db: &PgnDatabase) -> Result<&Path, WriteError> { + let path = db.path().ok_or(WriteError::NoFile)?; + if db.encoding() != crate::encoding::TextEncoding::Utf8 && !db.detected_encoding().ascii_only { + return Err(WriteError::Encoding); + } + if db.source_changed()? { + return Err(WriteError::Changed); + } + Ok(path) +} + +/// Appends `record` (PGN text of one game) to the file of `db`. The file is opened for +/// appending, so a record added by someone else meanwhile is not lost; the file's bytes +/// before the new record stay as they were. +pub fn append(db: &PgnDatabase, record: &str) -> Result { + let path = check_writable(db)?; + let bytes = db.bytes(); + let eol = line_ending(bytes); + let sep = separator(bytes, eol); + let mut data = sep.as_bytes().to_vec(); + data.extend(record_bytes(record, eol)); + let mut file = std::fs::OpenOptions::new().append(true).open(path)?; + let offset = file.metadata()?.len() + sep.len() as u64; + file.write_all(&data)?; + file.sync_all()?; + Ok(Appended { offset }) +} + +/// Replaces record `index` with `record`; every other byte of the file stays. +pub fn replace(db: &PgnDatabase, index: usize, record: &str) -> Result<(), WriteError> { + let path = check_writable(db)?; + let bytes = db.bytes(); + let range = db + .entries() + .get(index) + .ok_or(WriteError::NoRecord(index))? + .byte_range + .clone(); + let eol = line_ending(bytes); + let mut out = Vec::with_capacity(bytes.len() + record.len()); + out.extend_from_slice(&bytes[..range.start]); + out.extend(record_bytes(record, eol)); + out.extend_from_slice(&bytes[range.end..]); + write_atomic(path, &out)?; + Ok(()) +} + +/// Removes record `index`; the bytes before and after it stay. What was removed comes +/// back with [`restore`]. +pub fn remove(db: &PgnDatabase, index: usize) -> Result { + let path = check_writable(db)?; + let bytes = db.bytes(); + let range = db + .entries() + .get(index) + .ok_or(WriteError::NoRecord(index))? + .byte_range + .clone(); + let mut out = Vec::with_capacity(bytes.len()); + out.extend_from_slice(&bytes[..range.start]); + out.extend_from_slice(&bytes[range.end..]); + write_atomic(path, &out)?; + Ok(Removed { + index, + bytes: bytes[range].to_vec(), + }) +} + +/// Puts a removed record back at its place: the file is byte for byte what it was +/// before the removal, as long as nothing else was written in between. `db` is the +/// database as read after the removal. +pub fn restore(db: &PgnDatabase, removed: &Removed) -> Result<(), WriteError> { + let path = check_writable(db)?; + let bytes = db.bytes(); + let at = match db.entries().get(removed.index) { + Some(e) => e.byte_range.start, + None if removed.index == db.len() => bytes.len(), + None => return Err(WriteError::NoRecord(removed.index)), + }; + let mut out = Vec::with_capacity(bytes.len() + removed.bytes.len()); + out.extend_from_slice(&bytes[..at]); + out.extend_from_slice(&removed.bytes); + out.extend_from_slice(&bytes[at..]); + write_atomic(path, &out)?; + Ok(()) +} + +/// Writes every record of `db` into `dest` as UTF-8 (LF, one blank line between +/// records): a copy of a file in another encoding, which can then be written to. `db` +/// itself is not touched. `dest` must not exist. +pub fn write_utf8_copy(db: &PgnDatabase, dest: &Path) -> io::Result<()> { + if dest.exists() { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + format!("{} exists", dest.display()), + )); + } + let mut out = Vec::with_capacity(db.byte_len()); + // Letters the source writes as `~~`/`o^` (see repair.rs) are restored in the copy, + // as they are on the screen: the copy is read as UTF-8, where nothing is restored. + let restore = db.repair_letters_enabled(); + for i in 0..db.len() { + if let Some(text) = db.raw_text(i) { + let text = if restore { + crate::repair::repair_letters(&text).0 + } else { + text + }; + out.extend(record_bytes(&text, "\n")); + } + } + write_atomic(dest, &out) +} + +/// The record of `db` that is the same game as `game`: the same players and date, and +/// the same moves of the main line. `None` when there is none. +pub fn find_same_game(db: &PgnDatabase, game: &crate::Game) -> Option { + // Names compared without case; an unknown date in any spelling is one value. + let name = |v: Option<&str>| v.unwrap_or("?").trim().to_lowercase(); + let date = |v: Option<&str>| match v.map(str::trim) { + None | Some("" | "?") => "????.??.??".to_owned(), + Some(d) => d.to_owned(), + }; + let (white, black, when) = ( + name(game.tag("White")), + name(game.tag("Black")), + date(game.tag("Date")), + ); + let sans: Vec<&str> = game + .mainline() + .iter() + .filter_map(|id| game.game_move(*id).map(|m| m.san.as_str())) + .collect(); + (0..db.len()).find(|&i| { + let e = &db.entries()[i]; + if name(e.white()) != white || name(e.black()) != black || date(e.date()) != when { + return false; + } + let Some(parsed) = db.load_game(i) else { + return false; + }; + // Two studies from different positions are different games. + if parsed.game.tag("FEN") != game.tag("FEN") { + return false; + } + let other: Vec = parsed + .game + .mainline() + .iter() + .filter_map(|id| parsed.game.game_move(*id).map(|m| m.san.clone())) + .collect(); + other.len() == sans.len() && other.iter().zip(&sans).all(|(a, b)| a == b) + }) +} + +/// A date as the user types it — `2026.10.18`, `18.10.2026`, `2026-10-18`, `2026.10`, +/// `2026`, nothing — as PGN writes it (`2026.10.18`, `2026.10.??`, `????.??.??`). +/// `None` for text that is not a date. +pub fn pgn_date(input: &str) -> Option { + let t = input.trim(); + if t.is_empty() || t.chars().all(|c| c == '?' || c == '.') { + return Some("????.??.??".to_owned()); + } + let parts: Vec<&str> = t.split(['.', '-', '/']).map(str::trim).collect(); + let num = |s: &str| s.parse::().ok(); + // A month or day may be unknown, as PGN writes it: "1910.??.??". + let part = |s: &str| -> Option> { + if !s.is_empty() && s.chars().all(|c| c == '?') { + Some(None) + } else { + num(s).map(Some) + } + }; + // A year is written with four digits: "12.10" is not a date. + let (y, m, d) = match parts.as_slice() { + [y] if y.len() == 4 => (num(y)?, None, None), + [y, m] if y.len() == 4 => (num(y)?, part(m)?, None), + [_] | [_, _] => return None, + [a, b, c] => { + if a.len() == 4 && a.chars().all(|c| c.is_ascii_digit()) { + (num(a)?, part(b)?, part(c)?) + } else if c.len() == 4 { + (num(c)?, part(b)?, part(a)?) + } else { + return None; + } + } + _ => return None, + }; + if !(1..=9999).contains(&y) + || m.is_some_and(|m| !(1..=12).contains(&m)) + || d.is_some_and(|d| !(1..=31).contains(&d)) + { + return None; + } + Some(format!( + "{y:04}.{}.{}", + m.map_or("??".to_owned(), |m| format!("{m:02}")), + d.map_or("??".to_owned(), |d| format!("{d:02}")) + )) +} + +/// Writes `bytes` to `path` through a temporary file in the same directory: the old +/// file stays whole until the new one is on disk (`sync_all`), then is replaced. +pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { + // A link to the file is a way to it, not the file: the target is rewritten. + let target = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_owned()); + let path = target.as_path(); + if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) { + std::fs::create_dir_all(dir)?; + } + let name = path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let tmp = path.with_file_name(format!(".{name}.tmp{}", std::process::id())); + let result = (|| { + let mut file = std::fs::File::create(&tmp)?; + // The file keeps its permissions (a private 600 stays 600). + if let Ok(meta) = std::fs::metadata(path) { + file.set_permissions(meta.permissions())?; + } + file.write_all(bytes)?; + file.sync_all()?; + std::fs::rename(&tmp, path)?; + // The rename itself reaches the disk with the folder. + if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) + && let Ok(d) = std::fs::File::open(dir) + { + let _ = d.sync_all(); + } + Ok(()) + })(); + if result.is_err() { + let _ = std::fs::remove_file(&tmp); + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::pgn::parse_str; + use std::sync::atomic::AtomicBool; + + fn open(path: &Path) -> PgnDatabase { + PgnDatabase::open(path, &mut |_| {}, &AtomicBool::new(false)).expect("opens") + } + + fn dir(name: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("cp-store-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + const G1: &str = "[Event \"One\"]\n[White \"A\"]\n[Black \"B\"]\n\n1. e4 e5 *\n"; + const G2: &str = + "[Event \"Two\"]\n[White \"C\"]\n[Black \"D\"]\n\n1. d4 d5 {a comment} 1/2-1/2\n"; + const G3: &str = "[Event \"Three\"]\n[White \"E\"]\n[Black \"F\"]\n\n1. c4 1-0\n"; + + fn new_record() -> String { + parse_str("[Event \"New\"]\n[White \"X\"]\n[Black \"Y\"]\n\n1. Nf3 d5 2. g3 *\n") + .game + .to_pgn() + } + + fn records(db: &PgnDatabase) -> Vec> { + (0..db.len()) + .map(|i| db.raw_bytes(i).unwrap().to_vec()) + .collect() + } + + /// Records without their trailing whitespace: an append adds a blank line after + /// the last one, which is still the same record. + fn trimmed(records: &[Vec]) -> Vec> { + records + .iter() + .map(|r| { + r[..r.len() + - r.iter() + .rev() + .take_while(|b| b.is_ascii_whitespace()) + .count()] + .to_vec() + }) + .collect() + } + + #[test] + fn append_to_files_of_every_shape() { + for (name, content) in [ + ("blank-line", format!("{G1}\n{G2}\n")), + ("one-newline", format!("{G1}\n{G2}")), + ("no-newline", format!("{G1}\n{}", G2.trim_end())), + ("crlf", format!("{G1}\n{G2}").replace('\n', "\r\n")), + ("empty", String::new()), + ] { + let d = dir(name); + let path = d.join("base.pgn"); + std::fs::write(&path, &content).unwrap(); + let db = open(&path); + let before = records(&db); + let added = append(&db, &new_record()).unwrap(); + let after_bytes = std::fs::read(&path).unwrap(); + assert!( + after_bytes.starts_with(content.as_bytes()), + "{name}: old bytes kept" + ); + let db2 = open(&path); + assert_eq!(db2.len(), before.len() + 1, "{name}"); + assert_eq!( + trimmed(&records(&db2)[..before.len()]), + trimmed(&before), + "{name}: old records same" + ); + let new = db2.entries().last().unwrap(); + assert_eq!(new.byte_range.start as u64, added.offset, "{name}: offset"); + assert_eq!(new.white(), Some("X")); + let parsed = db2.load_game(db2.len() - 1).unwrap(); + assert_eq!( + parsed.game.canonical_tree(), + parse_str(&new_record()).game.canonical_tree() + ); + if name == "crlf" { + let text = String::from_utf8(after_bytes).unwrap(); + assert!(!text.contains("[^\r]\n"), "no bare LF"); + assert!(text.ends_with("\r\n\r\n")); + } else { + assert!(after_bytes.ends_with(b"\n\n")); + } + // A second append starts after a blank line too. + let db3 = open(&path); + append(&db3, &new_record()).unwrap(); + assert_eq!(open(&path).len(), before.len() + 2, "{name}: twice"); + } + } + + #[test] + fn replace_keeps_the_other_records() { + for k in 0..3 { + let d = dir(&format!("replace{k}")); + let path = d.join("base.pgn"); + std::fs::write(&path, format!("{G1}\n{G2}\n{G3}\n")).unwrap(); + let db = open(&path); + let before = records(&db); + replace(&db, k, &new_record()).unwrap(); + let db2 = open(&path); + assert_eq!(db2.len(), 3); + let after = records(&db2); + for i in 0..3 { + if i != k { + assert_eq!( + after[i], before[i], + "record {i} unchanged when {k} replaced" + ); + } + } + assert_eq!(db2.entries()[k].white(), Some("X")); + } + // The only record. + let d = dir("replace-only"); + let path = d.join("base.pgn"); + std::fs::write(&path, G1).unwrap(); + replace(&open(&path), 0, &new_record()).unwrap(); + let db = open(&path); + assert_eq!(db.len(), 1); + assert_eq!(db.entries()[0].white(), Some("X")); + } + + #[test] + fn remove_and_restore_are_exact() { + for k in 0..3 { + let d = dir(&format!("remove{k}")); + let path = d.join("base.pgn"); + let content = format!("{G1}\n{G2}\n{G3}\n"); + std::fs::write(&path, &content).unwrap(); + let db = open(&path); + let before = records(&db); + let removed = remove(&db, k).unwrap(); + let db2 = open(&path); + assert_eq!(db2.len(), 2); + let after = records(&db2); + let expected: Vec<_> = before + .iter() + .enumerate() + .filter(|(i, _)| *i != k) + .map(|(_, r)| r.clone()) + .collect(); + assert_eq!(after, expected, "others kept when {k} removed"); + restore(&db2, &removed).unwrap(); + assert_eq!( + std::fs::read(&path).unwrap(), + content.as_bytes(), + "restored byte for byte" + ); + } + } + + #[test] + fn a_changed_file_is_not_written() { + let d = dir("changed"); + let path = d.join("base.pgn"); + std::fs::write(&path, format!("{G1}\n{G2}\n")).unwrap(); + let db = open(&path); + // Another program appends; the modification time moves on. + std::thread::sleep(std::time::Duration::from_millis(20)); + std::fs::OpenOptions::new() + .append(true) + .open(&path) + .unwrap() + .write_all(G3.as_bytes()) + .unwrap(); + assert!(db.source_changed().unwrap()); + assert!(matches!( + replace(&db, 0, &new_record()), + Err(WriteError::Changed) + )); + assert!(matches!(remove(&db, 0), Err(WriteError::Changed))); + assert!(matches!( + append(&db, &new_record()), + Err(WriteError::Changed) + )); + } + + /// A crash in the middle of an append leaves a broken tail; the next append goes + /// after it, never into it, and the records before it stay whole. + #[test] + fn a_broken_tail_is_appended_after() { + let d = dir("broken"); + let path = d.join("base.pgn"); + let half = &G2[..G2.len() - 8]; + let content = format!("{G1}\n{half}"); + std::fs::write(&path, &content).unwrap(); + let db = open(&path); + assert_eq!(db.len(), 2); + let added = append(&db, &new_record()).unwrap(); + let bytes = std::fs::read(&path).unwrap(); + assert!(bytes.starts_with(content.as_bytes())); + assert_eq!( + &bytes[added.offset as usize..], + &record_bytes(&new_record(), "\n")[..] + ); + let db2 = open(&path); + assert_eq!(db2.len(), 3); + assert_eq!(db2.entries()[0].white(), Some("A")); + assert_eq!(db2.entries()[2].white(), Some("X")); + } + + #[test] + fn other_encodings_are_refused_and_copied() { + let d = dir("cp1251"); + let path = d.join("base.pgn"); + let (bytes, _, _) = encoding_rs::WINDOWS_1251 + .encode("[Event \"Турнир\"]\n[White \"Иванов\"]\n[Black \"Петров\"]\n\n1. e4 e5 *\n"); + std::fs::write(&path, &bytes).unwrap(); + let db = open(&path); + assert_eq!(db.encoding(), crate::encoding::TextEncoding::Windows1251); + assert!(matches!( + append(&db, &new_record()), + Err(WriteError::Encoding) + )); + let copy = d.join("base (UTF-8).pgn"); + write_utf8_copy(&db, ©).unwrap(); + assert_eq!( + std::fs::read(&path).unwrap(), + bytes.as_ref(), + "original untouched" + ); + let db2 = open(©); + assert_eq!(db2.encoding(), crate::encoding::TextEncoding::Utf8); + assert_eq!(db2.len(), 1); + assert_eq!(db2.entries()[0].white(), Some("Иванов")); + assert_eq!(db2.raw_text(0), db.raw_text(0)); + assert!( + matches!(write_utf8_copy(&db, ©), Err(e) if e.kind() == io::ErrorKind::AlreadyExists) + ); + } + + #[test] + fn an_empty_file_is_a_database() { + let d = dir("empty"); + let path = d.join("new.pgn"); + std::fs::write(&path, "").unwrap(); + let db = open(&path); + assert_eq!(db.len(), 0); + append(&db, &new_record()).unwrap(); + assert_eq!(open(&path).len(), 1); + } + + #[test] + fn dates_as_typed() { + assert_eq!(pgn_date("").as_deref(), Some("????.??.??")); + assert_eq!(pgn_date("?").as_deref(), Some("????.??.??")); + assert_eq!(pgn_date("2026.10.18").as_deref(), Some("2026.10.18")); + assert_eq!(pgn_date("18.10.2026").as_deref(), Some("2026.10.18")); + assert_eq!(pgn_date("2026-10-18").as_deref(), Some("2026.10.18")); + assert_eq!(pgn_date("2026.10").as_deref(), Some("2026.10.??")); + assert_eq!(pgn_date(" 2026 ").as_deref(), Some("2026.??.??")); + assert_eq!(pgn_date("1.1.2026").as_deref(), Some("2026.01.01")); + assert_eq!(pgn_date("tomorrow"), None); + assert_eq!(pgn_date("2026.13.01"), None); + assert_eq!(pgn_date("12.10"), None); + // PGN's own unknown parts. + assert_eq!(pgn_date("1910.??.??").as_deref(), Some("1910.??.??")); + assert_eq!(pgn_date("1910.05.??").as_deref(), Some("1910.05.??")); + assert_eq!(pgn_date("1910.??.05").as_deref(), Some("1910.??.05")); + } + + #[test] + fn the_same_game_is_found() { + let d = dir("same"); + let path = d.join("base.pgn"); + std::fs::write(&path, format!("{G1}\n{G2}\n")).unwrap(); + let db = open(&path); + let same = parse_str("[White \"C\"]\n[Black \"D\"]\n[Date \"?\"]\n\n1. d4 d5 *\n").game; + assert_eq!(find_same_game(&db, &same), Some(1)); + let other_moves = parse_str("[White \"C\"]\n[Black \"D\"]\n\n1. d4 Nf6 *\n").game; + assert_eq!(find_same_game(&db, &other_moves), None); + let other_player = parse_str("[White \"C\"]\n[Black \"Z\"]\n\n1. d4 d5 *\n").game; + assert_eq!(find_same_game(&db, &other_player), None); + } + + #[test] + fn tag_values_with_quotes_survive() { + let mut g = parse_str("[Event \"?\"]\n\n*\n").game; + g.set_tag("White", "Smith \"Jr\" \\ O'Neil"); + g.set_tag("Event", "Cup"); + let text = g.to_pgn(); + let again = parse_str(&text).game; + assert_eq!(again.tag("White"), Some("Smith \"Jr\" \\ O'Neil")); + } +} diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index 595674c..43b14eb 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -28,6 +28,7 @@ egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `i | `engines.rs` | Поиск движков: встроенный Stockfish (`/lib/chesspenguin/stockfish` или `stockfish/` рядом с exe), системный `stockfish` в `PATH`; настройка при первом запуске, подсказки в настройках | | `review.rs` | Анализ партии целиком на компьютере: фоновый поток задания, график, вкладка «Отчёт», окно запуска, запись анализа в партию. Оценки, суждения, точность, кэш и само задание движка (`go nodes N`) — в общем крейте `crates/game-review` (вместе с Android) | | `assets.rs`, `sound.rs` | Встроенные SVG-фигуры, темы доски, звуки (rodio в отдельном потоке) | +| `own_db.rs` | Свои базы (`docs/design/own-databases.md`): диалоги «Новая база», «Добавить в базу» (список полки с числом партий и причиной, почему база не принимает партии: онлайн, только чтение, legacy-кодировка → копия в UTF‑8, нет прав, файла нет), «Данные партии» (семь тегов, Эло, комментатор из «Ваше имя»; дата в любом из принятых видов), вопросы (дубликат, удаление, копия в UTF‑8, ошибка записи, файл изменился, большая база); `Block` — что мешает записи; `show_in_folder`. Сами потоки — в `app.rs` (`save_current`, `open_chooser`, `add_current_to`, `append_record`, `delete_now`/`undo_delete`, `create_base`, `own_dialogs`); запись — `chess_core::pgn::store` (append/replace/remove/restore/write_utf8_copy, проверка, что файл не изменился) | | `settings.rs`, `settings_ui.rs` | JSON в `$XDG_CONFIG_HOME/chesspenguin/settings.json` (атомарная запись), окно настроек | ## Инварианты @@ -50,7 +51,7 @@ XDG_CONFIG_HOME=/tmp/cfg CP_OPEN=11 CP_PLY=3 CP_ANALYZE=1 ./target/debug/chesspe ``` `CP_OPEN` — индекс партии (с 0) в первой базе списка, `CP_PLY` — шагов по основной линии, -`CP_ONLINE=<ник>` (или `<ник Lichess>,<ник Chess.com>`) — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу скачать). `CP_UPDATE_CHECK=<адрес>` — спрашивать о выпуске этот сайт вместо chess.vrubel.xyz/api/update (локальный, чтобы проверить счёт установок). `CP_UPDATE_SOURCE=<папка>` — брать «последний выпуск» из `latest.json` и файлов этой папки вместо GitHub, `CP_UPDATE_KIND=deb|rpm|arch|aur|flatpak|appimage|tarball|windows|mac` — считать установку такой, `CP_UPDATE_OPEN=1` — открыть окно обновления (`=start` — сразу начать), `CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about`, `=translation` — сразу эту вкладку), `CP_TRANSLATE_SETUP=1` — окно «Как переводить?» (`=key` — с выбранным ключом API), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска базы с этими ходами (SAN), `CP_SORT=date` — база по дате (новые сверху), `CP_PANE=hidden` — база без правой панели (`=drawer` — фильтры поверх таблицы в узком окне), `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» базы при запуске, `CP_SEARCH="текст"` — быстрый поиск базы при запуске, `CP_KEYS="ArrowDown Shift+ArrowUp Escape"` — нажать эти клавиши (имена egui, по одной раз в полсекунды со второй секунды), `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_PANEL_CHECK=1` — сообщать в stderr о боковой панели, чьё содержимое шире её места (egui тогда задвигает панель под соседнюю); в отладочной сборке egui ещё и подсвечивает красным, что расширяет родителя (`docs/design/narrow-windows.md`). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). +`CP_ONLINE=<ник>` (или `<ник Lichess>,<ник Chess.com>`) — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу скачать). `CP_UPDATE_CHECK=<адрес>` — спрашивать о выпуске этот сайт вместо chess.vrubel.xyz/api/update (локальный, чтобы проверить счёт установок). `CP_UPDATE_SOURCE=<папка>` — брать «последний выпуск» из `latest.json` и файлов этой папки вместо GitHub, `CP_UPDATE_KIND=deb|rpm|arch|aur|flatpak|appimage|tarball|windows|mac` — считать установку такой, `CP_UPDATE_OPEN=1` — открыть окно обновления (`=start` — сразу начать), `CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about`, `=translation` — сразу эту вкладку), `CP_TRANSLATE_SETUP=1` — окно «Как переводить?» (`=key` — с выбранным ключом API), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска базы с этими ходами (SAN), `CP_SORT=date` — база по дате (новые сверху), `CP_PANE=hidden` — база без правой панели (`=drawer` — фильтры поверх таблицы в узком окне), `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» базы при запуске, `CP_SEARCH="текст"` — быстрый поиск базы при запуске, `CP_KEYS="ArrowDown Shift+ArrowUp Ctrl+Z Escape"` — нажать эти клавиши (имена egui, по одной раз в полсекунды со второй секунды; модификаторы `Shift+`, `Ctrl+`), `CP_OWN=new|chooser|data|save|delete` — открыть диалог своих баз через 1,5 с: новая база, «Добавить в базу» (для открытой партии, иначе для записи `CP_OPEN` первой базы), данные партии, Ctrl+S, удаление записи `CP_OPEN` первой базы; `CP_PASTE="<текст PGN>"` — перед `CP_OWN` открыть эту партию как вставленную (без базы), `CP_COMMENT=текст` — комментарий к ходу после `CP_PLY` (партия считается изменённой), `CP_SETTINGS=interface` — вкладка «Интерфейс», `CP_LOG_FRAMES=1` — писать в `chesspenguin.log` отладочные сообщения egui_wgpu о каждом кадре (пропущенный как «occluded» кадр виден только там); предупреждения библиотек (wgpu, winit) пишутся туда всегда, одинаковые — раз в минуту со счётчиком, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_PANEL_CHECK=1` — сообщать в stderr о боковой панели, чьё содержимое шире её места (egui тогда задвигает панель под соседнюю); в отладочной сборке egui ещё и подсвечивает красным, что расширяет родителя (`docs/design/narrow-windows.md`). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). ## Языки diff --git a/docs/dev/tasks.md b/docs/dev/tasks.md index afdf706..56f95b8 100644 --- a/docs/dev/tasks.md +++ b/docs/dev/tasks.md @@ -83,6 +83,13 @@ - **Чем поиск сейчас отличается** (`docs/design/large-databases.md` §9.2): одно поле ищет сразу по всему — игрокам, турниру, комментатору, ECO, году, дате — без выбора поля и без открытия панели; слова можно смешивать («вафин 2025»). Фильтры точнее: цвет, диапазон лет, Эло, результат, длина, аннотации. Поиск и фильтры складываются. - **Что решить:** оставить оба (поиск — быстрый ввод, фильтры — точная настройка), объединить (поле поиска сверху панели фильтров) или убрать поиск. Обсудить с дизайнером на реальном использовании. +### 9. Режим ввода партии: писать комментарии к ходам +- **Статус:** новая. +- **Добавлено:** 2026-10-25. +- **От кого:** владелец. +- **Суть:** при вводе партии (новая партия, своя база) нужно писать текстовые комментарии к ходам прямо в программе — сейчас комментарии только читаются (и приходят из анализа). +- **Мысли:** поле комментария под нотацией или по двойному клику/клавише у хода; запись через `Game::annotate` (уже есть, с Undo); комментарии до хода и после; NAG-символы (!, ?, ±…) той же панелью; сохранение в свою базу — Ctrl+S (задача «свои базы»). + ## Сделано (пусто)