chessbaseLinux/apps/desktop/src/settings.rs

413 lines
14 KiB
Rust
Raw Normal View History

//! Persistent user settings (JSON in the XDG config dir), written atomically.
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::assets::{BoardThemeId, PieceSet, SoundSet};
use crate::i18n::Lang;
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct EngineConfig {
pub name: String,
pub path: PathBuf,
#[serde(default = "default_threads")]
pub threads: u32,
#[serde(default = "default_hash")]
pub hash_mb: u32,
#[serde(default = "default_multipv")]
pub multipv: u32,
/// Search time per position in seconds; `None` = infinite.
#[serde(default)]
pub search_secs: Option<u32>,
/// ChessPenguin's Stockfish (bundled in the Flatpak, otherwise downloaded on
/// request); `path` is unused and resolved at start.
#[serde(default)]
pub builtin: bool,
}
fn default_threads() -> u32 {
std::thread::available_parallelism()
.map(|n| (n.get() as u32 / 2).max(1))
.unwrap_or(1)
}
fn default_hash() -> u32 {
256
}
fn default_multipv() -> u32 {
3
}
impl EngineConfig {
pub fn new(name: String, path: PathBuf) -> Self {
Self {
name,
path,
threads: default_threads(),
hash_mb: default_hash(),
multipv: default_multipv(),
search_secs: None,
builtin: false,
}
}
/// Executable to start; `None` if ChessPenguin's Stockfish is neither bundled nor
/// downloaded yet (it is offered for download then).
pub fn executable(&self) -> Option<crate::engines::EngineLocation> {
if self.builtin {
crate::engines::own_stockfish()
} else {
// A browser runs no engine programs: there are none but its own.
#[cfg(not(web))]
return Some(crate::engines::EngineLocation::Program(self.path.clone()));
#[cfg(web)]
None
}
}
Web version, stage 2: Stockfish 19 in workers, live analysis, game review on N workers, My games, files, keys game-review: what the job does for one target (the full search, the second best without the move played, the shallow ones) becomes a machine without I/O (job/work.rs), driven by the engine processes on a computer (job/engines.rs, the same searches as before) and by Web Workers in a browser (job/workers.rs: a dispatcher polled from the frames, never blocking). The analysis cache goes through a CacheStore (a folder, or the program's files of the platform). The browser's engine: Stockfish.js 19.0.1 (npm stockfish, GPL-3.0), its single-threaded build served beside /app/ (engine/, build.sh checks the package's sha512), its 99 MB wasm downloaded only through the engine offer, checked against its SHA-256 and kept in Cache Storage; workers get it as a blob: address. Live analysis (lines, arrows, the bar) and the review run on it; the review uses one worker per logical CPU, at most 8. My games (the web version): a PGN in the browser's storage, always on the shelf; Ctrl+S puts a game there (its own record, or a new one); deleting with undo. chess-core's store gives the bytes of append/replace/remove/restore, so the platform writes them into the browser's files; on a computer the files are written as before. Settings: Browser data (used and free space, keeping the data for good, Download all as PGN, deleting the engine). Files: a file of the last visit offers Choose the file again; Keep a copy in the browser (refused with the room it needs when the browser gives too little); files over 1 GB are not opened, with a word on why. No reference tab and no search by position in the web version. Keys: Alt+Left, plain 1-6, Ctrl+C, N in the library (the browser keeps Ctrl+W/N/1-6/Shift+C). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 16:35:16 +03:00
/// Whether the engine can be started: ChessPenguin's Stockfish is there (in a
/// browser: downloaded into it), or the file of another engine.
pub fn present(&self) -> bool {
self.executable().is_some_and(|l| l.present())
Web version, stage 2: Stockfish 19 in workers, live analysis, game review on N workers, My games, files, keys game-review: what the job does for one target (the full search, the second best without the move played, the shallow ones) becomes a machine without I/O (job/work.rs), driven by the engine processes on a computer (job/engines.rs, the same searches as before) and by Web Workers in a browser (job/workers.rs: a dispatcher polled from the frames, never blocking). The analysis cache goes through a CacheStore (a folder, or the program's files of the platform). The browser's engine: Stockfish.js 19.0.1 (npm stockfish, GPL-3.0), its single-threaded build served beside /app/ (engine/, build.sh checks the package's sha512), its 99 MB wasm downloaded only through the engine offer, checked against its SHA-256 and kept in Cache Storage; workers get it as a blob: address. Live analysis (lines, arrows, the bar) and the review run on it; the review uses one worker per logical CPU, at most 8. My games (the web version): a PGN in the browser's storage, always on the shelf; Ctrl+S puts a game there (its own record, or a new one); deleting with undo. chess-core's store gives the bytes of append/replace/remove/restore, so the platform writes them into the browser's files; on a computer the files are written as before. Settings: Browser data (used and free space, keeping the data for good, Download all as PGN, deleting the engine). Files: a file of the last visit offers Choose the file again; Keep a copy in the browser (refused with the room it needs when the browser gives too little); files over 1 GB are not opened, with a word on why. No reference tab and no search by position in the web version. Keys: Alt+Left, plain 1-6, Ctrl+C, N in the library (the browser keeps Ctrl+W/N/1-6/Shift+C). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 16:35:16 +03:00
}
}
/// Piece animation, with Lichess's durations.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum Animation {
Off,
Fast,
#[default]
Normal,
Slow,
}
impl Animation {
pub const ALL: [Animation; 4] = [Self::Off, Self::Fast, Self::Normal, Self::Slow];
pub fn seconds(self) -> f32 {
match self {
Self::Off => 0.0,
Self::Fast => 0.12,
Self::Normal => 0.25,
Self::Slow => 0.5,
}
}
pub fn label(self) -> &'static str {
crate::i18n::tr(match self {
Self::Off => "Off",
Self::Fast => "Fast",
Self::Normal => "Normal",
Self::Slow => "Slow",
})
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct Settings {
pub piece_set: PieceSet,
pub board_theme: BoardThemeId,
pub show_coords: bool,
/// How fast moves slide on the board.
pub animation: Animation,
/// A pawn reaching the last rank becomes a queen without the choice of a piece.
pub auto_queen: bool,
/// How moves are shown: Latin letters, figurines or the interface language's letters.
pub move_notation: crate::san::MoveNotation,
/// Translating game comments (docs/design/translation.md).
pub translation: crate::translate::TranslationSettings,
pub sound_enabled: bool,
pub sound_set: SoundSet,
pub volume: f32,
pub dark_mode: bool,
pub language: Lang,
pub engines: Vec<EngineConfig>,
pub active_engine: Option<usize>,
pub show_best_arrow: bool,
/// Recently opened PGN files, most recent first.
pub databases: Vec<PathBuf>,
/// The first-start engine discovery has run (see `engines::first_run_setup`).
pub engines_discovered: bool,
/// The sample databases were put on the shelf (see `examples::setup`).
pub examples_added: bool,
/// Ask GitHub for a newer release at start (Settings → About).
pub check_updates: bool,
/// A version the user chose to skip (its button is not shown).
pub skipped_version: Option<String>,
/// The version that ran last (to say "updated to …" once).
pub last_version: Option<String>,
/// A random id of this installation, sent with the update check (the site counts
/// installations that run; nothing else identifies the user).
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>,
/// The user's rating (optional): the strength of Maia is chosen relative to it.
pub rating: Option<u32>,
/// The last choices of the play dialog.
pub play: crate::play::PlayPrefs,
/// Games against the computer go by themselves into the player's database.
pub record_games: bool,
/// Who played on this computer, the last first (`player_games.rs`).
pub players: Vec<crate::player_games::Player>,
Opponent prep: the desktop screen (dialog, report, engine run) The «Prepare against…» entry points in the library (the filter panel's button when a player is set, the game row's context menu, Ctrl+Shift+P), the dialog (database, the player's spellings with the similar names apart, colour, book) and the report screen in the stack between the library and the game: the repertoire tree with transpositions, opening names, scores and the book column, the openings table by family and variation, the errors tab (repeated errors and by opening), the board of the chosen position with the line under it, and the games of the selection, which open in the game screen at that move with «⬅ Back to preparation». The engine run reuses the game analysis job over the distinct opening positions of the chosen colour: the launch dialog shares the engine picker and the quality/threads/memory grid with review.rs (quality «Fast» by default, its own setting), marks appear as positions are evaluated, «Stop» keeps what was done, the evaluations and the report are cached under <cache>/prep. One engine job per program: game analysis and the live engine are blocked meanwhile. Core: targets and counts by colour (`targets_for`, `missing_for`), the book step keeps its per-position counts (`book_counts`) for the tree column. Narrow windows: the board stacks over the lists under 804 px and folds into a button under 720 px of height; the right column is split explicitly (a nested bottom panel is not reserved from the content above it in egui). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 15:43:15 +03:00
/// Preparing against an opponent (docs/design/opponent-prep.md).
pub prep: PrepSettings,
2026-11-03 00:03:51 +03:00
pub repertoire_flow_version: u8,
/// Last training mode and queue of each opening repertoire.
pub repertoire_modes: std::collections::HashMap<
String,
(
trainer::repertoire::TrainingMode,
trainer::repertoire::QueueMode,
),
>,
Opponent prep: the desktop screen (dialog, report, engine run) The «Prepare against…» entry points in the library (the filter panel's button when a player is set, the game row's context menu, Ctrl+Shift+P), the dialog (database, the player's spellings with the similar names apart, colour, book) and the report screen in the stack between the library and the game: the repertoire tree with transpositions, opening names, scores and the book column, the openings table by family and variation, the errors tab (repeated errors and by opening), the board of the chosen position with the line under it, and the games of the selection, which open in the game screen at that move with «⬅ Back to preparation». The engine run reuses the game analysis job over the distinct opening positions of the chosen colour: the launch dialog shares the engine picker and the quality/threads/memory grid with review.rs (quality «Fast» by default, its own setting), marks appear as positions are evaluated, «Stop» keeps what was done, the evaluations and the report are cached under <cache>/prep. One engine job per program: game analysis and the live engine are blocked meanwhile. Core: targets and counts by colour (`targets_for`, `missing_for`), the book step keeps its per-position counts (`book_counts`) for the tree column. Narrow windows: the board stacks over the lists under 804 px and folds into a button under 720 px of height; the right column is split explicitly (a nested bottom panel is not reserved from the content above it in egui). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 15:43:15 +03:00
}
/// Options of the opponent preparation; its engine search is the game analysis's.
Opponent prep: the desktop screen (dialog, report, engine run) The «Prepare against…» entry points in the library (the filter panel's button when a player is set, the game row's context menu, Ctrl+Shift+P), the dialog (database, the player's spellings with the similar names apart, colour, book) and the report screen in the stack between the library and the game: the repertoire tree with transpositions, opening names, scores and the book column, the openings table by family and variation, the errors tab (repeated errors and by opening), the board of the chosen position with the line under it, and the games of the selection, which open in the game screen at that move with «⬅ Back to preparation». The engine run reuses the game analysis job over the distinct opening positions of the chosen colour: the launch dialog shares the engine picker and the quality/threads/memory grid with review.rs (quality «Fast» by default, its own setting), marks appear as positions are evaluated, «Stop» keeps what was done, the evaluations and the report are cached under <cache>/prep. One engine job per program: game analysis and the live engine are blocked meanwhile. Core: targets and counts by colour (`targets_for`, `missing_for`), the book step keeps its per-position counts (`book_counts`) for the tree column. Narrow windows: the board stacks over the lists under 804 px and folds into a button under 720 px of height; the right column is split explicitly (a nested bottom panel is not reserved from the content above it in egui). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 15:43:15 +03:00
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct PrepSettings {
/// Unused legacy book choice, preserved when old settings are saved again.
Opponent prep: the desktop screen (dialog, report, engine run) The «Prepare against…» entry points in the library (the filter panel's button when a player is set, the game row's context menu, Ctrl+Shift+P), the dialog (database, the player's spellings with the similar names apart, colour, book) and the report screen in the stack between the library and the game: the repertoire tree with transpositions, opening names, scores and the book column, the openings table by family and variation, the errors tab (repeated errors and by opening), the board of the chosen position with the line under it, and the games of the selection, which open in the game screen at that move with «⬅ Back to preparation». The engine run reuses the game analysis job over the distinct opening positions of the chosen colour: the launch dialog shares the engine picker and the quality/threads/memory grid with review.rs (quality «Fast» by default, its own setting), marks appear as positions are evaluated, «Stop» keeps what was done, the evaluations and the report are cached under <cache>/prep. One engine job per program: game analysis and the live engine are blocked meanwhile. Core: targets and counts by colour (`targets_for`, `missing_for`), the book step keeps its per-position counts (`book_counts`) for the tree column. Narrow windows: the board stacks over the lists under 804 px and folds into a button under 720 px of height; the right column is split explicitly (a nested bottom panel is not reserved from the content above it in egui). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 15:43:15 +03:00
pub book: Option<PathBuf>,
/// Plies of the opening the report looks at.
pub plies: usize,
/// Which of the player's games.
pub period: prep::Period,
Opponent prep: the desktop screen (dialog, report, engine run) The «Prepare against…» entry points in the library (the filter panel's button when a player is set, the game row's context menu, Ctrl+Shift+P), the dialog (database, the player's spellings with the similar names apart, colour, book) and the report screen in the stack between the library and the game: the repertoire tree with transpositions, opening names, scores and the book column, the openings table by family and variation, the errors tab (repeated errors and by opening), the board of the chosen position with the line under it, and the games of the selection, which open in the game screen at that move with «⬅ Back to preparation». The engine run reuses the game analysis job over the distinct opening positions of the chosen colour: the launch dialog shares the engine picker and the quality/threads/memory grid with review.rs (quality «Fast» by default, its own setting), marks appear as positions are evaluated, «Stop» keeps what was done, the evaluations and the report are cached under <cache>/prep. One engine job per program: game analysis and the live engine are blocked meanwhile. Core: targets and counts by colour (`targets_for`, `missing_for`), the book step keeps its per-position counts (`book_counts`) for the tree column. Narrow windows: the board stacks over the lists under 804 px and folds into a button under 720 px of height; the right column is split explicitly (a nested bottom panel is not reserved from the content above it in egui). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 15:43:15 +03:00
/// Moves with fewer games fold into «other moves».
pub branches_from: u32,
Opponent prep: the tester's and designer's review Core: the most precise opening name stays down a line (a deeper position the table names more generally, «Sicilian Defense» after 3.d4, does not take it back), in the games' names and in the tree; one name per position across move orders; the games and the last date of a position over all its move orders; `evaluated()` (evaluations from the cache count). Report version 3. Screen: errors judged from cached evaluations show without a run; «Checked N of M positions · Continue» after «Stop» or a new depth; the report shows the book only when it was computed with the chosen one; the dialog keeps the remembered book and the same player reopens with the dialog's colour and book; «Deeper» and the depth list share one path (setting kept, report from the cache); a chosen error survives re-judging during the run; quitting during the run asks first; Ctrl+W returns from a game opened from the report; a game opened at an error opens after the move, a repeated error at its newest game. Design (§12): the summary as a grid whose columns give way, counts in the colours of the signs; result bars without numbers, faint over few games; move lines numbered at White's moves; whole-move first-move lines; colour icons in the openings table; ECO kept beside the name; the errors tab as one table with row selection and keys (↑/↓/→/←/Enter); colour lines there only in the stack; «Inaccuracies» switch (kept in settings) for the tab, the summary, the tree and the games; «▾» at the right end; one colour order; the depth caption by the room left; names first in narrow game lists; two-row games minimum in a low window; the caption beside the stacked board; «others (N)» when narrow. Designer's review recorded in docs/design/opponent-prep.md §12. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 16:21:16 +03:00
/// Inaccuracies (?!) are shown with the mistakes and blunders.
pub inaccuracies: bool,
/// The order of each table of the screen.
pub sorts: crate::prep_ui::PrepSorts,
Opponent prep: the desktop screen (dialog, report, engine run) The «Prepare against…» entry points in the library (the filter panel's button when a player is set, the game row's context menu, Ctrl+Shift+P), the dialog (database, the player's spellings with the similar names apart, colour, book) and the report screen in the stack between the library and the game: the repertoire tree with transpositions, opening names, scores and the book column, the openings table by family and variation, the errors tab (repeated errors and by opening), the board of the chosen position with the line under it, and the games of the selection, which open in the game screen at that move with «⬅ Back to preparation». The engine run reuses the game analysis job over the distinct opening positions of the chosen colour: the launch dialog shares the engine picker and the quality/threads/memory grid with review.rs (quality «Fast» by default, its own setting), marks appear as positions are evaluated, «Stop» keeps what was done, the evaluations and the report are cached under <cache>/prep. One engine job per program: game analysis and the live engine are blocked meanwhile. Core: targets and counts by colour (`targets_for`, `missing_for`), the book step keeps its per-position counts (`book_counts`) for the tree column. Narrow windows: the board stacks over the lists under 804 px and folds into a button under 720 px of height; the right column is split explicitly (a nested bottom panel is not reserved from the content above it in egui). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 15:43:15 +03:00
}
impl Default for PrepSettings {
fn default() -> Self {
Self {
book: None,
plies: 20,
period: prep::Period::All,
Opponent prep: the desktop screen (dialog, report, engine run) The «Prepare against…» entry points in the library (the filter panel's button when a player is set, the game row's context menu, Ctrl+Shift+P), the dialog (database, the player's spellings with the similar names apart, colour, book) and the report screen in the stack between the library and the game: the repertoire tree with transpositions, opening names, scores and the book column, the openings table by family and variation, the errors tab (repeated errors and by opening), the board of the chosen position with the line under it, and the games of the selection, which open in the game screen at that move with «⬅ Back to preparation». The engine run reuses the game analysis job over the distinct opening positions of the chosen colour: the launch dialog shares the engine picker and the quality/threads/memory grid with review.rs (quality «Fast» by default, its own setting), marks appear as positions are evaluated, «Stop» keeps what was done, the evaluations and the report are cached under <cache>/prep. One engine job per program: game analysis and the live engine are blocked meanwhile. Core: targets and counts by colour (`targets_for`, `missing_for`), the book step keeps its per-position counts (`book_counts`) for the tree column. Narrow windows: the board stacks over the lists under 804 px and folds into a button under 720 px of height; the right column is split explicitly (a nested bottom panel is not reserved from the content above it in egui). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 15:43:15 +03:00
branches_from: 3,
Opponent prep: the tester's and designer's review Core: the most precise opening name stays down a line (a deeper position the table names more generally, «Sicilian Defense» after 3.d4, does not take it back), in the games' names and in the tree; one name per position across move orders; the games and the last date of a position over all its move orders; `evaluated()` (evaluations from the cache count). Report version 3. Screen: errors judged from cached evaluations show without a run; «Checked N of M positions · Continue» after «Stop» or a new depth; the report shows the book only when it was computed with the chosen one; the dialog keeps the remembered book and the same player reopens with the dialog's colour and book; «Deeper» and the depth list share one path (setting kept, report from the cache); a chosen error survives re-judging during the run; quitting during the run asks first; Ctrl+W returns from a game opened from the report; a game opened at an error opens after the move, a repeated error at its newest game. Design (§12): the summary as a grid whose columns give way, counts in the colours of the signs; result bars without numbers, faint over few games; move lines numbered at White's moves; whole-move first-move lines; colour icons in the openings table; ECO kept beside the name; the errors tab as one table with row selection and keys (↑/↓/→/←/Enter); colour lines there only in the stack; «Inaccuracies» switch (kept in settings) for the tab, the summary, the tree and the games; «▾» at the right end; one colour order; the depth caption by the room left; names first in narrow game lists; two-row games minimum in a low window; the caption beside the stacked board; «others (N)» when narrow. Designer's review recorded in docs/design/opponent-prep.md §12. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 16:21:16 +03:00
inaccuracies: true,
sorts: Default::default(),
Opponent prep: the desktop screen (dialog, report, engine run) The «Prepare against…» entry points in the library (the filter panel's button when a player is set, the game row's context menu, Ctrl+Shift+P), the dialog (database, the player's spellings with the similar names apart, colour, book) and the report screen in the stack between the library and the game: the repertoire tree with transpositions, opening names, scores and the book column, the openings table by family and variation, the errors tab (repeated errors and by opening), the board of the chosen position with the line under it, and the games of the selection, which open in the game screen at that move with «⬅ Back to preparation». The engine run reuses the game analysis job over the distinct opening positions of the chosen colour: the launch dialog shares the engine picker and the quality/threads/memory grid with review.rs (quality «Fast» by default, its own setting), marks appear as positions are evaluated, «Stop» keeps what was done, the evaluations and the report are cached under <cache>/prep. One engine job per program: game analysis and the live engine are blocked meanwhile. Core: targets and counts by colour (`targets_for`, `missing_for`), the book step keeps its per-position counts (`book_counts`) for the tree column. Narrow windows: the board stacks over the lists under 804 px and folds into a button under 720 px of height; the right column is split explicitly (a nested bottom panel is not reserved from the content above it in egui). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 15:43:15 +03:00
}
}
}
impl Default for Settings {
fn default() -> Self {
Self {
piece_set: PieceSet::default(),
board_theme: BoardThemeId::default(),
show_coords: true,
animation: Animation::default(),
auto_queen: false,
move_notation: Default::default(),
translation: Default::default(),
sound_enabled: true,
sound_set: SoundSet::default(),
volume: 0.7,
dark_mode: true,
language: Lang::default(),
engines: Vec::new(),
active_engine: None,
show_best_arrow: true,
databases: Vec::new(),
engines_discovered: false,
examples_added: false,
check_updates: true,
skipped_version: None,
last_version: None,
install_id: String::new(),
reference_db: None,
your_name: String::new(),
new_database_dir: None,
last_target: None,
record_games: true,
players: Vec::new(),
rating: None,
play: Default::default(),
Opponent prep: the desktop screen (dialog, report, engine run) The «Prepare against…» entry points in the library (the filter panel's button when a player is set, the game row's context menu, Ctrl+Shift+P), the dialog (database, the player's spellings with the similar names apart, colour, book) and the report screen in the stack between the library and the game: the repertoire tree with transpositions, opening names, scores and the book column, the openings table by family and variation, the errors tab (repeated errors and by opening), the board of the chosen position with the line under it, and the games of the selection, which open in the game screen at that move with «⬅ Back to preparation». The engine run reuses the game analysis job over the distinct opening positions of the chosen colour: the launch dialog shares the engine picker and the quality/threads/memory grid with review.rs (quality «Fast» by default, its own setting), marks appear as positions are evaluated, «Stop» keeps what was done, the evaluations and the report are cached under <cache>/prep. One engine job per program: game analysis and the live engine are blocked meanwhile. Core: targets and counts by colour (`targets_for`, `missing_for`), the book step keeps its per-position counts (`book_counts`) for the tree column. Narrow windows: the board stacks over the lists under 804 px and folds into a button under 720 px of height; the right column is split explicitly (a nested bottom panel is not reserved from the content above it in egui). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 15:43:15 +03:00
prep: PrepSettings::default(),
2026-11-03 00:03:51 +03:00
repertoire_modes: Default::default(),
repertoire_flow_version: 0,
}
}
}
impl Settings {
2026-11-03 00:03:51 +03:00
pub fn migrate_repertoire_flow(&mut self) -> bool {
if self.repertoire_flow_version >= 1 {
return false;
}
for (_, queue) in self.repertoire_modes.values_mut() {
*queue = trainer::repertoire::QueueMode::Practice;
}
self.repertoire_flow_version = 1;
true
}
pub fn config_dir() -> Option<PathBuf> {
Web version, stage 1: the interface as a library over a platform layer; apps/web apps/desktop becomes a library (chesspenguin_app: the interface) and a thin binary; apps/web starts the same interface in a page's canvas (eframe's WebRunner). cfg(web) (build.rs) marks WebAssembly in a browser. The platform layer (apps/desktop/src/platform): the program's folders, files, background work, the files the user opens or saves, the clipboard and what the platform offers (CAPS). On a computer it is the system as before; in a browser the program's data lives in IndexedDB behind an in-memory file tree loaded before the start, the files the user opens are read into it for the session (only read), background jobs run on the page's thread after the frame, the clipboard is read through the browser's API, sounds play through audio elements, a game is saved as a download. What a browser does not have is not built for it: updates, the online games window and its probe, engine processes (analysis starts a Web Worker there; the review and preparation jobs, Rodent and the judge are native), blocking requests (engine, Maia and Rodent downloads report no download for the platform, translation reports that it makes no requests). The desktop program behaves as before; its build finds unused code (the web build compiles parts it never shows). apps/web: the entry point, the page /app/ (device check before anything large is loaded: phones and tablets get the page about the apps in the site's nine languages, keys app_* in website/site/i18n), build.sh (wasm-bindgen, profile web), a static server and headless Firefox checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:09:17 +03:00
crate::platform::config_dir()
}
/// `~/.cache/chesspenguin` (derived data that can be deleted at any time).
pub fn cache_dir() -> Option<PathBuf> {
Web version, stage 1: the interface as a library over a platform layer; apps/web apps/desktop becomes a library (chesspenguin_app: the interface) and a thin binary; apps/web starts the same interface in a page's canvas (eframe's WebRunner). cfg(web) (build.rs) marks WebAssembly in a browser. The platform layer (apps/desktop/src/platform): the program's folders, files, background work, the files the user opens or saves, the clipboard and what the platform offers (CAPS). On a computer it is the system as before; in a browser the program's data lives in IndexedDB behind an in-memory file tree loaded before the start, the files the user opens are read into it for the session (only read), background jobs run on the page's thread after the frame, the clipboard is read through the browser's API, sounds play through audio elements, a game is saved as a download. What a browser does not have is not built for it: updates, the online games window and its probe, engine processes (analysis starts a Web Worker there; the review and preparation jobs, Rodent and the judge are native), blocking requests (engine, Maia and Rodent downloads report no download for the platform, translation reports that it makes no requests). The desktop program behaves as before; its build finds unused code (the web build compiles parts it never shows). apps/web: the entry point, the page /app/ (device check before anything large is loaded: phones and tablets get the page about the apps in the site's nine languages, keys app_* in website/site/i18n), build.sh (wasm-bindgen, profile web), a static server and headless Firefox checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:09:17 +03:00
crate::platform::cache_dir()
}
fn file() -> Option<PathBuf> {
Self::config_dir().map(|d| d.join("settings.json"))
}
pub fn load() -> Self {
let Some(path) = Self::file() else {
return Self::first_start();
};
migrate_legacy_config(&path);
Web version, stage 1: the interface as a library over a platform layer; apps/web apps/desktop becomes a library (chesspenguin_app: the interface) and a thin binary; apps/web starts the same interface in a page's canvas (eframe's WebRunner). cfg(web) (build.rs) marks WebAssembly in a browser. The platform layer (apps/desktop/src/platform): the program's folders, files, background work, the files the user opens or saves, the clipboard and what the platform offers (CAPS). On a computer it is the system as before; in a browser the program's data lives in IndexedDB behind an in-memory file tree loaded before the start, the files the user opens are read into it for the session (only read), background jobs run on the page's thread after the frame, the clipboard is read through the browser's API, sounds play through audio elements, a game is saved as a download. What a browser does not have is not built for it: updates, the online games window and its probe, engine processes (analysis starts a Web Worker there; the review and preparation jobs, Rodent and the judge are native), blocking requests (engine, Maia and Rodent downloads report no download for the platform, translation reports that it makes no requests). The desktop program behaves as before; its build finds unused code (the web build compiles parts it never shows). apps/web: the entry point, the page /app/ (device check before anything large is loaded: phones and tablets get the page about the apps in the site's nine languages, keys app_* in website/site/i18n), build.sh (wasm-bindgen, profile web), a static server and headless Firefox checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:09:17 +03:00
match crate::platform::fs::read(&path) {
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
eprintln!(
"settings: cannot parse {}: {e}; using defaults",
path.display()
);
Self::default()
}),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::first_start(),
Err(_) => Self::default(),
}
}
/// Settings of the very first start: the defaults in the system's language (if it
/// is one of ours, otherwise English).
fn first_start() -> Self {
Self {
language: Lang::system(),
..Self::default()
}
}
pub fn save(&self) -> std::io::Result<()> {
let Some(path) = Self::file() else {
return Ok(());
};
let json = serde_json::to_vec_pretty(self).map_err(std::io::Error::other)?;
write_atomic(&path, &json)
}
pub fn active_engine(&self) -> Option<&EngineConfig> {
self.active_engine.and_then(|i| self.engines.get(i))
}
/// Puts the database first on the shelf; a database there already by another path
/// to the same file (a link) keeps its path. Returns the path on the shelf.
pub fn touch_database(&mut self, path: &Path) -> PathBuf {
let real = |p: &Path| std::fs::canonicalize(p).ok();
let same = |p: &PathBuf| p == path || real(p).is_some_and(|r| Some(r) == real(path));
let kept = match self.databases.iter().position(same) {
Some(i) => self.databases.remove(i),
None => path.to_path_buf(),
};
self.databases.insert(0, kept.clone());
kept
}
}
/// Copies settings of the pre-rename build (`chessbase-linux`) once, if the new file is absent.
fn migrate_legacy_config(new_file: &Path) {
Web version, stage 1: the interface as a library over a platform layer; apps/web apps/desktop becomes a library (chesspenguin_app: the interface) and a thin binary; apps/web starts the same interface in a page's canvas (eframe's WebRunner). cfg(web) (build.rs) marks WebAssembly in a browser. The platform layer (apps/desktop/src/platform): the program's folders, files, background work, the files the user opens or saves, the clipboard and what the platform offers (CAPS). On a computer it is the system as before; in a browser the program's data lives in IndexedDB behind an in-memory file tree loaded before the start, the files the user opens are read into it for the session (only read), background jobs run on the page's thread after the frame, the clipboard is read through the browser's API, sounds play through audio elements, a game is saved as a download. What a browser does not have is not built for it: updates, the online games window and its probe, engine processes (analysis starts a Web Worker there; the review and preparation jobs, Rodent and the judge are native), blocking requests (engine, Maia and Rodent downloads report no download for the platform, translation reports that it makes no requests). The desktop program behaves as before; its build finds unused code (the web build compiles parts it never shows). apps/web: the entry point, the page /app/ (device check before anything large is loaded: phones and tablets get the page about the apps in the site's nine languages, keys app_* in website/site/i18n), build.sh (wasm-bindgen, profile web), a static server and headless Firefox checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:09:17 +03:00
if crate::platform::fs::exists(new_file) {
return;
}
let legacy = directories::ProjectDirs::from("org", "chessbase-linux", "chessbase-linux")
.map(|d| d.config_dir().join("settings.json"));
if let Some(old) = legacy.filter(|p| p.is_file())
&& let Ok(bytes) = std::fs::read(&old)
{
let _ = write_atomic(new_file, &bytes);
}
}
/// Writes via a temp file in the same directory and renames over the target.
pub fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
Web version, stage 1: the interface as a library over a platform layer; apps/web apps/desktop becomes a library (chesspenguin_app: the interface) and a thin binary; apps/web starts the same interface in a page's canvas (eframe's WebRunner). cfg(web) (build.rs) marks WebAssembly in a browser. The platform layer (apps/desktop/src/platform): the program's folders, files, background work, the files the user opens or saves, the clipboard and what the platform offers (CAPS). On a computer it is the system as before; in a browser the program's data lives in IndexedDB behind an in-memory file tree loaded before the start, the files the user opens are read into it for the session (only read), background jobs run on the page's thread after the frame, the clipboard is read through the browser's API, sounds play through audio elements, a game is saved as a download. What a browser does not have is not built for it: updates, the online games window and its probe, engine processes (analysis starts a Web Worker there; the review and preparation jobs, Rodent and the judge are native), blocking requests (engine, Maia and Rodent downloads report no download for the platform, translation reports that it makes no requests). The desktop program behaves as before; its build finds unused code (the web build compiles parts it never shows). apps/web: the entry point, the page /app/ (device check before anything large is loaded: phones and tablets get the page about the apps in the site's nine languages, keys app_* in website/site/i18n), build.sh (wasm-bindgen, profile web), a static server and headless Firefox checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:09:17 +03:00
crate::platform::fs::write_atomic(path, bytes)
}
#[cfg(test)]
mod tests {
use super::*;
/// A database put on the shelf again by a link to its file stays itself, once.
#[cfg(unix)]
#[test]
fn a_link_to_a_database_on_the_shelf_does_not_add_it_twice() {
let dir = std::env::temp_dir().join(format!("cp-shelf-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let (base, other, link) = (dir.join("a.pgn"), dir.join("b.pgn"), dir.join("link.pgn"));
std::fs::write(&base, "").unwrap();
std::fs::write(&other, "").unwrap();
std::os::unix::fs::symlink(&base, &link).unwrap();
let mut s = Settings::default();
s.databases.clear();
assert_eq!(s.touch_database(&base), base);
assert_eq!(s.touch_database(&other), other);
assert_eq!(s.touch_database(&link), base);
assert_eq!(s.databases, vec![base.clone(), other.clone()]);
// A database gone from the disk is still told by its path.
let gone = dir.join("gone.pgn");
s.touch_database(&gone);
assert_eq!(s.touch_database(&gone), gone);
assert_eq!(s.databases.len(), 3);
let _ = std::fs::remove_dir_all(&dir);
}
/// The settings of 1.x kept the engine options of the game analysis and the
/// quality of the preparation: they are read without them now.
#[test]
fn settings_with_the_old_analysis_options_are_read() {
let old = r#"{
"language": "Ru",
"review": {"quality": 2, "threads": 12, "hash_mb": 1024, "chosen": true},
"prep": {"quality": 1, "plies": 16, "chosen": true, "book": "/db/book.pgn"}
}"#;
let s: Settings = serde_json::from_str(old).expect("read");
assert_eq!(s.language, Lang::Ru);
assert_eq!(s.prep.plies, 16);
assert_eq!(s.prep.book, Some(PathBuf::from("/db/book.pgn")));
let json = serde_json::to_string(&s).expect("written");
assert!(!json.contains("\"review\"") && !json.contains("quality"));
assert!(!json.contains("\"chosen\""));
assert!(json.contains("\"book\":\"/db/book.pgn\""));
}
}
2026-11-03 00:03:51 +03:00
#[cfg(test)]
mod repertoire_flow_tests {
use super::*;
use trainer::repertoire::{QueueMode, TrainingMode};
#[test]
fn old_training_preferences_migrate_once_without_resetting_color_or_custom_settings() {
let mut settings = Settings::default();
settings.repertoire_modes.insert(
"old".into(),
(TrainingMode::Black, QueueMode::SpacedRepetition),
);
assert!(settings.migrate_repertoire_flow());
assert_eq!(
settings.repertoire_modes["old"],
(TrainingMode::Black, QueueMode::Practice)
);
settings.repertoire_modes.get_mut("old").unwrap().1 = QueueMode::SpacedRepetition;
assert!(!settings.migrate_repertoire_flow());
assert_eq!(
settings.repertoire_modes["old"].1,
QueueMode::SpacedRepetition
);
}
}