Own databases: create PGN bases, add, save, delete games; library logging
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 <noreply@anthropic.com>
This commit is contained in:
parent
b6024e9bdd
commit
0f66486a22
20 changed files with 4428 additions and 73 deletions
19
CHANGELOG.md
19
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.
|
||||
|
|
|
|||
37
Cargo.lock
generated
37
Cargo.lock
generated
|
|
@ -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"
|
||||
|
|
|
|||
10
README.md
10
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
|
||||
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -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<crate::own_db::Block>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
/// 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<String>,
|
||||
/// 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<String> {
|
||||
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<String> = 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))
|
||||
|
|
|
|||
|
|
@ -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<Option<(String, std::time::Instant, u32)>>,
|
||||
/// `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<LibraryLog> = 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 {
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -319,6 +319,11 @@ pub struct LargeView {
|
|||
blocked: Option<u64>,
|
||||
/// 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<LibraryAction>,
|
||||
) -> 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 };
|
||||
|
|
|
|||
|
|
@ -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::<f32>() + 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<crate::own_db::Block> {
|
||||
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());
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
993
apps/desktop/src/own_db.rs
Normal file
993
apps/desktop/src/own_db.rs
Normal file
|
|
@ -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<String>,
|
||||
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<bool, String> {
|
||||
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<NewBaseOutcome> {
|
||||
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<usize>,
|
||||
pub block: Option<Block>,
|
||||
}
|
||||
|
||||
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<ChooserRow>,
|
||||
pub selected: Option<usize>,
|
||||
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<ChooserRow>,
|
||||
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<ChooserRow>) {
|
||||
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<ChooserOutcome> {
|
||||
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<usize> = (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<usize> = 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<usize> = 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<String>,
|
||||
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<String> = 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::<Vec<_>>()
|
||||
.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<EditorOutcome> {
|
||||
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<Answer> {
|
||||
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<String>, Option<String>, &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());
|
||||
}
|
||||
}
|
||||
|
|
@ -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<PathBuf>,
|
||||
/// 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<PathBuf>,
|
||||
/// The database a game was last added to (preselected in the chooser).
|
||||
pub last_target: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
mod lexer;
|
||||
pub mod parse;
|
||||
pub mod scan;
|
||||
pub mod store;
|
||||
pub mod write;
|
||||
|
||||
pub use parse::{
|
||||
|
|
|
|||
616
crates/chess-core/src/pgn/store.rs
Normal file
616
crates/chess-core/src/pgn/store.rs
Normal file
|
|
@ -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<u8>,
|
||||
}
|
||||
|
||||
/// `"\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<u8> {
|
||||
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<Appended, WriteError> {
|
||||
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<Removed, 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 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<usize> {
|
||||
// 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<String> = 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<String> {
|
||||
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::<u32>().ok();
|
||||
// A month or day may be unknown, as PGN writes it: "1910.??.??".
|
||||
let part = |s: &str| -> Option<Option<u32>> {
|
||||
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<Vec<u8>> {
|
||||
(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<u8>]) -> Vec<Vec<u8>> {
|
||||
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"));
|
||||
}
|
||||
}
|
||||
|
|
@ -28,6 +28,7 @@ egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `i
|
|||
| `engines.rs` | Поиск движков: встроенный Stockfish (`<prefix>/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).
|
||||
|
||||
## Языки
|
||||
|
||||
|
|
|
|||
|
|
@ -83,6 +83,13 @@
|
|||
- **Чем поиск сейчас отличается** (`docs/design/large-databases.md` §9.2): одно поле ищет сразу по всему — игрокам, турниру, комментатору, ECO, году, дате — без выбора поля и без открытия панели; слова можно смешивать («вафин 2025»). Фильтры точнее: цвет, диапазон лет, Эло, результат, длина, аннотации. Поиск и фильтры складываются.
|
||||
- **Что решить:** оставить оба (поиск — быстрый ввод, фильтры — точная настройка), объединить (поле поиска сверху панели фильтров) или убрать поиск. Обсудить с дизайнером на реальном использовании.
|
||||
|
||||
### 9. Режим ввода партии: писать комментарии к ходам
|
||||
- **Статус:** новая.
|
||||
- **Добавлено:** 2026-10-25.
|
||||
- **От кого:** владелец.
|
||||
- **Суть:** при вводе партии (новая партия, своя база) нужно писать текстовые комментарии к ходам прямо в программе — сейчас комментарии только читаются (и приходят из анализа).
|
||||
- **Мысли:** поле комментария под нотацией или по двойному клику/клавише у хода; запись через `Game::annotate` (уже есть, с Undo); комментарии до хода и после; NAG-символы (!, ?, ±…) той же панелью; сохранение в свою базу — Ctrl+S (задача «свои базы»).
|
||||
|
||||
## Сделано
|
||||
|
||||
(пусто)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue