ChessPenguin 0.1.0
Native chess database for Linux: PGN library, notation with variations and comments, UCI engine analysis, move entry and export. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
8188b584aa
296 changed files with 22048 additions and 0 deletions
363
apps/desktop/src/analysis.rs
Normal file
363
apps/desktop/src/analysis.rs
Normal file
|
|
@ -0,0 +1,363 @@
|
|||
//! Engine analysis controller: owns the UCI process, binds results to the analysed position.
|
||||
|
||||
use crate::i18n::{tr, trf};
|
||||
use std::sync::mpsc::{Receiver, channel};
|
||||
|
||||
use shakmaty::san::SanPlus;
|
||||
use shakmaty::uci::UciMove;
|
||||
use shakmaty::{Chess, Color, Move, Position};
|
||||
use uci::{
|
||||
EngineEvent, EngineHandle, EnginePosition, SearchId, SearchInfo, SearchLimits, Side,
|
||||
TerminationReason, WhiteEval, WhiteScore,
|
||||
};
|
||||
|
||||
use crate::settings::EngineConfig;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PvLine {
|
||||
pub multipv: u32,
|
||||
pub depth: u32,
|
||||
pub score: WhiteScore,
|
||||
/// Legal moves of the PV from the analysed position (stops at the first illegal move).
|
||||
pub moves: Vec<Move>,
|
||||
pub san: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Status {
|
||||
Off,
|
||||
Starting,
|
||||
Running,
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
/// A position the engine is (or should be) analysing.
|
||||
struct Target {
|
||||
key: String,
|
||||
root: Chess,
|
||||
engine_pos: EnginePosition,
|
||||
}
|
||||
|
||||
pub struct Analysis {
|
||||
engine: Option<EngineHandle>,
|
||||
spawning: Option<Receiver<Result<EngineHandle, uci::EngineError>>>,
|
||||
pub status: Status,
|
||||
pub engine_name: String,
|
||||
next_id: u64,
|
||||
current: Option<(SearchId, Target)>,
|
||||
/// Requested while the engine is still starting.
|
||||
queued: Option<Target>,
|
||||
pub lines: Vec<PvLine>,
|
||||
pub nodes: u64,
|
||||
pub nps: u64,
|
||||
multipv: u32,
|
||||
/// Search time per position; `None` = infinite analysis.
|
||||
limit: Option<u32>,
|
||||
/// The current search ended (time limit reached); lines stay as the final result.
|
||||
pub finished: bool,
|
||||
/// Executable of the running engine (to detect a switch of the active engine).
|
||||
pub engine_path: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
impl Analysis {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
engine: None,
|
||||
spawning: None,
|
||||
status: Status::Off,
|
||||
engine_name: String::new(),
|
||||
next_id: 1,
|
||||
current: None,
|
||||
queued: None,
|
||||
lines: Vec::new(),
|
||||
nodes: 0,
|
||||
nps: 0,
|
||||
multipv: 1,
|
||||
limit: None,
|
||||
finished: false,
|
||||
engine_path: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_on(&self) -> bool {
|
||||
matches!(self.status, Status::Starting | Status::Running)
|
||||
}
|
||||
|
||||
/// Starts the engine in a background thread (handshake blocks for up to ~20 s).
|
||||
pub fn start(&mut self, cfg: &EngineConfig, ctx: &egui::Context) {
|
||||
self.stop();
|
||||
let (tx, rx) = channel();
|
||||
let ctx_w = ctx.clone();
|
||||
let ctx_done = ctx.clone();
|
||||
let cfg = cfg.clone();
|
||||
self.engine_name = cfg.name.clone();
|
||||
self.multipv = cfg.multipv.max(1);
|
||||
self.limit = cfg.search_secs;
|
||||
self.engine_path = Some(cfg.path.clone());
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("engine-spawn".into())
|
||||
.spawn(move || {
|
||||
let res = uci::Engine::spawn_with(
|
||||
uci::EngineConfig::new(&cfg.path),
|
||||
Box::new(move || ctx_w.request_repaint()),
|
||||
)
|
||||
.inspect(|h| {
|
||||
// Unknown options are not fatal: some engines lack Threads/Hash/MultiPV.
|
||||
let _ = h.set_threads(cfg.threads);
|
||||
let _ = h.set_hash_mb(cfg.hash_mb);
|
||||
let _ = h.set_multipv(cfg.multipv.max(1));
|
||||
});
|
||||
let _ = tx.send(res);
|
||||
ctx_done.request_repaint();
|
||||
});
|
||||
match spawned {
|
||||
Ok(_) => {
|
||||
self.spawning = Some(rx);
|
||||
self.status = Status::Starting;
|
||||
}
|
||||
Err(e) => self.status = Status::Failed(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops analysis and terminates the engine process.
|
||||
pub fn stop(&mut self) {
|
||||
if let Some(e) = self.engine.take() {
|
||||
// quit() may wait up to the quit timeout; do it off the UI thread.
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("engine-quit".into())
|
||||
.spawn(move || {
|
||||
e.quit();
|
||||
});
|
||||
}
|
||||
self.spawning = None;
|
||||
self.current = None;
|
||||
self.queued = None;
|
||||
self.lines.clear();
|
||||
self.engine_path = None;
|
||||
self.status = Status::Off;
|
||||
}
|
||||
|
||||
/// Applies Threads/Hash/MultiPV/time of the running engine and restarts the current search.
|
||||
pub fn reconfigure(&mut self, cfg: &EngineConfig, ctx: &egui::Context) {
|
||||
if self.engine_path.as_deref() != Some(cfg.path.as_path()) || self.spawning.is_some() {
|
||||
self.start(cfg, ctx);
|
||||
return;
|
||||
}
|
||||
let Some(engine) = &self.engine else { return };
|
||||
let _ = engine.set_threads(cfg.threads);
|
||||
let _ = engine.set_hash_mb(cfg.hash_mb);
|
||||
let _ = engine.set_multipv(cfg.multipv.max(1));
|
||||
self.multipv = cfg.multipv.max(1);
|
||||
self.limit = cfg.search_secs;
|
||||
if let Some((_, t)) = self.current.take() {
|
||||
self.set_position(&t.root, t.engine_pos);
|
||||
}
|
||||
}
|
||||
|
||||
/// Requests analysis of `root`; no-op if that exact history is already being analysed.
|
||||
pub fn set_position(&mut self, root: &Chess, engine_pos: EnginePosition) {
|
||||
if !self.is_on() {
|
||||
return;
|
||||
}
|
||||
let key = format!("{:?}|{}", engine_pos.base, engine_pos.moves.join(" "));
|
||||
if self.current.as_ref().is_some_and(|(_, t)| t.key == key) {
|
||||
return;
|
||||
}
|
||||
if self.queued.as_ref().is_some_and(|t| t.key == key) {
|
||||
return;
|
||||
}
|
||||
let target = Target {
|
||||
key,
|
||||
root: root.clone(),
|
||||
engine_pos,
|
||||
};
|
||||
self.lines.clear();
|
||||
self.nodes = 0;
|
||||
self.nps = 0;
|
||||
self.finished = false;
|
||||
let Some(engine) = &self.engine else {
|
||||
self.queued = Some(target);
|
||||
return;
|
||||
};
|
||||
let id = SearchId(self.next_id);
|
||||
self.next_id += 1;
|
||||
let res = match self.limit {
|
||||
None => engine.analyze(target.engine_pos.clone(), id),
|
||||
Some(secs) => engine.search(
|
||||
target.engine_pos.clone(),
|
||||
id,
|
||||
SearchLimits::MoveTime(std::time::Duration::from_secs(u64::from(secs))),
|
||||
),
|
||||
};
|
||||
match res {
|
||||
Ok(()) => self.current = Some((id, target)),
|
||||
Err(e) => {
|
||||
self.current = None;
|
||||
self.status = Status::Failed(e.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Drains engine events; call once per frame.
|
||||
pub fn poll(&mut self) {
|
||||
if let Some(rx) = &self.spawning
|
||||
&& let Ok(res) = rx.try_recv()
|
||||
{
|
||||
self.spawning = None;
|
||||
match res {
|
||||
Ok(h) => {
|
||||
if let Some(name) = &h.info().name {
|
||||
self.engine_name = name.clone();
|
||||
}
|
||||
self.engine = Some(h);
|
||||
self.status = Status::Running;
|
||||
if let Some(t) = self.queued.take() {
|
||||
let (root, pos) = (t.root, t.engine_pos);
|
||||
self.set_position(&root, pos);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
self.lines.clear();
|
||||
self.status = Status::Failed(e.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(engine) = &self.engine else { return };
|
||||
let events: Vec<EngineEvent> = engine.drain_events().collect();
|
||||
for ev in events {
|
||||
match ev {
|
||||
EngineEvent::Info { search_id, info } => {
|
||||
if let Some((id, target)) = &self.current
|
||||
&& *id == search_id
|
||||
{
|
||||
let side = side(target.root.turn());
|
||||
if let Some(line) = make_line(&target.root, side, &info) {
|
||||
self.nodes = info.nodes.unwrap_or(self.nodes);
|
||||
self.nps = info.nps.unwrap_or(self.nps);
|
||||
upsert(&mut self.lines, line, self.multipv);
|
||||
}
|
||||
}
|
||||
}
|
||||
EngineEvent::BestMove { search_id, .. } => {
|
||||
if self
|
||||
.current
|
||||
.as_ref()
|
||||
.is_some_and(|(id, _)| *id == search_id)
|
||||
{
|
||||
self.finished = true;
|
||||
}
|
||||
}
|
||||
EngineEvent::Terminated(reason) => {
|
||||
self.engine = None;
|
||||
self.current = None;
|
||||
self.lines.clear();
|
||||
self.status = Status::Failed(match reason {
|
||||
TerminationReason::Hung { .. } => {
|
||||
tr("The engine hung and was stopped").into()
|
||||
}
|
||||
TerminationReason::Exited { status }
|
||||
| TerminationReason::Quit { status } => match status {
|
||||
Some(s) => trf("The engine exited ({s})", &[("s", &s)]),
|
||||
None => tr("The engine exited").into(),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Best line of the current search, already bound to the position it was computed for.
|
||||
pub fn best(&self) -> Option<&PvLine> {
|
||||
if self.status == Status::Running {
|
||||
self.lines.first()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Analysis {
|
||||
fn drop(&mut self) {
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
fn side(c: Color) -> Side {
|
||||
match c {
|
||||
Color::White => Side::White,
|
||||
Color::Black => Side::Black,
|
||||
}
|
||||
}
|
||||
|
||||
fn make_line(root: &Chess, side: Side, info: &SearchInfo) -> Option<PvLine> {
|
||||
let score = info.score?.to_white(side);
|
||||
if info.pv.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut pos = root.clone();
|
||||
let mut moves = Vec::new();
|
||||
let mut san = Vec::new();
|
||||
for u in &info.pv {
|
||||
let Ok(m) = u
|
||||
.parse::<UciMove>()
|
||||
.map_err(|_| ())
|
||||
.and_then(|um| um.to_move(&pos).map_err(|_| ()))
|
||||
else {
|
||||
break;
|
||||
};
|
||||
san.push(SanPlus::from_move_and_play_unchecked(&mut pos, m).to_string());
|
||||
moves.push(m);
|
||||
}
|
||||
if moves.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(PvLine {
|
||||
multipv: info.multipv_index(),
|
||||
depth: info.depth.unwrap_or(0),
|
||||
score,
|
||||
moves,
|
||||
san,
|
||||
})
|
||||
}
|
||||
|
||||
fn upsert(lines: &mut Vec<PvLine>, line: PvLine, multipv: u32) {
|
||||
if line.multipv > multipv {
|
||||
return;
|
||||
}
|
||||
match lines.iter_mut().find(|l| l.multipv == line.multipv) {
|
||||
Some(l) => *l = line,
|
||||
None => lines.push(line),
|
||||
}
|
||||
lines.sort_by_key(|l| l.multipv);
|
||||
}
|
||||
|
||||
/// "+0.35", "-1.20", "#3", "#-2" from White's point of view.
|
||||
pub fn format_eval(s: &WhiteScore) -> String {
|
||||
match s.eval {
|
||||
WhiteEval::Cp(cp) => format!("{:+.2}", cp as f32 / 100.0),
|
||||
WhiteEval::Mate { winner, moves } => match winner {
|
||||
Side::White => format!("#{moves}"),
|
||||
Side::Black => format!("#-{moves}"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluation squashed into 0..1 for the eval bar (1 = White winning).
|
||||
pub fn bar_fraction(s: &WhiteScore) -> f32 {
|
||||
match s.eval {
|
||||
WhiteEval::Cp(cp) => {
|
||||
let x = cp as f32 / 100.0;
|
||||
0.5 + 0.5 * (2.0 / (1.0 + (-0.37 * x).exp()) - 1.0)
|
||||
}
|
||||
WhiteEval::Mate {
|
||||
winner: Side::White,
|
||||
..
|
||||
} => 1.0,
|
||||
WhiteEval::Mate {
|
||||
winner: Side::Black,
|
||||
..
|
||||
} => 0.0,
|
||||
}
|
||||
}
|
||||
646
apps/desktop/src/app.rs
Normal file
646
apps/desktop/src/app.rs
Normal file
|
|
@ -0,0 +1,646 @@
|
|||
//! Top-level application state: library ⇄ game, settings, engine, background dialogs.
|
||||
|
||||
use crate::i18n::{tr, trf};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use chess_core::{Game, PgnDatabase, TextEncoding};
|
||||
use egui::{Key, KeyboardShortcut, Modifiers, RichText};
|
||||
|
||||
use crate::analysis::Analysis;
|
||||
use crate::assets::Sound;
|
||||
use crate::game_view::{GameAction, GameSource, GameView};
|
||||
use crate::library::{Library, LibraryAction};
|
||||
use crate::settings::{EngineConfig, Settings, write_atomic};
|
||||
use crate::settings_ui::{SettingsAction, SettingsWindow, Tab};
|
||||
use crate::sound::SoundPlayer;
|
||||
|
||||
/// Results of work done off the UI thread (file dialogs, engine checks).
|
||||
enum Async {
|
||||
DatabasesPicked(Vec<PathBuf>),
|
||||
SavePicked(PathBuf),
|
||||
SaveCancelled,
|
||||
EngineChecked(Result<(PathBuf, String), String>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum CloseIntent {
|
||||
BackToLibrary,
|
||||
QuitApp,
|
||||
}
|
||||
|
||||
pub struct App {
|
||||
settings: Settings,
|
||||
settings_dirty: bool,
|
||||
sound: SoundPlayer,
|
||||
library: Library,
|
||||
game: Option<GameView>,
|
||||
analysis: Analysis,
|
||||
settings_ui: SettingsWindow,
|
||||
toast: Option<(String, f64)>,
|
||||
tx: Sender<Async>,
|
||||
rx: Receiver<Async>,
|
||||
confirm_close: Option<CloseIntent>,
|
||||
/// Close the game once the pending "save as" succeeds.
|
||||
close_after_save: Option<CloseIntent>,
|
||||
allow_quit: bool,
|
||||
applied_dark: Option<bool>,
|
||||
debug: DebugStartup,
|
||||
}
|
||||
|
||||
/// Dev-only startup automation for screenshots/manual QA (see docs/dev/desktop.md):
|
||||
/// `CP_OPEN=<game index>` opens a game from the first database, `CP_PLY=<n>` steps
|
||||
/// along the main line, `CP_ANALYZE=1` starts the engine, `CP_SETTINGS=1` opens settings.
|
||||
#[derive(Default)]
|
||||
struct DebugStartup {
|
||||
open: Option<usize>,
|
||||
ply: usize,
|
||||
analyze: bool,
|
||||
/// `CP_SCREENSHOT=<file.png>`: go fullscreen, wait `CP_SCREENSHOT_DELAY` seconds,
|
||||
/// save the window contents and quit (README screenshots without desktop overlays).
|
||||
screenshot: Option<PathBuf>,
|
||||
screenshot_delay: f64,
|
||||
screenshot_requested: bool,
|
||||
open_settings: bool,
|
||||
}
|
||||
|
||||
impl DebugStartup {
|
||||
fn from_env() -> Self {
|
||||
let num = |k| std::env::var(k).ok().and_then(|v| v.parse::<usize>().ok());
|
||||
Self {
|
||||
open: num("CP_OPEN"),
|
||||
ply: num("CP_PLY").unwrap_or(0),
|
||||
analyze: std::env::var("CP_ANALYZE").is_ok(),
|
||||
screenshot: std::env::var_os("CP_SCREENSHOT").map(PathBuf::from),
|
||||
screenshot_delay: std::env::var("CP_SCREENSHOT_DELAY")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(4.0),
|
||||
screenshot_requested: false,
|
||||
open_settings: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new(ctx: &egui::Context) -> Self {
|
||||
let mut settings = Settings::load();
|
||||
crate::i18n::set_lang(settings.language);
|
||||
// PGN files passed on the command line (e.g. "Open with…") join the library, first one selected.
|
||||
let args: Vec<PathBuf> = std::env::args_os()
|
||||
.skip(1)
|
||||
.map(PathBuf::from)
|
||||
.filter(|p| p.is_file())
|
||||
.collect();
|
||||
for p in args.iter().rev() {
|
||||
let p = p.canonicalize().unwrap_or_else(|_| p.clone());
|
||||
settings.touch_database(&p);
|
||||
}
|
||||
if !args.is_empty() {
|
||||
let _ = settings.save();
|
||||
}
|
||||
let (tx, rx) = channel();
|
||||
let mut library = Library::new();
|
||||
if let Some(first) = settings.databases.first().filter(|p| p.exists()) {
|
||||
library.select_db(first, ctx);
|
||||
}
|
||||
Self {
|
||||
settings,
|
||||
settings_dirty: false,
|
||||
sound: SoundPlayer::new(),
|
||||
library,
|
||||
game: None,
|
||||
analysis: Analysis::new(),
|
||||
settings_ui: SettingsWindow::new(),
|
||||
toast: None,
|
||||
tx,
|
||||
rx,
|
||||
confirm_close: None,
|
||||
close_after_save: None,
|
||||
allow_quit: false,
|
||||
applied_dark: None,
|
||||
debug: DebugStartup::from_env(),
|
||||
}
|
||||
.with_debug_settings()
|
||||
}
|
||||
|
||||
fn with_debug_settings(mut self) -> Self {
|
||||
if let Ok(tab) = std::env::var("CP_SETTINGS") {
|
||||
// Opened after a short delay (see debug_screenshot) so a fullscreen switch is done first.
|
||||
self.debug.open_settings = true;
|
||||
if tab == "board" {
|
||||
self.settings_ui.tab = Tab::Board;
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
fn debug_screenshot(&mut self, ctx: &egui::Context) {
|
||||
if self.debug.open_settings && ctx.input(|i| i.time) > 1.5 {
|
||||
self.debug.open_settings = false;
|
||||
self.settings_ui.open = true;
|
||||
}
|
||||
let Some(path) = self.debug.screenshot.clone() else {
|
||||
return;
|
||||
};
|
||||
let now = ctx.input(|i| i.time);
|
||||
if !self.debug.screenshot_requested {
|
||||
if ctx.cumulative_frame_nr() == 1 {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(true));
|
||||
}
|
||||
if now >= self.debug.screenshot_delay {
|
||||
self.debug.screenshot_requested = true;
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(Default::default()));
|
||||
}
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(100));
|
||||
return;
|
||||
}
|
||||
let shot = ctx.input(|i| {
|
||||
i.raw.events.iter().find_map(|e| match e {
|
||||
egui::Event::Screenshot { image, .. } => Some(image.clone()),
|
||||
_ => None,
|
||||
})
|
||||
});
|
||||
if let Some(img) = shot {
|
||||
let [w, h] = img.size;
|
||||
let bytes: Vec<u8> = img.pixels.iter().flat_map(|c| c.to_array()).collect();
|
||||
if let Err(e) =
|
||||
image::save_buffer(&path, &bytes, w as u32, h as u32, image::ColorType::Rgba8)
|
||||
{
|
||||
eprintln!("screenshot: {e}");
|
||||
}
|
||||
self.allow_quit = true;
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
}
|
||||
|
||||
fn debug_step(&mut self, ctx: &egui::Context) {
|
||||
let Some(index) = self.debug.open else { return };
|
||||
let Some(path) = self.settings.databases.first().cloned() else {
|
||||
return;
|
||||
};
|
||||
if self.library.database(&path).is_none() {
|
||||
return;
|
||||
}
|
||||
self.debug.open = None;
|
||||
self.open_game(ctx, path, index);
|
||||
if let Some(g) = &mut self.game {
|
||||
g.debug_advance(self.debug.ply);
|
||||
if std::env::var("CP_ENGINE_PANEL").is_ok() {
|
||||
g.debug_open_engine_settings();
|
||||
}
|
||||
}
|
||||
if self.debug.analyze {
|
||||
self.toggle_engine(ctx);
|
||||
}
|
||||
}
|
||||
|
||||
fn toast(&mut self, ctx: &egui::Context, msg: impl Into<String>) {
|
||||
self.toast = Some((msg.into(), ctx.input(|i| i.time) + 3.5));
|
||||
}
|
||||
|
||||
fn play(&self, s: Sound) {
|
||||
if self.settings.sound_enabled {
|
||||
self.sound
|
||||
.play(self.settings.sound_set, s, self.settings.volume);
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_dialog(
|
||||
&self,
|
||||
ctx: &egui::Context,
|
||||
f: impl FnOnce() -> Option<Async> + Send + 'static,
|
||||
) {
|
||||
let tx = self.tx.clone();
|
||||
let ctx = ctx.clone();
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("dialog".into())
|
||||
.spawn(move || {
|
||||
if let Some(r) = f() {
|
||||
let _ = tx.send(r);
|
||||
}
|
||||
ctx.request_repaint();
|
||||
});
|
||||
}
|
||||
|
||||
fn pick_databases(&self, ctx: &egui::Context) {
|
||||
self.spawn_dialog(ctx, || {
|
||||
rfd::FileDialog::new()
|
||||
.set_title(tr("Open PGN"))
|
||||
.add_filter("PGN", &["pgn", "PGN"])
|
||||
.add_filter(tr("All files"), &["*"])
|
||||
.pick_files()
|
||||
.map(Async::DatabasesPicked)
|
||||
});
|
||||
}
|
||||
|
||||
fn pick_save(&self, ctx: &egui::Context) {
|
||||
let Some(g) = &self.game else { return };
|
||||
let name = sanitize(&g.title()) + ".pgn";
|
||||
self.spawn_dialog(ctx, move || {
|
||||
rfd::FileDialog::new()
|
||||
.set_title(tr("Save game"))
|
||||
.set_file_name(name)
|
||||
.add_filter("PGN", &["pgn"])
|
||||
.save_file()
|
||||
.map_or(Some(Async::SaveCancelled), |p| Some(Async::SavePicked(p)))
|
||||
});
|
||||
}
|
||||
|
||||
fn pick_engine(&mut self, ctx: &egui::Context) {
|
||||
self.settings_ui.checking_engine = true;
|
||||
let tx = self.tx.clone();
|
||||
let ctx2 = ctx.clone();
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("engine-check".into())
|
||||
.spawn(move || {
|
||||
let Some(path) = rfd::FileDialog::new()
|
||||
.set_title(tr("Choose the UCI engine executable"))
|
||||
.pick_file()
|
||||
else {
|
||||
let _ = tx.send(Async::EngineChecked(Err(String::new())));
|
||||
ctx2.request_repaint();
|
||||
return;
|
||||
};
|
||||
let res = uci::Engine::spawn(&path, std::iter::empty::<&str>(), Box::new(|| {}))
|
||||
.map(|h| {
|
||||
let name = h.info().name.clone().unwrap_or_else(|| {
|
||||
path.file_name()
|
||||
.map(|s| s.to_string_lossy().into_owned())
|
||||
.unwrap_or_default()
|
||||
});
|
||||
h.quit();
|
||||
(path.clone(), name)
|
||||
})
|
||||
.map_err(|e| format!("{}: {e}", path.display()));
|
||||
let _ = tx.send(Async::EngineChecked(res));
|
||||
ctx2.request_repaint();
|
||||
});
|
||||
}
|
||||
|
||||
fn handle_async(&mut self, ctx: &egui::Context) {
|
||||
while let Ok(msg) = self.rx.try_recv() {
|
||||
match msg {
|
||||
Async::DatabasesPicked(paths) => {
|
||||
for p in paths.iter().rev() {
|
||||
self.settings.touch_database(p);
|
||||
}
|
||||
if let Some(first) = paths.first() {
|
||||
self.library.select_db(first, ctx);
|
||||
}
|
||||
self.settings_dirty = true;
|
||||
}
|
||||
Async::SavePicked(path) => self.save_game(ctx, path),
|
||||
Async::SaveCancelled => self.close_after_save = None,
|
||||
Async::EngineChecked(res) => {
|
||||
self.settings_ui.checking_engine = false;
|
||||
match res {
|
||||
Ok((path, name)) => {
|
||||
self.settings
|
||||
.engines
|
||||
.push(EngineConfig::new(name.clone(), path));
|
||||
if self.settings.active_engine.is_none() {
|
||||
self.settings.active_engine = Some(self.settings.engines.len() - 1);
|
||||
}
|
||||
self.settings_dirty = true;
|
||||
self.toast(ctx, trf("Engine “{name}” added", &[("name", &name)]));
|
||||
}
|
||||
Err(e) if e.is_empty() => {}
|
||||
Err(e) => self.toast(
|
||||
ctx,
|
||||
trf("Not a UCI engine or it failed to start: {e}", &[("e", &e)]),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn save_game(&mut self, ctx: &egui::Context, path: PathBuf) {
|
||||
// Never replace a source database with a single game (explicit invariant).
|
||||
let same = |a: &std::path::Path| match (a.canonicalize(), path.canonicalize()) {
|
||||
(Ok(x), Ok(y)) => x == y,
|
||||
_ => a == path,
|
||||
};
|
||||
let is_source = self
|
||||
.game
|
||||
.as_ref()
|
||||
.and_then(|g| g.source.as_ref())
|
||||
.is_some_and(|s| same(&s.path));
|
||||
if is_source || self.settings.databases.iter().any(|d| same(d)) {
|
||||
self.close_after_save = None;
|
||||
self.toast(
|
||||
ctx,
|
||||
tr("An open database cannot be overwritten with a single game — choose another file"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
let Some(g) = &mut self.game else { return };
|
||||
let pgn = g.game.to_pgn();
|
||||
match write_atomic(&path, pgn.as_bytes()) {
|
||||
Ok(()) => {
|
||||
g.game.mark_saved();
|
||||
self.toast(ctx, trf("Saved: {path}", &[("path", &path.display())]));
|
||||
if let Some(intent) = self.close_after_save.take() {
|
||||
self.finish_close(ctx, intent);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
self.close_after_save = None;
|
||||
self.toast(ctx, trf("Save failed: {e}", &[("e", &e)]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn open_game(&mut self, ctx: &egui::Context, path: PathBuf, index: usize) {
|
||||
let Some(db) = self.library.database(&path) else {
|
||||
return;
|
||||
};
|
||||
match db.load_game(index) {
|
||||
Some(parsed) => {
|
||||
self.game = Some(GameView::new(
|
||||
parsed.game,
|
||||
Some(GameSource {
|
||||
path: path.clone(),
|
||||
index,
|
||||
}),
|
||||
parsed.diagnostics,
|
||||
));
|
||||
self.settings.touch_database(&path);
|
||||
self.settings_dirty = true;
|
||||
}
|
||||
None => self.toast(ctx, tr("Could not read the game")),
|
||||
}
|
||||
}
|
||||
|
||||
fn request_close(&mut self, ctx: &egui::Context, intent: CloseIntent) {
|
||||
if self.game.as_ref().is_some_and(|g| g.game.is_modified()) {
|
||||
self.confirm_close = Some(intent);
|
||||
} else {
|
||||
self.finish_close(ctx, intent);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_close(&mut self, ctx: &egui::Context, intent: CloseIntent) {
|
||||
self.analysis.stop();
|
||||
if let Some(g) = self.game.take()
|
||||
&& let Some(src) = g.source
|
||||
{
|
||||
self.library.reveal(&src.path, src.index);
|
||||
}
|
||||
if intent == CloseIntent::QuitApp {
|
||||
self.allow_quit = true;
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
}
|
||||
|
||||
fn toggle_engine(&mut self, ctx: &egui::Context) {
|
||||
if self.analysis.is_on() {
|
||||
self.analysis.stop();
|
||||
return;
|
||||
}
|
||||
match self.settings.active_engine().cloned() {
|
||||
Some(cfg) => self.analysis.start(&cfg, ctx),
|
||||
None => {
|
||||
self.settings_ui.open = true;
|
||||
self.settings_ui.tab = Tab::Engines;
|
||||
self.toast(ctx, tr("Add a UCI engine (for example, Stockfish)"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn paste_pgn(&mut self, ctx: &egui::Context) {
|
||||
let text = arboard::Clipboard::new().and_then(|mut c| c.get_text());
|
||||
match text {
|
||||
Ok(t) if !t.trim().is_empty() => {
|
||||
// Split into records first: several games must not be glued into one.
|
||||
let never = AtomicBool::new(false);
|
||||
let db = PgnDatabase::from_bytes(
|
||||
t.into_bytes(),
|
||||
Some(TextEncoding::Utf8),
|
||||
&mut |_| {},
|
||||
&never,
|
||||
);
|
||||
let (parsed, count) = match db.as_ref().ok().filter(|db| !db.is_empty()) {
|
||||
Some(db) => (db.load_game(0), db.len()),
|
||||
None => (None, 0),
|
||||
};
|
||||
let Some(parsed) = parsed else {
|
||||
self.toast(ctx, tr("The clipboard contains no recognizable PGN game"));
|
||||
return;
|
||||
};
|
||||
if parsed.game.main_child(parsed.game.root()).is_none()
|
||||
&& parsed.game.tags().len() <= 7
|
||||
&& !parsed.diagnostics.is_empty()
|
||||
{
|
||||
self.toast(ctx, tr("The clipboard contains no recognizable PGN game"));
|
||||
return;
|
||||
}
|
||||
if count > 1 {
|
||||
self.toast(ctx, trf("The clipboard has {count} games — the first one is open. To work with all of them, save them to a .pgn file and add it as a database", &[("count", &count)]));
|
||||
}
|
||||
self.game = Some(GameView::new(parsed.game, None, parsed.diagnostics));
|
||||
}
|
||||
_ => self.toast(ctx, tr("The clipboard is empty or unavailable")),
|
||||
}
|
||||
}
|
||||
|
||||
fn confirm_dialog(&mut self, ctx: &egui::Context) {
|
||||
let Some(intent) = self.confirm_close else {
|
||||
return;
|
||||
};
|
||||
let mut choice = None;
|
||||
egui::Modal::new(egui::Id::new("confirm_close")).show(ctx, |ui| {
|
||||
ui.set_width(380.0);
|
||||
ui.heading(tr("Game modified"));
|
||||
ui.label(tr(
|
||||
"The source PGN is not changed. Save the changes to a separate file?",
|
||||
));
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button(tr("Save as…")).clicked() {
|
||||
choice = Some(0);
|
||||
}
|
||||
if ui.button(tr("Don't save")).clicked() {
|
||||
choice = Some(1);
|
||||
}
|
||||
if ui.button(tr("Cancel")).clicked() || ui.input(|i| i.key_pressed(Key::Escape)) {
|
||||
choice = Some(2);
|
||||
}
|
||||
});
|
||||
});
|
||||
match choice {
|
||||
Some(0) => {
|
||||
self.confirm_close = None;
|
||||
self.close_after_save = Some(intent);
|
||||
self.pick_save(ctx);
|
||||
}
|
||||
Some(1) => {
|
||||
self.confirm_close = None;
|
||||
self.finish_close(ctx, intent);
|
||||
}
|
||||
Some(2) => self.confirm_close = None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl eframe::App for App {
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
let ctx = ui.ctx().clone();
|
||||
if self.applied_dark != Some(self.settings.dark_mode) {
|
||||
ctx.set_visuals(if self.settings.dark_mode {
|
||||
egui::Visuals::dark()
|
||||
} else {
|
||||
egui::Visuals::light()
|
||||
});
|
||||
self.applied_dark = Some(self.settings.dark_mode);
|
||||
}
|
||||
if ctx.input(|i| i.viewport().close_requested())
|
||||
&& !self.allow_quit
|
||||
&& self.game.as_ref().is_some_and(|g| g.game.is_modified())
|
||||
{
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
self.confirm_close = Some(CloseIntent::QuitApp);
|
||||
}
|
||||
self.handle_async(&ctx);
|
||||
self.debug_step(&ctx);
|
||||
self.debug_screenshot(&ctx);
|
||||
self.analysis.poll();
|
||||
|
||||
let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k);
|
||||
if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::O))) {
|
||||
self.pick_databases(&ctx);
|
||||
}
|
||||
if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::N))) && self.game.is_none() {
|
||||
self.game = Some(GameView::new(Game::new(), None, Vec::new()));
|
||||
}
|
||||
if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::Comma))) {
|
||||
self.settings_ui.open = !self.settings_ui.open;
|
||||
}
|
||||
|
||||
if let Some(game) = &mut self.game {
|
||||
let input_enabled = self.confirm_close.is_none();
|
||||
let actions = game.show(ui, &mut self.settings, &mut self.analysis, input_enabled);
|
||||
for a in actions {
|
||||
match a {
|
||||
GameAction::Back => self.request_close(&ctx, CloseIntent::BackToLibrary),
|
||||
GameAction::Sound(s) => self.play(s),
|
||||
GameAction::CopyText(text, msg) => {
|
||||
ctx.copy_text(text);
|
||||
self.toast(&ctx, msg);
|
||||
}
|
||||
GameAction::SaveAs => self.pick_save(&ctx),
|
||||
GameAction::ToggleEngine => self.toggle_engine(&ctx),
|
||||
GameAction::EngineReconfigure => {
|
||||
self.settings_dirty = true;
|
||||
if self.analysis.is_on()
|
||||
&& let Some(cfg) = self.settings.active_engine().cloned()
|
||||
{
|
||||
self.analysis.reconfigure(&cfg, &ctx);
|
||||
}
|
||||
}
|
||||
GameAction::EngineSwitch => {
|
||||
self.settings_dirty = true;
|
||||
if self.analysis.is_on()
|
||||
&& let Some(cfg) = self.settings.active_engine().cloned()
|
||||
{
|
||||
self.analysis.start(&cfg, &ctx);
|
||||
}
|
||||
}
|
||||
GameAction::OpenEngineSettings => {
|
||||
self.settings_ui.open = true;
|
||||
self.settings_ui.tab = Tab::Engines;
|
||||
}
|
||||
GameAction::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
|
||||
GameAction::OpenSettings => self.settings_ui.open = !self.settings_ui.open,
|
||||
GameAction::Toast(m) => self.toast(&ctx, m),
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let dbs = self.settings.databases.clone();
|
||||
for a in self.library.show(ui, &dbs) {
|
||||
match a {
|
||||
LibraryAction::OpenGame { path, index } => self.open_game(&ctx, path, index),
|
||||
LibraryAction::NewGame => {
|
||||
self.game = Some(GameView::new(Game::new(), None, Vec::new()))
|
||||
}
|
||||
LibraryAction::PastePgn => self.paste_pgn(&ctx),
|
||||
LibraryAction::AddDatabases => self.pick_databases(&ctx),
|
||||
LibraryAction::RemoveDatabase(p) => {
|
||||
self.settings.databases.retain(|d| *d != p);
|
||||
self.library.forget(&p);
|
||||
self.settings_dirty = true;
|
||||
}
|
||||
LibraryAction::OpenSettings => self.settings_ui.open = true,
|
||||
LibraryAction::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let (actions, changed) = self.settings_ui.show(&ctx, &mut self.settings);
|
||||
self.settings_dirty |= changed;
|
||||
for a in actions {
|
||||
match a {
|
||||
SettingsAction::AddEngine => self.pick_engine(&ctx),
|
||||
SettingsAction::TestSound => {
|
||||
if self.settings.sound_enabled {
|
||||
self.sound
|
||||
.play(self.settings.sound_set, Sound::Move, self.settings.volume);
|
||||
}
|
||||
}
|
||||
SettingsAction::EngineChanged => {
|
||||
if self.analysis.is_on() {
|
||||
self.analysis.stop();
|
||||
if let Some(cfg) = self.settings.active_engine().cloned() {
|
||||
self.analysis.start(&cfg, &ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.confirm_dialog(&ctx);
|
||||
|
||||
if let Some((msg, until)) = &self.toast {
|
||||
let now = ctx.input(|i| i.time);
|
||||
if now > *until {
|
||||
self.toast = None;
|
||||
} else {
|
||||
egui::Area::new(egui::Id::new("toast"))
|
||||
.anchor(egui::Align2::CENTER_BOTTOM, egui::vec2(0.0, -24.0))
|
||||
.order(egui::Order::Foreground)
|
||||
.show(&ctx, |ui| {
|
||||
egui::Frame::popup(ui.style()).show(ui, |ui| {
|
||||
ui.label(RichText::new(msg.as_str()).size(14.0));
|
||||
});
|
||||
});
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(250));
|
||||
}
|
||||
}
|
||||
|
||||
if self.settings_dirty && !ctx.input(|i| i.pointer.any_down()) {
|
||||
self.settings_dirty = false;
|
||||
if let Err(e) = self.settings.save() {
|
||||
eprintln!("settings: save failed: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn on_exit(&mut self) {
|
||||
self.analysis.stop();
|
||||
let _ = self.settings.save();
|
||||
}
|
||||
}
|
||||
|
||||
fn sanitize(s: &str) -> String {
|
||||
s.chars()
|
||||
.map(|c| match c {
|
||||
'—' | '–' => '-',
|
||||
c if c.is_alphanumeric() || " -.,".contains(c) => c,
|
||||
_ => '_',
|
||||
})
|
||||
.collect::<String>()
|
||||
}
|
||||
442
apps/desktop/src/assets.rs
Normal file
442
apps/desktop/src/assets.rs
Normal file
|
|
@ -0,0 +1,442 @@
|
|||
//! Bundled piece sets, board themes and sounds (see THIRD_PARTY_NOTICES.md).
|
||||
|
||||
use crate::i18n::tr;
|
||||
use egui::{Color32, Rect};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use shakmaty::{Color, Piece, Role};
|
||||
|
||||
macro_rules! piece_set {
|
||||
($name:literal) => {
|
||||
[
|
||||
include_bytes!(concat!("../assets/pieces/", $name, "/wK.svg")).as_slice(),
|
||||
include_bytes!(concat!("../assets/pieces/", $name, "/wQ.svg")),
|
||||
include_bytes!(concat!("../assets/pieces/", $name, "/wR.svg")),
|
||||
include_bytes!(concat!("../assets/pieces/", $name, "/wB.svg")),
|
||||
include_bytes!(concat!("../assets/pieces/", $name, "/wN.svg")),
|
||||
include_bytes!(concat!("../assets/pieces/", $name, "/wP.svg")),
|
||||
include_bytes!(concat!("../assets/pieces/", $name, "/bK.svg")),
|
||||
include_bytes!(concat!("../assets/pieces/", $name, "/bQ.svg")),
|
||||
include_bytes!(concat!("../assets/pieces/", $name, "/bR.svg")),
|
||||
include_bytes!(concat!("../assets/pieces/", $name, "/bB.svg")),
|
||||
include_bytes!(concat!("../assets/pieces/", $name, "/bN.svg")),
|
||||
include_bytes!(concat!("../assets/pieces/", $name, "/bP.svg")),
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum PieceSet {
|
||||
#[default]
|
||||
Cburnett,
|
||||
Merida,
|
||||
Mpchess,
|
||||
Chessnut,
|
||||
Fantasy,
|
||||
Celtic,
|
||||
Spatial,
|
||||
Rhosgfx,
|
||||
Shapes,
|
||||
KiwenSuwi,
|
||||
Firi,
|
||||
Pixel,
|
||||
Letter,
|
||||
Pirouetti,
|
||||
}
|
||||
|
||||
impl PieceSet {
|
||||
pub const ALL: [PieceSet; 14] = [
|
||||
PieceSet::Cburnett,
|
||||
PieceSet::Merida,
|
||||
PieceSet::Mpchess,
|
||||
PieceSet::Chessnut,
|
||||
PieceSet::Fantasy,
|
||||
PieceSet::Celtic,
|
||||
PieceSet::Spatial,
|
||||
PieceSet::Rhosgfx,
|
||||
PieceSet::Shapes,
|
||||
PieceSet::KiwenSuwi,
|
||||
PieceSet::Firi,
|
||||
PieceSet::Pixel,
|
||||
PieceSet::Letter,
|
||||
PieceSet::Pirouetti,
|
||||
];
|
||||
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
PieceSet::Cburnett => "cburnett",
|
||||
PieceSet::Merida => "merida",
|
||||
PieceSet::Mpchess => "mpchess",
|
||||
PieceSet::Chessnut => "chessnut",
|
||||
PieceSet::Fantasy => "fantasy",
|
||||
PieceSet::Celtic => "celtic",
|
||||
PieceSet::Spatial => "spatial",
|
||||
PieceSet::Rhosgfx => "rhosgfx",
|
||||
PieceSet::Shapes => "shapes",
|
||||
PieceSet::KiwenSuwi => "kiwen-suwi",
|
||||
PieceSet::Firi => "firi",
|
||||
PieceSet::Pixel => "pixel",
|
||||
PieceSet::Letter => "letter",
|
||||
PieceSet::Pirouetti => "pirouetti",
|
||||
}
|
||||
}
|
||||
|
||||
fn files(self) -> [&'static [u8]; 12] {
|
||||
match self {
|
||||
PieceSet::Cburnett => piece_set!("cburnett"),
|
||||
PieceSet::Merida => piece_set!("merida"),
|
||||
PieceSet::Mpchess => piece_set!("mpchess"),
|
||||
PieceSet::Chessnut => piece_set!("chessnut"),
|
||||
PieceSet::Fantasy => piece_set!("fantasy"),
|
||||
PieceSet::Celtic => piece_set!("celtic"),
|
||||
PieceSet::Spatial => piece_set!("spatial"),
|
||||
PieceSet::Rhosgfx => piece_set!("rhosgfx"),
|
||||
PieceSet::Shapes => piece_set!("shapes"),
|
||||
PieceSet::KiwenSuwi => piece_set!("kiwen-suwi"),
|
||||
PieceSet::Firi => piece_set!("firi"),
|
||||
PieceSet::Pixel => piece_set!("pixel"),
|
||||
PieceSet::Letter => piece_set!("letter"),
|
||||
PieceSet::Pirouetti => piece_set!("pirouetti"),
|
||||
}
|
||||
}
|
||||
|
||||
fn index(piece: Piece) -> usize {
|
||||
let r = match piece.role {
|
||||
Role::King => 0,
|
||||
Role::Queen => 1,
|
||||
Role::Rook => 2,
|
||||
Role::Bishop => 3,
|
||||
Role::Knight => 4,
|
||||
Role::Pawn => 5,
|
||||
};
|
||||
if piece.color == Color::White {
|
||||
r
|
||||
} else {
|
||||
r + 6
|
||||
}
|
||||
}
|
||||
|
||||
fn uri(self, piece: Piece) -> String {
|
||||
format!("bytes://pieces/{}/{}.svg", self.name(), Self::index(piece))
|
||||
}
|
||||
|
||||
pub fn paint(self, ui: &egui::Ui, piece: Piece, rect: Rect) {
|
||||
egui::Image::new(self.uri(piece)).paint_at(ui, rect);
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers all bundled SVGs with egui's byte loader.
|
||||
pub fn install(ctx: &egui::Context) {
|
||||
egui_extras::install_image_loaders(ctx);
|
||||
for set in PieceSet::ALL {
|
||||
for (i, bytes) in set.files().into_iter().enumerate() {
|
||||
ctx.include_bytes(format!("bytes://pieces/{}/{i}.svg", set.name()), bytes);
|
||||
}
|
||||
}
|
||||
for (name, bytes) in TEXTURES {
|
||||
ctx.include_bytes(format!("bytes://boards/{name}"), *bytes);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum BoardThemeId {
|
||||
#[default]
|
||||
Brown,
|
||||
Blue,
|
||||
Green,
|
||||
Tournament,
|
||||
Sand,
|
||||
Coral,
|
||||
Grey,
|
||||
Purple,
|
||||
Wood,
|
||||
Wood2,
|
||||
Wood3,
|
||||
Wood4,
|
||||
Maple,
|
||||
Maple2,
|
||||
Leather,
|
||||
Marble,
|
||||
BlueMarble,
|
||||
Blue2,
|
||||
Blue3,
|
||||
Canvas,
|
||||
Metal,
|
||||
Olive,
|
||||
Stone,
|
||||
GreenPlastic,
|
||||
PurpleDiag,
|
||||
PinkPyramid,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct BoardTheme {
|
||||
pub light: Color32,
|
||||
pub dark: Color32,
|
||||
/// Full-board image (8×8 squares, a1 dark) drawn instead of flat squares.
|
||||
pub texture: Option<&'static str>,
|
||||
pub last_move: Color32,
|
||||
pub selected: Color32,
|
||||
pub dot: Color32,
|
||||
}
|
||||
|
||||
/// Board image textures from Lichess (see THIRD_PARTY_NOTICES.md).
|
||||
const TEXTURES: &[(&str, &[u8])] = &[
|
||||
("wood.jpg", include_bytes!("../assets/boards/wood.jpg")),
|
||||
("wood2.jpg", include_bytes!("../assets/boards/wood2.jpg")),
|
||||
("wood3.jpg", include_bytes!("../assets/boards/wood3.jpg")),
|
||||
("wood4.jpg", include_bytes!("../assets/boards/wood4.jpg")),
|
||||
("maple.jpg", include_bytes!("../assets/boards/maple.jpg")),
|
||||
("maple2.jpg", include_bytes!("../assets/boards/maple2.jpg")),
|
||||
(
|
||||
"leather.jpg",
|
||||
include_bytes!("../assets/boards/leather.jpg"),
|
||||
),
|
||||
("marble.jpg", include_bytes!("../assets/boards/marble.jpg")),
|
||||
(
|
||||
"blue-marble.jpg",
|
||||
include_bytes!("../assets/boards/blue-marble.jpg"),
|
||||
),
|
||||
("blue2.jpg", include_bytes!("../assets/boards/blue2.jpg")),
|
||||
("blue3.jpg", include_bytes!("../assets/boards/blue3.jpg")),
|
||||
(
|
||||
"canvas2.jpg",
|
||||
include_bytes!("../assets/boards/canvas2.jpg"),
|
||||
),
|
||||
("metal.jpg", include_bytes!("../assets/boards/metal.jpg")),
|
||||
("olive.jpg", include_bytes!("../assets/boards/olive.jpg")),
|
||||
("grey.jpg", include_bytes!("../assets/boards/grey.jpg")),
|
||||
(
|
||||
"green-plastic.png",
|
||||
include_bytes!("../assets/boards/green-plastic.png"),
|
||||
),
|
||||
(
|
||||
"purple-diag.png",
|
||||
include_bytes!("../assets/boards/purple-diag.png"),
|
||||
),
|
||||
(
|
||||
"pink-pyramid.png",
|
||||
include_bytes!("../assets/boards/pink-pyramid.png"),
|
||||
),
|
||||
];
|
||||
|
||||
impl BoardThemeId {
|
||||
pub const ALL: [BoardThemeId; 26] = [
|
||||
BoardThemeId::Brown,
|
||||
BoardThemeId::Blue,
|
||||
BoardThemeId::Green,
|
||||
BoardThemeId::Tournament,
|
||||
BoardThemeId::Sand,
|
||||
BoardThemeId::Coral,
|
||||
BoardThemeId::Grey,
|
||||
BoardThemeId::Purple,
|
||||
BoardThemeId::Wood,
|
||||
BoardThemeId::Wood2,
|
||||
BoardThemeId::Wood3,
|
||||
BoardThemeId::Wood4,
|
||||
BoardThemeId::Maple,
|
||||
BoardThemeId::Maple2,
|
||||
BoardThemeId::Leather,
|
||||
BoardThemeId::Marble,
|
||||
BoardThemeId::BlueMarble,
|
||||
BoardThemeId::Blue2,
|
||||
BoardThemeId::Blue3,
|
||||
BoardThemeId::Canvas,
|
||||
BoardThemeId::Metal,
|
||||
BoardThemeId::Olive,
|
||||
BoardThemeId::Stone,
|
||||
BoardThemeId::GreenPlastic,
|
||||
BoardThemeId::PurpleDiag,
|
||||
BoardThemeId::PinkPyramid,
|
||||
];
|
||||
|
||||
pub fn label(self) -> String {
|
||||
let (key, n): (&'static str, Option<&str>) = match self {
|
||||
BoardThemeId::Brown => ("Brown", None),
|
||||
BoardThemeId::Blue => ("Blue", None),
|
||||
BoardThemeId::Green => ("Green", None),
|
||||
BoardThemeId::Tournament => ("Tournament", None),
|
||||
BoardThemeId::Sand => ("Sand", None),
|
||||
BoardThemeId::Coral => ("Coral", None),
|
||||
BoardThemeId::Grey => ("Grey", None),
|
||||
BoardThemeId::Purple => ("Purple", None),
|
||||
BoardThemeId::Wood => ("Wood", None),
|
||||
BoardThemeId::Wood2 => ("Wood", Some("2")),
|
||||
BoardThemeId::Wood3 => ("Wood", Some("3")),
|
||||
BoardThemeId::Wood4 => ("Wood", Some("4")),
|
||||
BoardThemeId::Maple => ("Maple", None),
|
||||
BoardThemeId::Maple2 => ("Maple", Some("2")),
|
||||
BoardThemeId::Leather => ("Leather", None),
|
||||
BoardThemeId::Marble => ("Marble", None),
|
||||
BoardThemeId::BlueMarble => ("Blue marble", None),
|
||||
BoardThemeId::Blue2 => ("Blue", Some("2")),
|
||||
BoardThemeId::Blue3 => ("Blue", Some("3")),
|
||||
BoardThemeId::Canvas => ("Canvas", None),
|
||||
BoardThemeId::Metal => ("Metal", None),
|
||||
BoardThemeId::Olive => ("Olive", None),
|
||||
BoardThemeId::Stone => ("Stone", None),
|
||||
BoardThemeId::GreenPlastic => ("Green plastic", None),
|
||||
BoardThemeId::PurpleDiag => ("Purple diagonal", None),
|
||||
BoardThemeId::PinkPyramid => ("Pink pyramid", None),
|
||||
};
|
||||
match n {
|
||||
Some(n) => format!("{} {n}", tr(key)),
|
||||
None => tr(key).to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn theme(self) -> BoardTheme {
|
||||
let rgb = |(r, g, b): (u8, u8, u8)| Color32::from_rgb(r, g, b);
|
||||
let (light, dark, texture) = match self {
|
||||
BoardThemeId::Brown => (rgb((240, 217, 181)), rgb((181, 136, 99)), None),
|
||||
BoardThemeId::Blue => (rgb((222, 227, 230)), rgb((140, 162, 173)), None),
|
||||
BoardThemeId::Green => (rgb((255, 255, 221)), rgb((134, 166, 102)), None),
|
||||
BoardThemeId::Tournament => (rgb((238, 238, 210)), rgb((118, 150, 86)), None),
|
||||
BoardThemeId::Sand => (rgb((240, 228, 196)), rgb((200, 168, 110)), None),
|
||||
BoardThemeId::Coral => (rgb((177, 228, 185)), rgb((112, 162, 163)), None),
|
||||
BoardThemeId::Grey => (rgb((217, 217, 217)), rgb((154, 154, 154)), None),
|
||||
BoardThemeId::Purple => (rgb((232, 224, 240)), rgb((159, 144, 176)), None),
|
||||
BoardThemeId::Wood => (
|
||||
rgb((215, 161, 91)),
|
||||
rgb((154, 88, 35)),
|
||||
Some("bytes://boards/wood.jpg"),
|
||||
),
|
||||
BoardThemeId::Wood2 => (
|
||||
rgb((151, 124, 79)),
|
||||
rgb((121, 95, 48)),
|
||||
Some("bytes://boards/wood2.jpg"),
|
||||
),
|
||||
BoardThemeId::Wood3 => (
|
||||
rgb((186, 173, 157)),
|
||||
rgb((129, 94, 56)),
|
||||
Some("bytes://boards/wood3.jpg"),
|
||||
),
|
||||
BoardThemeId::Wood4 => (
|
||||
rgb((191, 158, 104)),
|
||||
rgb((134, 91, 54)),
|
||||
Some("bytes://boards/wood4.jpg"),
|
||||
),
|
||||
BoardThemeId::Maple => (
|
||||
rgb((224, 190, 146)),
|
||||
rgb((180, 111, 60)),
|
||||
Some("bytes://boards/maple.jpg"),
|
||||
),
|
||||
BoardThemeId::Maple2 => (
|
||||
rgb((222, 193, 151)),
|
||||
rgb((167, 114, 85)),
|
||||
Some("bytes://boards/maple2.jpg"),
|
||||
),
|
||||
BoardThemeId::Leather => (
|
||||
rgb((206, 206, 198)),
|
||||
rgb((192, 140, 18)),
|
||||
Some("bytes://boards/leather.jpg"),
|
||||
),
|
||||
BoardThemeId::Marble => (
|
||||
rgb((126, 150, 128)),
|
||||
rgb((97, 120, 97)),
|
||||
Some("bytes://boards/marble.jpg"),
|
||||
),
|
||||
BoardThemeId::BlueMarble => (
|
||||
rgb((229, 224, 212)),
|
||||
rgb((148, 158, 174)),
|
||||
Some("bytes://boards/blue-marble.jpg"),
|
||||
),
|
||||
BoardThemeId::Blue2 => (
|
||||
rgb((129, 151, 173)),
|
||||
rgb((96, 118, 138)),
|
||||
Some("bytes://boards/blue2.jpg"),
|
||||
),
|
||||
BoardThemeId::Blue3 => (
|
||||
rgb((189, 200, 211)),
|
||||
rgb((68, 114, 163)),
|
||||
Some("bytes://boards/blue3.jpg"),
|
||||
),
|
||||
BoardThemeId::Canvas => (
|
||||
rgb((203, 206, 223)),
|
||||
rgb((114, 130, 156)),
|
||||
Some("bytes://boards/canvas2.jpg"),
|
||||
),
|
||||
BoardThemeId::Metal => (
|
||||
rgb((177, 177, 177)),
|
||||
rgb((119, 119, 119)),
|
||||
Some("bytes://boards/metal.jpg"),
|
||||
),
|
||||
BoardThemeId::Olive => (
|
||||
rgb((173, 166, 148)),
|
||||
rgb((132, 124, 106)),
|
||||
Some("bytes://boards/olive.jpg"),
|
||||
),
|
||||
BoardThemeId::Stone => (
|
||||
rgb((169, 169, 169)),
|
||||
rgb((136, 136, 136)),
|
||||
Some("bytes://boards/grey.jpg"),
|
||||
),
|
||||
BoardThemeId::GreenPlastic => (
|
||||
rgb((241, 246, 178)),
|
||||
rgb((89, 147, 93)),
|
||||
Some("bytes://boards/green-plastic.png"),
|
||||
),
|
||||
BoardThemeId::PurpleDiag => (
|
||||
rgb((227, 216, 238)),
|
||||
rgb((151, 123, 178)),
|
||||
Some("bytes://boards/purple-diag.png"),
|
||||
),
|
||||
BoardThemeId::PinkPyramid => (
|
||||
rgb((237, 238, 191)),
|
||||
rgb((242, 117, 117)),
|
||||
Some("bytes://boards/pink-pyramid.png"),
|
||||
),
|
||||
};
|
||||
BoardTheme {
|
||||
light,
|
||||
dark,
|
||||
texture,
|
||||
last_move: Color32::from_rgba_unmultiplied(155, 199, 0, 105),
|
||||
selected: Color32::from_rgba_unmultiplied(20, 85, 30, 125),
|
||||
dot: Color32::from_rgba_unmultiplied(20, 85, 30, 110),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum SoundSet {
|
||||
#[default]
|
||||
Sfx,
|
||||
Piano,
|
||||
}
|
||||
|
||||
impl SoundSet {
|
||||
pub const ALL: [SoundSet; 2] = [SoundSet::Sfx, SoundSet::Piano];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
SoundSet::Sfx => "SFX",
|
||||
SoundSet::Piano => tr("Piano"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Sound {
|
||||
Move,
|
||||
Capture,
|
||||
Check,
|
||||
Checkmate,
|
||||
}
|
||||
|
||||
pub fn sound_bytes(set: SoundSet, sound: Sound) -> &'static [u8] {
|
||||
macro_rules! s {
|
||||
($set:literal, $f:literal) => {
|
||||
include_bytes!(concat!("../assets/sounds/", $set, "/", $f, ".ogg")).as_slice()
|
||||
};
|
||||
}
|
||||
match (set, sound) {
|
||||
(SoundSet::Sfx, Sound::Move) => s!("sfx", "Move"),
|
||||
(SoundSet::Sfx, Sound::Capture) => s!("sfx", "Capture"),
|
||||
(SoundSet::Sfx, Sound::Check) => s!("sfx", "Check"),
|
||||
(SoundSet::Sfx, Sound::Checkmate) => s!("sfx", "Checkmate"),
|
||||
(SoundSet::Piano, Sound::Move) => s!("piano", "Move"),
|
||||
(SoundSet::Piano, Sound::Capture) => s!("piano", "Capture"),
|
||||
(SoundSet::Piano, Sound::Check) => s!("piano", "Check"),
|
||||
(SoundSet::Piano, Sound::Checkmate) => s!("piano", "Checkmate"),
|
||||
}
|
||||
}
|
||||
370
apps/desktop/src/board.rs
Normal file
370
apps/desktop/src/board.rs
Normal file
|
|
@ -0,0 +1,370 @@
|
|||
//! Chessboard widget: drawing, click/drag move input, promotion picker, arrows.
|
||||
|
||||
use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Shape, Stroke, Vec2, vec2};
|
||||
use shakmaty::{Chess, Color, File, Move, Piece, Position, Rank, Role, Square};
|
||||
|
||||
use crate::assets::{BoardTheme, PieceSet};
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Arrow {
|
||||
pub from: Square,
|
||||
pub to: Square,
|
||||
pub color: Color32,
|
||||
/// Relative thickness, 1.0 = default.
|
||||
pub weight: f32,
|
||||
}
|
||||
|
||||
/// Interaction state that lives across frames (per board instance).
|
||||
#[derive(Default)]
|
||||
pub struct BoardState {
|
||||
selected: Option<Square>,
|
||||
drag: Option<Square>,
|
||||
promotion: Option<(Square, Square)>,
|
||||
}
|
||||
|
||||
impl BoardState {
|
||||
pub fn clear(&mut self) {
|
||||
*self = Self::default();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BoardView<'a> {
|
||||
pub pos: &'a Chess,
|
||||
pub orientation: Color,
|
||||
pub last_move: Option<(Square, Square)>,
|
||||
pub arrows: &'a [Arrow],
|
||||
/// Circled squares (from `[%csl]` comment annotations).
|
||||
pub circles: &'a [(Square, Color32)],
|
||||
pub interactive: bool,
|
||||
pub show_coords: bool,
|
||||
pub theme: BoardTheme,
|
||||
pub pieces: PieceSet,
|
||||
}
|
||||
|
||||
impl BoardView<'_> {
|
||||
/// Draws the board into the available square area. Returns a move the user made, if any.
|
||||
pub fn show(self, ui: &mut egui::Ui, state: &mut BoardState) -> Option<Move> {
|
||||
let avail = ui.available_size();
|
||||
let side = avail.x.min(avail.y).max(64.0).floor();
|
||||
let (rect, response) = ui.allocate_exact_size(Vec2::splat(side), Sense::click_and_drag());
|
||||
let sq_size = side / 8.0;
|
||||
let geo = Geometry {
|
||||
rect,
|
||||
sq: sq_size,
|
||||
flipped: self.orientation == Color::Black,
|
||||
};
|
||||
let painter = ui.painter_at(rect);
|
||||
let legal = self.pos.legal_moves();
|
||||
let mut result = None;
|
||||
|
||||
// --- input -----------------------------------------------------------------------
|
||||
if self.interactive && state.promotion.is_none() {
|
||||
let pointer = response.interact_pointer_pos();
|
||||
if response.drag_started() {
|
||||
let origin = ui.input(|i| i.pointer.press_origin()).or(pointer);
|
||||
if let Some(sq) = origin.and_then(|p| geo.square_at(p))
|
||||
&& self.own_piece(sq)
|
||||
{
|
||||
state.drag = Some(sq);
|
||||
state.selected = Some(sq);
|
||||
}
|
||||
}
|
||||
if response.drag_stopped() {
|
||||
if let Some(from) = state.drag.take() {
|
||||
let target = ui
|
||||
.input(|i| i.pointer.latest_pos())
|
||||
.and_then(|p| geo.square_at(p));
|
||||
if let Some(to) = target.filter(|&t| t != from) {
|
||||
result = self.try_move(state, &legal, from, to);
|
||||
}
|
||||
}
|
||||
} else if response.clicked()
|
||||
&& let Some(sq) = pointer.and_then(|p| geo.square_at(p))
|
||||
{
|
||||
match state.selected {
|
||||
// try_move also covers castling by clicking the own rook,
|
||||
// and reselects when the target is just another own piece.
|
||||
Some(from) if from != sq => {
|
||||
result = self.try_move(state, &legal, from, sq);
|
||||
}
|
||||
Some(from) if from == sq => state.selected = None,
|
||||
_ => state.selected = self.own_piece(sq).then_some(sq),
|
||||
}
|
||||
}
|
||||
if response.secondary_clicked() {
|
||||
state.clear();
|
||||
}
|
||||
}
|
||||
|
||||
// --- squares -----------------------------------------------------------------------
|
||||
if let Some(uri) = self.theme.texture {
|
||||
egui::Image::new(uri).paint_at(ui, rect);
|
||||
}
|
||||
for sq in Square::ALL
|
||||
.into_iter()
|
||||
.filter(|_| self.theme.texture.is_none())
|
||||
{
|
||||
let light = (u32::from(sq.file()) + u32::from(sq.rank())) % 2 == 1;
|
||||
let fill = if light {
|
||||
self.theme.light
|
||||
} else {
|
||||
self.theme.dark
|
||||
};
|
||||
painter.rect_filled(geo.square_rect(sq), 0.0, fill);
|
||||
}
|
||||
let hl = |painter: &egui::Painter, sq: Square, c: Color32| {
|
||||
painter.rect_filled(geo.square_rect(sq), 0.0, c);
|
||||
};
|
||||
if let Some((from, to)) = self.last_move {
|
||||
hl(&painter, from, self.theme.last_move);
|
||||
hl(&painter, to, self.theme.last_move);
|
||||
}
|
||||
if let Some(sel) = state.selected {
|
||||
hl(&painter, sel, self.theme.selected);
|
||||
}
|
||||
if self.pos.is_check()
|
||||
&& let Some(k) = self.pos.board().king_of(self.pos.turn())
|
||||
{
|
||||
let r = geo.square_rect(k);
|
||||
painter.circle_filled(
|
||||
r.center(),
|
||||
sq_size * 0.48,
|
||||
Color32::from_rgba_unmultiplied(230, 40, 40, 150),
|
||||
);
|
||||
}
|
||||
|
||||
if self.show_coords {
|
||||
self.draw_coords(&painter, &geo);
|
||||
}
|
||||
|
||||
// --- pieces --------------------------------------------------------------------------
|
||||
for (sq, piece) in self.pos.board().clone() {
|
||||
if state.drag == Some(sq) && response.dragged() {
|
||||
continue;
|
||||
}
|
||||
self.pieces
|
||||
.paint(ui, piece, geo.square_rect(sq).shrink(sq_size * 0.02));
|
||||
}
|
||||
|
||||
// legal targets of the selected piece
|
||||
if let Some(sel) = state.selected {
|
||||
for m in legal.iter().filter(|m| m.from() == Some(sel)) {
|
||||
let to = ui_target(m);
|
||||
let r = geo.square_rect(to);
|
||||
if self.pos.board().piece_at(to).is_some() && !m.is_castle() {
|
||||
painter.circle_stroke(
|
||||
r.center(),
|
||||
sq_size * 0.44,
|
||||
Stroke::new(sq_size * 0.07, self.theme.dot),
|
||||
);
|
||||
} else {
|
||||
painter.circle_filled(r.center(), sq_size * 0.15, self.theme.dot);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (sq, c) in self.circles {
|
||||
let r = geo.square_rect(*sq);
|
||||
painter.circle_stroke(r.center(), sq_size * 0.46, Stroke::new(sq_size * 0.07, *c));
|
||||
}
|
||||
for a in self.arrows {
|
||||
draw_arrow(&painter, &geo, a);
|
||||
}
|
||||
|
||||
// dragged piece follows the cursor
|
||||
if let (Some(from), true) = (state.drag, response.dragged())
|
||||
&& let (Some(piece), Some(p)) = (
|
||||
self.pos.board().piece_at(from),
|
||||
ui.input(|i| i.pointer.latest_pos()),
|
||||
)
|
||||
{
|
||||
let r = Rect::from_center_size(p, Vec2::splat(sq_size * 1.1));
|
||||
self.pieces.paint(ui, piece, r);
|
||||
}
|
||||
|
||||
// --- promotion picker ---------------------------------------------------------------
|
||||
if let Some((from, to)) = state.promotion {
|
||||
painter.rect_filled(rect, 0.0, Color32::from_black_alpha(140));
|
||||
let color = self.pos.turn();
|
||||
let roles = [Role::Queen, Role::Knight, Role::Rook, Role::Bishop];
|
||||
let top_down = geo.square_rect(to).center().y < rect.center().y;
|
||||
for (i, role) in roles.iter().enumerate() {
|
||||
let off = if top_down { i as f32 } else { -(i as f32) };
|
||||
let r = geo.square_rect(to).translate(vec2(0.0, off * sq_size));
|
||||
let hover = ui.rect_contains_pointer(r);
|
||||
painter.circle_filled(
|
||||
r.center(),
|
||||
sq_size * 0.5,
|
||||
if hover {
|
||||
Color32::from_gray(240)
|
||||
} else {
|
||||
Color32::from_gray(190)
|
||||
},
|
||||
);
|
||||
self.pieces
|
||||
.paint(ui, Piece { color, role: *role }, r.shrink(sq_size * 0.08));
|
||||
if hover && ui.input(|i| i.pointer.primary_clicked()) {
|
||||
result = legal
|
||||
.iter()
|
||||
.find(|m| {
|
||||
m.from() == Some(from) && m.to() == to && m.promotion() == Some(*role)
|
||||
})
|
||||
.cloned();
|
||||
state.clear();
|
||||
}
|
||||
}
|
||||
if result.is_none()
|
||||
&& ui.input(|i| i.key_pressed(egui::Key::Escape) || i.pointer.secondary_clicked())
|
||||
{
|
||||
state.clear();
|
||||
}
|
||||
}
|
||||
|
||||
if result.is_some() {
|
||||
state.clear();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn own_piece(&self, sq: Square) -> bool {
|
||||
self.pos
|
||||
.board()
|
||||
.piece_at(sq)
|
||||
.is_some_and(|p| p.color == self.pos.turn())
|
||||
}
|
||||
|
||||
fn try_move(
|
||||
&self,
|
||||
state: &mut BoardState,
|
||||
legal: &shakmaty::MoveList,
|
||||
from: Square,
|
||||
to: Square,
|
||||
) -> Option<Move> {
|
||||
let candidates: Vec<&Move> = legal
|
||||
.iter()
|
||||
.filter(|m| m.from() == Some(from) && (ui_target(m) == to || m.to() == to))
|
||||
.collect();
|
||||
match candidates.as_slice() {
|
||||
[] => {
|
||||
state.selected = self.own_piece(to).then_some(to);
|
||||
None
|
||||
}
|
||||
[m] => Some(*(*m)),
|
||||
_ if candidates.iter().all(|m| m.is_promotion()) => {
|
||||
state.promotion = Some((from, to));
|
||||
state.selected = None;
|
||||
None
|
||||
}
|
||||
_ => candidates.first().map(|m| *(*m)),
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_coords(&self, painter: &egui::Painter, geo: &Geometry) {
|
||||
let font = FontId::proportional((geo.sq * 0.17).max(9.0));
|
||||
for i in 0..8u32 {
|
||||
let file = File::new(i);
|
||||
let rank = Rank::new(i);
|
||||
let bottom_rank = if geo.flipped {
|
||||
Rank::Eighth
|
||||
} else {
|
||||
Rank::First
|
||||
};
|
||||
let left_file = if geo.flipped { File::H } else { File::A };
|
||||
let fsq = Square::from_coords(file, bottom_rank);
|
||||
let rsq = Square::from_coords(left_file, rank);
|
||||
let color_for = |sq: Square| {
|
||||
let light = (u32::from(sq.file()) + u32::from(sq.rank())) % 2 == 1;
|
||||
if light {
|
||||
self.theme.dark
|
||||
} else {
|
||||
self.theme.light
|
||||
}
|
||||
};
|
||||
let fr = geo.square_rect(fsq);
|
||||
painter.text(
|
||||
fr.right_bottom() + vec2(-geo.sq * 0.06, -geo.sq * 0.02),
|
||||
Align2::RIGHT_BOTTOM,
|
||||
file.char(),
|
||||
font.clone(),
|
||||
color_for(fsq),
|
||||
);
|
||||
let rr = geo.square_rect(rsq);
|
||||
painter.text(
|
||||
rr.left_top() + vec2(geo.sq * 0.05, geo.sq * 0.03),
|
||||
Align2::LEFT_TOP,
|
||||
rank.char(),
|
||||
font.clone(),
|
||||
color_for(rsq),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Square the user clicks to make a move: for castling, the king's destination.
|
||||
pub fn ui_target(m: &Move) -> Square {
|
||||
match (m, m.castling_side()) {
|
||||
(Move::Castle { king, .. }, Some(side)) => side.king_to(if king.rank() == Rank::First {
|
||||
Color::White
|
||||
} else {
|
||||
Color::Black
|
||||
}),
|
||||
_ => m.to(),
|
||||
}
|
||||
}
|
||||
|
||||
struct Geometry {
|
||||
rect: Rect,
|
||||
sq: f32,
|
||||
flipped: bool,
|
||||
}
|
||||
|
||||
impl Geometry {
|
||||
fn square_rect(&self, sq: Square) -> Rect {
|
||||
let (f, r) = (u32::from(sq.file()) as f32, u32::from(sq.rank()) as f32);
|
||||
let (x, y) = if self.flipped {
|
||||
(7.0 - f, r)
|
||||
} else {
|
||||
(f, 7.0 - r)
|
||||
};
|
||||
Rect::from_min_size(
|
||||
self.rect.min + vec2(x * self.sq, y * self.sq),
|
||||
Vec2::splat(self.sq),
|
||||
)
|
||||
}
|
||||
|
||||
fn center(&self, sq: Square) -> Pos2 {
|
||||
self.square_rect(sq).center()
|
||||
}
|
||||
|
||||
fn square_at(&self, p: Pos2) -> Option<Square> {
|
||||
if !self.rect.contains(p) {
|
||||
return None;
|
||||
}
|
||||
let x = ((p.x - self.rect.min.x) / self.sq).floor().clamp(0.0, 7.0) as u32;
|
||||
let y = ((p.y - self.rect.min.y) / self.sq).floor().clamp(0.0, 7.0) as u32;
|
||||
let (f, r) = if self.flipped { (7 - x, y) } else { (x, 7 - y) };
|
||||
Some(Square::from_coords(File::new(f), Rank::new(r)))
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_arrow(painter: &egui::Painter, geo: &Geometry, a: &Arrow) {
|
||||
let from = geo.center(a.from);
|
||||
let to = geo.center(a.to);
|
||||
let dir = (to - from).normalized();
|
||||
if !dir.x.is_finite() {
|
||||
return;
|
||||
}
|
||||
let width = geo.sq * 0.16 * a.weight;
|
||||
let head_len = geo.sq * 0.42 * a.weight.sqrt();
|
||||
let head_w = geo.sq * 0.38 * a.weight.sqrt();
|
||||
let tip = to - dir * geo.sq * 0.12;
|
||||
let base = tip - dir * head_len;
|
||||
let start = from + dir * geo.sq * 0.2;
|
||||
let normal = vec2(-dir.y, dir.x);
|
||||
painter.line_segment([start, base], Stroke::new(width, a.color));
|
||||
painter.add(Shape::convex_polygon(
|
||||
vec![tip, base + normal * head_w, base - normal * head_w],
|
||||
a.color,
|
||||
Stroke::NONE,
|
||||
));
|
||||
}
|
||||
1092
apps/desktop/src/game_view.rs
Normal file
1092
apps/desktop/src/game_view.rs
Normal file
File diff suppressed because it is too large
Load diff
1101
apps/desktop/src/i18n.rs
Normal file
1101
apps/desktop/src/i18n.rs
Normal file
File diff suppressed because it is too large
Load diff
628
apps/desktop/src/library.rs
Normal file
628
apps/desktop/src/library.rs
Normal file
|
|
@ -0,0 +1,628 @@
|
|||
//! Library screen: shelf of PGN databases + searchable, sortable game table.
|
||||
|
||||
use crate::i18n::{tr, trf};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{Receiver, channel};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use chess_core::{GameEntry, OpenError, PgnDatabase, ScanProgress};
|
||||
use egui::{Color32, RichText, Sense, Ui, vec2};
|
||||
use egui_extras::{Column, TableBuilder};
|
||||
|
||||
enum Slot {
|
||||
Loading {
|
||||
progress: Arc<Mutex<ScanProgress>>,
|
||||
cancel: Arc<AtomicBool>,
|
||||
rx: Receiver<Result<PgnDatabase, OpenError>>,
|
||||
},
|
||||
Ready(Arc<PgnDatabase>),
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum SortKey {
|
||||
Index,
|
||||
White,
|
||||
WhiteElo,
|
||||
Black,
|
||||
BlackElo,
|
||||
Result,
|
||||
Date,
|
||||
Event,
|
||||
Eco,
|
||||
Moves,
|
||||
}
|
||||
|
||||
pub enum LibraryAction {
|
||||
OpenGame { path: PathBuf, index: usize },
|
||||
NewGame,
|
||||
PastePgn,
|
||||
AddDatabases,
|
||||
RemoveDatabase(PathBuf),
|
||||
OpenSettings,
|
||||
Quit,
|
||||
}
|
||||
|
||||
pub struct Library {
|
||||
slots: HashMap<PathBuf, Slot>,
|
||||
pub selected_db: Option<PathBuf>,
|
||||
search: String,
|
||||
selected_row: Option<usize>,
|
||||
sort: (SortKey, bool),
|
||||
/// Cached filtered+sorted entry indices for (db, search, sort).
|
||||
view: Vec<usize>,
|
||||
view_key: Option<(PathBuf, String, SortKey, bool)>,
|
||||
scroll_to_selected: bool,
|
||||
}
|
||||
|
||||
impl Library {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
slots: HashMap::new(),
|
||||
selected_db: None,
|
||||
search: String::new(),
|
||||
selected_row: None,
|
||||
sort: (SortKey::Index, true),
|
||||
view: Vec::new(),
|
||||
view_key: None,
|
||||
scroll_to_selected: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts loading `path` in the background (no-op if already loaded/loading).
|
||||
pub fn load(&mut self, path: &Path, ctx: &egui::Context) {
|
||||
if matches!(
|
||||
self.slots.get(path),
|
||||
Some(Slot::Loading { .. } | Slot::Ready(_))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
let progress = Arc::new(Mutex::new(ScanProgress {
|
||||
bytes_done: 0,
|
||||
bytes_total: 0,
|
||||
games: 0,
|
||||
}));
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let (tx, rx) = channel();
|
||||
let (p, c, path_owned, ctx) = (
|
||||
progress.clone(),
|
||||
cancel.clone(),
|
||||
path.to_path_buf(),
|
||||
ctx.clone(),
|
||||
);
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("pgn-scan".into())
|
||||
.spawn(move || {
|
||||
let res = PgnDatabase::open(
|
||||
&path_owned,
|
||||
&mut |sp| {
|
||||
if let Ok(mut g) = p.lock() {
|
||||
*g = sp;
|
||||
}
|
||||
ctx.request_repaint();
|
||||
},
|
||||
&c,
|
||||
);
|
||||
let _ = tx.send(res);
|
||||
ctx.request_repaint();
|
||||
});
|
||||
let slot = match spawned {
|
||||
Ok(_) => Slot::Loading {
|
||||
progress,
|
||||
cancel,
|
||||
rx,
|
||||
},
|
||||
Err(e) => Slot::Failed(e.to_string()),
|
||||
};
|
||||
self.slots.insert(path.to_path_buf(), slot);
|
||||
}
|
||||
|
||||
pub fn select_db(&mut self, path: &Path, ctx: &egui::Context) {
|
||||
self.load(path, ctx);
|
||||
if self.selected_db.as_deref() != Some(path) {
|
||||
self.selected_db = Some(path.to_path_buf());
|
||||
self.selected_row = None;
|
||||
self.search.clear();
|
||||
self.view_key = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects (and scrolls to) a game row, e.g. when returning from a game.
|
||||
pub fn reveal(&mut self, path: &Path, index: usize) {
|
||||
if self.selected_db.as_deref() == Some(path) {
|
||||
self.selected_row = Some(index);
|
||||
self.scroll_to_selected = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn forget(&mut self, path: &Path) {
|
||||
if let Some(Slot::Loading { cancel, .. }) = self.slots.remove(path) {
|
||||
cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
if self.selected_db.as_deref() == Some(path) {
|
||||
self.selected_db = None;
|
||||
self.view_key = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn database(&self, path: &Path) -> Option<Arc<PgnDatabase>> {
|
||||
match self.slots.get(path) {
|
||||
Some(Slot::Ready(db)) => Some(db.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn poll(&mut self) {
|
||||
for slot in self.slots.values_mut() {
|
||||
if let Slot::Loading { rx, .. } = slot
|
||||
&& let Ok(res) = rx.try_recv()
|
||||
{
|
||||
*slot = match res {
|
||||
Ok(db) => Slot::Ready(Arc::new(db)),
|
||||
Err(OpenError::Cancelled) => Slot::Failed(tr("Loading cancelled").into()),
|
||||
Err(e) => Slot::Failed(e.to_string()),
|
||||
};
|
||||
self.view_key = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn show(&mut self, ui: &mut Ui, databases: &[PathBuf]) -> Vec<LibraryAction> {
|
||||
self.poll();
|
||||
let mut actions = Vec::new();
|
||||
egui::Panel::top("shelf").show(ui, |ui| self.shelf(ui, databases, &mut actions));
|
||||
egui::CentralPanel::default().show(ui, |ui| self.table_area(ui, &mut actions));
|
||||
actions
|
||||
}
|
||||
|
||||
fn shelf(&mut self, ui: &mut Ui, databases: &[PathBuf], actions: &mut Vec<LibraryAction>) {
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.heading(tr("Databases"));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if crate::widgets::close_button(ui).clicked() {
|
||||
actions.push(LibraryAction::Quit);
|
||||
}
|
||||
if ui.button(tr("⚙ Settings")).clicked() {
|
||||
actions.push(LibraryAction::OpenSettings);
|
||||
}
|
||||
if ui
|
||||
.button(tr("📋 Paste PGN"))
|
||||
.on_hover_text(tr("Open a game from the clipboard"))
|
||||
.clicked()
|
||||
{
|
||||
actions.push(LibraryAction::PastePgn);
|
||||
}
|
||||
if ui
|
||||
.button(tr("♟ New game"))
|
||||
.on_hover_text(tr("Empty board in the starting position (Ctrl+N)"))
|
||||
.clicked()
|
||||
{
|
||||
actions.push(LibraryAction::NewGame);
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(8.0, 8.0);
|
||||
for path in databases {
|
||||
self.db_card(ui, path, actions);
|
||||
}
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(150.0, 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("+ Add PGN"),
|
||||
egui::FontId::proportional(15.0),
|
||||
visuals.text_color(),
|
||||
);
|
||||
if resp.on_hover_text(tr("Open a PGN file (Ctrl+O)")).clicked() {
|
||||
actions.push(LibraryAction::AddDatabases);
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
|
||||
fn db_card(&mut self, ui: &mut Ui, path: &Path, actions: &mut Vec<LibraryAction>) {
|
||||
let selected = self.selected_db.as_deref() == Some(path);
|
||||
let name = path
|
||||
.file_stem()
|
||||
.map(|s| s.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
let detail = match self.slots.get(path) {
|
||||
Some(Slot::Ready(db)) => trf("{n} games", &[("n", &db.len())]),
|
||||
Some(Slot::Loading { progress, .. }) => {
|
||||
let p = progress.lock().map(|g| *g).unwrap_or(ScanProgress {
|
||||
bytes_done: 0,
|
||||
bytes_total: 0,
|
||||
games: 0,
|
||||
});
|
||||
trf("loading… {n}", &[("n", &p.games)])
|
||||
}
|
||||
Some(Slot::Failed(_)) => tr("error").into(),
|
||||
None if !path.exists() => tr("file not found").into(),
|
||||
None => tr("not loaded").into(),
|
||||
};
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(190.0, 64.0), Sense::click());
|
||||
let v = ui.visuals();
|
||||
let fill = if selected {
|
||||
v.selection.bg_fill
|
||||
} else if resp.hovered() {
|
||||
v.widgets.hovered.weak_bg_fill
|
||||
} else {
|
||||
v.faint_bg_color
|
||||
};
|
||||
ui.painter().rect_filled(rect, 6.0, fill);
|
||||
let text_color = if selected {
|
||||
v.selection.stroke.color
|
||||
} else {
|
||||
v.text_color()
|
||||
};
|
||||
ui.painter().text(
|
||||
rect.left_top() + vec2(12.0, 10.0),
|
||||
egui::Align2::LEFT_TOP,
|
||||
"🗄",
|
||||
egui::FontId::proportional(22.0),
|
||||
text_color,
|
||||
);
|
||||
let galley = ui.painter().layout(
|
||||
name,
|
||||
egui::FontId::proportional(14.0),
|
||||
text_color,
|
||||
rect.width() - 52.0,
|
||||
);
|
||||
ui.painter()
|
||||
.galley(rect.left_top() + vec2(44.0, 9.0), galley, text_color);
|
||||
ui.painter().text(
|
||||
rect.left_bottom() + vec2(44.0, -8.0),
|
||||
egui::Align2::LEFT_BOTTOM,
|
||||
detail,
|
||||
egui::FontId::proportional(12.0),
|
||||
v.weak_text_color(),
|
||||
);
|
||||
let resp = resp.on_hover_text(path.display().to_string());
|
||||
if resp.clicked() {
|
||||
self.select_db(path, ui.ctx());
|
||||
}
|
||||
resp.context_menu(|ui| {
|
||||
if ui.button(tr("Remove from list")).clicked() {
|
||||
actions.push(LibraryAction::RemoveDatabase(path.to_path_buf()));
|
||||
ui.close();
|
||||
}
|
||||
if ui.button(tr("Reload file")).clicked() {
|
||||
self.slots.remove(path);
|
||||
self.view_key = None;
|
||||
self.load(path, ui.ctx());
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn table_area(&mut self, ui: &mut Ui, actions: &mut Vec<LibraryAction>) {
|
||||
let Some(path) = self.selected_db.clone() else {
|
||||
ui.centered_and_justified(|ui| {
|
||||
ui.label(
|
||||
RichText::new(tr(
|
||||
"Choose a database above, add a PGN file or start a new game",
|
||||
))
|
||||
.weak()
|
||||
.size(16.0),
|
||||
);
|
||||
});
|
||||
return;
|
||||
};
|
||||
let db = match self.slots.get(&path) {
|
||||
Some(Slot::Ready(db)) => db.clone(),
|
||||
Some(Slot::Loading {
|
||||
progress, cancel, ..
|
||||
}) => {
|
||||
let p = progress.lock().map(|g| *g).unwrap_or(ScanProgress {
|
||||
bytes_done: 0,
|
||||
bytes_total: 0,
|
||||
games: 0,
|
||||
});
|
||||
let frac = if p.bytes_total > 0 {
|
||||
p.bytes_done as f32 / p.bytes_total as f32
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let cancel = cancel.clone();
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.add_space(40.0);
|
||||
ui.label(trf(
|
||||
"Reading {path} — games found: {n}",
|
||||
&[("path", &path.display()), ("n", &p.games)],
|
||||
));
|
||||
ui.add(egui::ProgressBar::new(frac).desired_width(400.0));
|
||||
if ui.button(tr("Cancel")).clicked() {
|
||||
cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
Some(Slot::Failed(e)) => {
|
||||
let e = e.clone();
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.add_space(40.0);
|
||||
ui.label(
|
||||
RichText::new(trf(
|
||||
"Could not open {path}: {e}",
|
||||
&[("path", &path.display()), ("e", &e)],
|
||||
))
|
||||
.color(ui.visuals().error_fg_color),
|
||||
);
|
||||
if ui.button(tr("Retry")).clicked() {
|
||||
self.slots.remove(&path);
|
||||
self.load(&path, ui.ctx());
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
None => {
|
||||
self.load(&path, ui.ctx());
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let mut search_focused = false;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(
|
||||
RichText::new(
|
||||
path.file_name()
|
||||
.map(|s| s.to_string_lossy().into_owned())
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
.strong(),
|
||||
);
|
||||
let enc = db.encoding();
|
||||
ui.label(
|
||||
RichText::new(trf(
|
||||
"· {n} games · encoding {enc}",
|
||||
&[("n", &db.len()), ("enc", &enc.label())],
|
||||
))
|
||||
.weak(),
|
||||
);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let resp = ui.add(
|
||||
egui::TextEdit::singleline(&mut self.search)
|
||||
.hint_text(tr("🔍 Search: player, event, ECO, year"))
|
||||
.desired_width(280.0),
|
||||
);
|
||||
if ui.input(|i| i.modifiers.command && i.key_pressed(egui::Key::F)) {
|
||||
resp.request_focus();
|
||||
}
|
||||
search_focused = resp.has_focus();
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
|
||||
let key = (path.clone(), self.search.clone(), self.sort.0, self.sort.1);
|
||||
if self.view_key.as_ref() != Some(&key) {
|
||||
self.view = filtered_sorted(db.entries(), &self.search, self.sort);
|
||||
self.view_key = Some(key);
|
||||
}
|
||||
|
||||
// Keyboard: Up/Down move the selection, Enter opens.
|
||||
if !ui.ctx().egui_wants_keyboard_input() || search_focused {
|
||||
let pos = self
|
||||
.selected_row
|
||||
.and_then(|r| self.view.iter().position(|&i| i == r));
|
||||
let (up, down, enter) = ui.input(|i| {
|
||||
(
|
||||
i.key_pressed(egui::Key::ArrowUp),
|
||||
i.key_pressed(egui::Key::ArrowDown),
|
||||
i.key_pressed(egui::Key::Enter),
|
||||
)
|
||||
});
|
||||
if down || up {
|
||||
let next = match (pos, down) {
|
||||
(None, _) => 0,
|
||||
(Some(p), true) => (p + 1).min(self.view.len().saturating_sub(1)),
|
||||
(Some(p), false) => p.saturating_sub(1),
|
||||
};
|
||||
if let Some(&i) = self.view.get(next) {
|
||||
self.selected_row = Some(i);
|
||||
self.scroll_to_selected = true;
|
||||
}
|
||||
}
|
||||
if enter && let Some(index) = self.selected_row {
|
||||
actions.push(LibraryAction::OpenGame {
|
||||
path: path.clone(),
|
||||
index,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let scroll_row = if std::mem::take(&mut self.scroll_to_selected) {
|
||||
self.selected_row
|
||||
.and_then(|r| self.view.iter().position(|&i| i == r))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let headers: [(&str, SortKey); 10] = [
|
||||
("№", SortKey::Index),
|
||||
(tr("White"), SortKey::White),
|
||||
("Elo", SortKey::WhiteElo),
|
||||
(tr("Black"), SortKey::Black),
|
||||
("Elo", SortKey::BlackElo),
|
||||
(tr("Result"), SortKey::Result),
|
||||
(tr("Moves"), SortKey::Moves),
|
||||
("ECO", SortKey::Eco),
|
||||
(tr("Event"), SortKey::Event),
|
||||
(tr("Date"), SortKey::Date),
|
||||
];
|
||||
let mut table = TableBuilder::new(ui)
|
||||
.striped(true)
|
||||
.resizable(true)
|
||||
.sense(Sense::click())
|
||||
.cell_layout(egui::Layout::left_to_right(egui::Align::Center))
|
||||
.column(Column::exact(52.0))
|
||||
.column(Column::initial(170.0).at_least(60.0).clip(true))
|
||||
.column(Column::exact(48.0))
|
||||
.column(Column::initial(170.0).at_least(60.0).clip(true))
|
||||
.column(Column::exact(48.0))
|
||||
.column(Column::exact(80.0))
|
||||
.column(Column::exact(52.0))
|
||||
.column(Column::exact(48.0))
|
||||
.column(Column::remainder().at_least(80.0).clip(true))
|
||||
.column(Column::exact(96.0));
|
||||
if let Some(r) = scroll_row {
|
||||
table = table.scroll_to_row(r, Some(egui::Align::Center));
|
||||
}
|
||||
let view = &self.view;
|
||||
let entries = db.entries();
|
||||
let mut clicked = None;
|
||||
let mut opened = None;
|
||||
let mut sort_click = None;
|
||||
table
|
||||
.header(26.0, |mut header| {
|
||||
for (label, key) in headers {
|
||||
header.col(|ui| {
|
||||
let arrow = if self.sort.0 == key {
|
||||
if self.sort.1 { " ⏶" } else { " ⏷" }
|
||||
} else {
|
||||
""
|
||||
};
|
||||
if ui
|
||||
.add(
|
||||
egui::Button::new(
|
||||
RichText::new(format!("{label}{arrow}")).strong(),
|
||||
)
|
||||
.frame(false),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
sort_click = Some(key);
|
||||
}
|
||||
});
|
||||
}
|
||||
})
|
||||
.body(|body| {
|
||||
body.rows(24.0, view.len(), |mut row| {
|
||||
let Some(e) = view.get(row.index()).and_then(|&i| entries.get(i)) else {
|
||||
return;
|
||||
};
|
||||
row.set_selected(self.selected_row == Some(e.index));
|
||||
let cells: [String; 10] = [
|
||||
(e.index + 1).to_string(),
|
||||
e.white().unwrap_or("").to_string(),
|
||||
e.white_elo().map(|x| x.to_string()).unwrap_or_default(),
|
||||
e.black().unwrap_or("").to_string(),
|
||||
e.black_elo().map(|x| x.to_string()).unwrap_or_default(),
|
||||
e.result().unwrap_or("*").to_string(),
|
||||
e.ply_count()
|
||||
.map(|p| p.div_ceil(2).to_string())
|
||||
.unwrap_or_default(),
|
||||
e.eco().unwrap_or("").to_string(),
|
||||
e.event().filter(|s| *s != "?").unwrap_or("").to_string(),
|
||||
display_date(e.date().unwrap_or("")),
|
||||
];
|
||||
for (i, text) in cells.into_iter().enumerate() {
|
||||
row.col(|ui| {
|
||||
let mut t = RichText::new(text);
|
||||
if i == 0 {
|
||||
t = t.weak();
|
||||
}
|
||||
if i == 8 {
|
||||
t = t.italics();
|
||||
}
|
||||
if i == 0 && (e.flags.has_structure_issues || e.flags.has_decode_errors)
|
||||
{
|
||||
t = t.color(Color32::from_rgb(0xe6, 0x8f, 0x00));
|
||||
}
|
||||
ui.add(egui::Label::new(t).selectable(false).truncate());
|
||||
});
|
||||
}
|
||||
let resp = row.response();
|
||||
if resp.clicked() {
|
||||
clicked = Some(e.index);
|
||||
}
|
||||
if resp.double_clicked() {
|
||||
opened = Some(e.index);
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(k) = sort_click {
|
||||
self.sort = if self.sort.0 == k {
|
||||
(k, !self.sort.1)
|
||||
} else {
|
||||
(k, true)
|
||||
};
|
||||
}
|
||||
if let Some(i) = clicked {
|
||||
self.selected_row = Some(i);
|
||||
}
|
||||
if let Some(index) = opened {
|
||||
self.selected_row = Some(index);
|
||||
actions.push(LibraryAction::OpenGame { path, index });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// "2010.??.??" → "2010", "1997.05.??" → "05.1997", full dates as "dd.mm.yyyy".
|
||||
fn display_date(raw: &str) -> String {
|
||||
let parts: Vec<&str> = raw.split('.').collect();
|
||||
let known = |s: &&str| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit());
|
||||
match parts.as_slice() {
|
||||
[y, m, d] if known(y) && known(m) && known(d) => format!("{d}.{m}.{y}"),
|
||||
[y, m, _] if known(y) && known(m) => format!("{m}.{y}"),
|
||||
[y, ..] if known(y) => (*y).to_string(),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn filtered_sorted(entries: &[GameEntry], search: &str, (key, asc): (SortKey, bool)) -> Vec<usize> {
|
||||
let needle = search.trim().to_lowercase();
|
||||
let mut v: Vec<usize> = entries
|
||||
.iter()
|
||||
.filter(|e| {
|
||||
needle.is_empty()
|
||||
|| [
|
||||
"White",
|
||||
"Black",
|
||||
"Event",
|
||||
"Site",
|
||||
"ECO",
|
||||
"Date",
|
||||
"Annotator",
|
||||
]
|
||||
.iter()
|
||||
.any(|t| e.tag(t).is_some_and(|s| s.to_lowercase().contains(&needle)))
|
||||
})
|
||||
.map(|e| e.index)
|
||||
.collect();
|
||||
let text = |e: &GameEntry| -> String {
|
||||
match key {
|
||||
SortKey::White => e.white().unwrap_or("").to_lowercase(),
|
||||
SortKey::Black => e.black().unwrap_or("").to_lowercase(),
|
||||
SortKey::Result => e.result().unwrap_or("").to_string(),
|
||||
SortKey::Date => e.date().unwrap_or("").to_string(),
|
||||
SortKey::Event => e.event().unwrap_or("").to_lowercase(),
|
||||
SortKey::Eco => e.eco().unwrap_or("").to_string(),
|
||||
_ => String::new(),
|
||||
}
|
||||
};
|
||||
let num = |e: &GameEntry| -> i64 {
|
||||
match key {
|
||||
SortKey::Index => e.index as i64,
|
||||
SortKey::WhiteElo => e.white_elo().map(i64::from).unwrap_or(-1),
|
||||
SortKey::BlackElo => e.black_elo().map(i64::from).unwrap_or(-1),
|
||||
SortKey::Moves => e.ply_count().map(i64::from).unwrap_or(-1),
|
||||
_ => 0,
|
||||
}
|
||||
};
|
||||
v.sort_by(|&a, &b| {
|
||||
let (ea, eb) = (&entries[a], &entries[b]);
|
||||
let ord = text(ea)
|
||||
.cmp(&text(eb))
|
||||
.then(num(ea).cmp(&num(eb)))
|
||||
.then(a.cmp(&b));
|
||||
if asc { ord } else { ord.reverse() }
|
||||
});
|
||||
v
|
||||
}
|
||||
39
apps/desktop/src/main.rs
Normal file
39
apps/desktop/src/main.rs
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
// No console window for release builds on Windows.
|
||||
#![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")]
|
||||
|
||||
mod analysis;
|
||||
mod app;
|
||||
mod assets;
|
||||
mod board;
|
||||
mod game_view;
|
||||
mod i18n;
|
||||
mod library;
|
||||
mod notation;
|
||||
mod settings;
|
||||
mod settings_ui;
|
||||
mod sound;
|
||||
mod widgets;
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
let options = eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_app_id("io.github.vrubelroman.chessPenguin")
|
||||
.with_title("ChessPenguin")
|
||||
.with_inner_size([1400.0, 900.0])
|
||||
.with_min_inner_size([900.0, 600.0])
|
||||
// X11 uses this; on Wayland the icon comes from the .desktop entry matching the app id.
|
||||
.with_icon(
|
||||
eframe::icon_data::from_png_bytes(include_bytes!("../assets/icon-256.png"))
|
||||
.unwrap_or_default(),
|
||||
),
|
||||
..Default::default()
|
||||
};
|
||||
eframe::run_native(
|
||||
"ChessPenguin",
|
||||
options,
|
||||
Box::new(|cc| {
|
||||
assets::install(&cc.egui_ctx);
|
||||
Ok(Box::new(app::App::new(&cc.egui_ctx)))
|
||||
}),
|
||||
)
|
||||
}
|
||||
370
apps/desktop/src/notation.rs
Normal file
370
apps/desktop/src/notation.rs
Normal file
|
|
@ -0,0 +1,370 @@
|
|||
//! Move list: main line as a two-column table (Lichess style), comments and variations
|
||||
//! as full-width blocks between rows; nested variations inline in parentheses.
|
||||
|
||||
use crate::i18n::tr;
|
||||
use chess_core::shakmaty::Color;
|
||||
use chess_core::{CommentPart, Game, Nag, NodeId, parse_comment};
|
||||
use egui::{Align2, Color32, FontId, RichText, Sense, Stroke, Ui, vec2};
|
||||
|
||||
pub struct Notation<'a> {
|
||||
pub game: &'a Game,
|
||||
pub cursor: NodeId,
|
||||
pub scroll_to_cursor: bool,
|
||||
}
|
||||
|
||||
/// Result of a frame of the notation panel.
|
||||
#[derive(Default)]
|
||||
pub struct NotationResponse {
|
||||
pub clicked: Option<NodeId>,
|
||||
pub context: Option<(NodeId, NotationCommand)>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum NotationCommand {
|
||||
Promote,
|
||||
Delete,
|
||||
}
|
||||
|
||||
const ROW_H: f32 = 26.0;
|
||||
const NUM_W: f32 = 38.0;
|
||||
|
||||
impl Notation<'_> {
|
||||
pub fn show(self, ui: &mut Ui) -> NotationResponse {
|
||||
let mut out = NotationResponse::default();
|
||||
let game = self.game;
|
||||
let root_comments = comment_text(
|
||||
game.node(NodeId::ROOT)
|
||||
.map(|n| n.comments_after())
|
||||
.unwrap_or(&[]),
|
||||
);
|
||||
if !root_comments.is_empty() {
|
||||
comment_block(ui, &root_comments);
|
||||
}
|
||||
|
||||
let mut row = Row::default();
|
||||
let mut node = NodeId::ROOT;
|
||||
while let Some(child) = game.main_child(node) {
|
||||
let Some(n) = game.node(child) else { break };
|
||||
let before = comment_text(n.comments_before());
|
||||
if !before.is_empty() {
|
||||
row.flush(ui, &self, &mut out);
|
||||
comment_block(ui, &before);
|
||||
}
|
||||
let (num, color) = game.move_number(child).unwrap_or((0, Color::White));
|
||||
if color == Color::White {
|
||||
row.flush(ui, &self, &mut out);
|
||||
row.num = num;
|
||||
row.white = Some(child);
|
||||
} else {
|
||||
if row.white.is_none() {
|
||||
row.num = num;
|
||||
}
|
||||
row.black = Some(child);
|
||||
}
|
||||
let after = comment_text(n.comments_after());
|
||||
let vars = game.variations(node);
|
||||
let interrupted = !after.is_empty() || !vars.is_empty() || !n.unparsed().is_empty();
|
||||
if interrupted || color == Color::Black {
|
||||
row.flush(ui, &self, &mut out);
|
||||
if !after.is_empty() {
|
||||
comment_block(ui, &after);
|
||||
}
|
||||
for u in n.unparsed() {
|
||||
unparsed_block(ui, u);
|
||||
}
|
||||
for &v in vars {
|
||||
variation_block(ui, &self, v, &mut out);
|
||||
}
|
||||
}
|
||||
node = child;
|
||||
}
|
||||
row.flush(ui, &self, &mut out);
|
||||
|
||||
let result = game.result().as_str();
|
||||
if result != "*" {
|
||||
ui.add_space(6.0);
|
||||
ui.vertical_centered(|ui| ui.label(RichText::new(result).strong().size(16.0)));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Row {
|
||||
num: u32,
|
||||
white: Option<NodeId>,
|
||||
black: Option<NodeId>,
|
||||
}
|
||||
|
||||
impl Row {
|
||||
fn flush(&mut self, ui: &mut Ui, n: &Notation, out: &mut NotationResponse) {
|
||||
if self.white.is_none() && self.black.is_none() {
|
||||
return;
|
||||
}
|
||||
let width = ui.available_width();
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(width, ROW_H), Sense::hover());
|
||||
let painter = ui.painter();
|
||||
let visuals = ui.visuals();
|
||||
painter.rect_filled(
|
||||
egui::Rect::from_min_size(rect.min, vec2(NUM_W, ROW_H)),
|
||||
0.0,
|
||||
visuals.faint_bg_color,
|
||||
);
|
||||
painter.text(
|
||||
rect.left_center() + vec2(NUM_W - 8.0, 0.0),
|
||||
Align2::RIGHT_CENTER,
|
||||
self.num.to_string(),
|
||||
FontId::proportional(14.0),
|
||||
visuals.weak_text_color(),
|
||||
);
|
||||
let cell_w = (width - NUM_W) / 2.0;
|
||||
let cells = [(self.white, 0.0), (self.black, cell_w)];
|
||||
for (id, off) in cells {
|
||||
let cell =
|
||||
egui::Rect::from_min_size(rect.min + vec2(NUM_W + off, 0.0), vec2(cell_w, ROW_H));
|
||||
match id {
|
||||
Some(id) => {
|
||||
let resp = ui.interact(cell, ui.id().with(("mv", id.index())), Sense::click());
|
||||
paint_move_cell(ui, cell, n.game, id, id == n.cursor, resp.hovered());
|
||||
handle_move_response(ui, &resp, n, id, out);
|
||||
}
|
||||
None => {
|
||||
ui.painter().text(
|
||||
cell.left_center() + vec2(10.0, 0.0),
|
||||
Align2::LEFT_CENTER,
|
||||
"…",
|
||||
FontId::proportional(15.0),
|
||||
ui.visuals().weak_text_color(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
*self = Row::default();
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_move_response(
|
||||
ui: &Ui,
|
||||
resp: &egui::Response,
|
||||
n: &Notation,
|
||||
id: NodeId,
|
||||
out: &mut NotationResponse,
|
||||
) {
|
||||
if resp.clicked() {
|
||||
out.clicked = Some(id);
|
||||
}
|
||||
if n.scroll_to_cursor && id == n.cursor {
|
||||
resp.scroll_to_me(Some(egui::Align::Center));
|
||||
}
|
||||
let is_variation = n.game.child_index(id).is_some_and(|i| i > 0) || !n.game.is_mainline(id);
|
||||
resp.context_menu(|ui| {
|
||||
if is_variation && ui.button(tr("Make main line")).clicked() {
|
||||
out.context = Some((id, NotationCommand::Promote));
|
||||
ui.close();
|
||||
}
|
||||
if ui.button(tr("Delete move and continuation")).clicked() {
|
||||
out.context = Some((id, NotationCommand::Delete));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
let _ = ui;
|
||||
}
|
||||
|
||||
fn paint_move_cell(
|
||||
ui: &Ui,
|
||||
cell: egui::Rect,
|
||||
game: &Game,
|
||||
id: NodeId,
|
||||
current: bool,
|
||||
hovered: bool,
|
||||
) {
|
||||
let visuals = ui.visuals();
|
||||
if current {
|
||||
ui.painter()
|
||||
.rect_filled(cell, 2.0, visuals.selection.bg_fill);
|
||||
} else if hovered {
|
||||
ui.painter()
|
||||
.rect_filled(cell, 2.0, visuals.widgets.hovered.weak_bg_fill);
|
||||
}
|
||||
let node = game.node(id);
|
||||
let san = game.game_move(id).map(|m| m.san.as_str()).unwrap_or("?");
|
||||
let (sym, color) = node
|
||||
.map(|n| move_glyph(n.nags()))
|
||||
.unwrap_or((String::new(), None));
|
||||
let text_color = if current {
|
||||
visuals.selection.stroke.color
|
||||
} else {
|
||||
color.unwrap_or(visuals.text_color())
|
||||
};
|
||||
ui.painter().text(
|
||||
cell.left_center() + vec2(10.0, 0.0),
|
||||
Align2::LEFT_CENTER,
|
||||
format!("{san}{sym}"),
|
||||
FontId::proportional(16.0),
|
||||
text_color,
|
||||
);
|
||||
}
|
||||
|
||||
/// Move-assessment glyph (`!`, `?`, …) with its color, plus position assessments.
|
||||
fn move_glyph(nags: &[Nag]) -> (String, Option<Color32>) {
|
||||
let mut s = String::new();
|
||||
let mut color = None;
|
||||
for nag in nags {
|
||||
let Some(sym) = nag.symbol() else {
|
||||
s.push_str(&format!(" ${}", nag.0));
|
||||
continue;
|
||||
};
|
||||
if nag.is_move_assessment() {
|
||||
color = Some(match nag.0 {
|
||||
1 => Color32::from_rgb(0x62, 0x9c, 0x2e),
|
||||
2 => Color32::from_rgb(0xe6, 0x8f, 0x00),
|
||||
3 => Color32::from_rgb(0x22, 0xac, 0x9a),
|
||||
4 => Color32::from_rgb(0xdf, 0x53, 0x53),
|
||||
5 => Color32::from_rgb(0xea, 0x45, 0xd8),
|
||||
6 => Color32::from_rgb(0x56, 0xb4, 0xe9),
|
||||
_ => continue,
|
||||
});
|
||||
s.push_str(sym);
|
||||
} else {
|
||||
s.push(' ');
|
||||
s.push_str(sym);
|
||||
}
|
||||
}
|
||||
(s, color)
|
||||
}
|
||||
|
||||
fn comment_text(comments: &[String]) -> String {
|
||||
let mut out = String::new();
|
||||
for c in comments {
|
||||
for part in parse_comment(c) {
|
||||
if let CommentPart::Text(t) = part {
|
||||
// Source line breaks are formatting, not content: reflow to the panel width.
|
||||
for word in t.split_whitespace() {
|
||||
if !out.is_empty() {
|
||||
out.push(' ');
|
||||
}
|
||||
out.push_str(word);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn block_frame(ui: &Ui) -> egui::Frame {
|
||||
egui::Frame::new()
|
||||
.fill(ui.visuals().extreme_bg_color)
|
||||
.inner_margin(egui::Margin::symmetric(10, 6))
|
||||
.stroke(Stroke::new(
|
||||
1.0,
|
||||
ui.visuals().widgets.noninteractive.bg_stroke.color,
|
||||
))
|
||||
}
|
||||
|
||||
fn comment_block(ui: &mut Ui, text: &str) {
|
||||
block_frame(ui).show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.label(RichText::new(text).color(comment_color(ui)).size(14.5));
|
||||
});
|
||||
}
|
||||
|
||||
fn unparsed_block(ui: &mut Ui, text: &str) {
|
||||
block_frame(ui).show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.label(
|
||||
RichText::new(text)
|
||||
.monospace()
|
||||
.color(ui.visuals().warn_fg_color),
|
||||
)
|
||||
.on_hover_text(tr("PGN fragment that could not be parsed; kept as is"));
|
||||
});
|
||||
}
|
||||
|
||||
fn comment_color(ui: &Ui) -> Color32 {
|
||||
if ui.visuals().dark_mode {
|
||||
Color32::from_rgb(0x9e, 0xc4, 0xe0)
|
||||
} else {
|
||||
Color32::from_rgb(0x2a, 0x5b, 0x8a)
|
||||
}
|
||||
}
|
||||
|
||||
fn variation_block(ui: &mut Ui, n: &Notation, start: NodeId, out: &mut NotationResponse) {
|
||||
block_frame(ui).show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(3.0, 2.0);
|
||||
inline_line(ui, n, start, out);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Renders a line starting at `first` (a variation move) as flowing text.
|
||||
fn inline_line(ui: &mut Ui, n: &Notation, first: NodeId, out: &mut NotationResponse) {
|
||||
let game = n.game;
|
||||
let mut node = first;
|
||||
let mut need_number = true;
|
||||
loop {
|
||||
let Some(nd) = game.node(node) else { return };
|
||||
let before = comment_text(nd.comments_before());
|
||||
if !before.is_empty() {
|
||||
ui.label(RichText::new(before).color(comment_color(ui)));
|
||||
need_number = true;
|
||||
}
|
||||
let (num, color) = game.move_number(node).unwrap_or((0, Color::White));
|
||||
let san = game.game_move(node).map(|m| m.san.as_str()).unwrap_or("?");
|
||||
let (sym, sym_color) = move_glyph(nd.nags());
|
||||
let label = match (color, need_number) {
|
||||
(Color::White, _) => format!("{num}.{san}{sym}"),
|
||||
(Color::Black, true) => format!("{num}…{san}{sym}"),
|
||||
(Color::Black, false) => format!("{san}{sym}"),
|
||||
};
|
||||
need_number = false;
|
||||
let current = node == n.cursor;
|
||||
let mut text = RichText::new(label).size(15.0);
|
||||
if let Some(c) = sym_color
|
||||
&& !current
|
||||
{
|
||||
text = text.color(c);
|
||||
}
|
||||
// Same strong highlight as the main-line table, so the current move is visible inside text.
|
||||
let button = if current {
|
||||
let sel = ui.visuals().selection;
|
||||
egui::Button::new(text.color(sel.stroke.color).strong())
|
||||
.fill(sel.bg_fill)
|
||||
.stroke(egui::Stroke::new(1.0, sel.stroke.color))
|
||||
} else {
|
||||
egui::Button::new(text).frame_when_inactive(false)
|
||||
};
|
||||
let resp = ui.add(button);
|
||||
handle_move_response(ui, &resp, n, node, out);
|
||||
|
||||
let after = comment_text(nd.comments_after());
|
||||
if !after.is_empty() {
|
||||
ui.label(RichText::new(after).color(comment_color(ui)));
|
||||
need_number = true;
|
||||
}
|
||||
for u in nd.unparsed() {
|
||||
ui.label(
|
||||
RichText::new(u)
|
||||
.monospace()
|
||||
.color(ui.visuals().warn_fg_color),
|
||||
);
|
||||
}
|
||||
// Alternatives to this move are printed right after it (PGN order),
|
||||
// except for the line's own first move whose siblings belong to the outer level.
|
||||
if node != first
|
||||
&& let Some(parent) = game.parent(node)
|
||||
{
|
||||
for &v in game.variations(parent) {
|
||||
ui.label(RichText::new("(").weak());
|
||||
inline_line(ui, n, v, out);
|
||||
ui.label(RichText::new(")").weak());
|
||||
need_number = true;
|
||||
}
|
||||
}
|
||||
match game.main_child(node) {
|
||||
Some(next) => node = next,
|
||||
None => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
156
apps/desktop/src/settings.rs
Normal file
156
apps/desktop/src/settings.rs
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
//! 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>,
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Settings {
|
||||
pub piece_set: PieceSet,
|
||||
pub board_theme: BoardThemeId,
|
||||
pub show_coords: bool,
|
||||
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>,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
piece_set: PieceSet::default(),
|
||||
board_theme: BoardThemeId::default(),
|
||||
show_coords: true,
|
||||
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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
pub fn config_dir() -> Option<PathBuf> {
|
||||
directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin")
|
||||
.map(|d| d.config_dir().to_path_buf())
|
||||
}
|
||||
|
||||
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::default();
|
||||
};
|
||||
migrate_legacy_config(&path);
|
||||
match std::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(_) => 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))
|
||||
}
|
||||
|
||||
pub fn touch_database(&mut self, path: &Path) {
|
||||
self.databases.retain(|p| p != path);
|
||||
self.databases.insert(0, path.to_path_buf());
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies settings of the pre-rename build (`chessbase-linux`) once, if the new file is absent.
|
||||
fn migrate_legacy_config(new_file: &Path) {
|
||||
if new_file.exists() {
|
||||
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<()> {
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let tmp = path.with_extension(format!("tmp{}", std::process::id()));
|
||||
std::fs::write(&tmp, bytes)?;
|
||||
std::fs::rename(&tmp, path).inspect_err(|_| {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
})
|
||||
}
|
||||
296
apps/desktop/src/settings_ui.rs
Normal file
296
apps/desktop/src/settings_ui.rs
Normal file
|
|
@ -0,0 +1,296 @@
|
|||
//! Settings window: engines, board & pieces, sound, interface.
|
||||
|
||||
use crate::i18n::{Lang, tr};
|
||||
use egui::{RichText, Sense, Ui, vec2};
|
||||
use shakmaty::{Color, Piece, Role};
|
||||
|
||||
use crate::assets::{BoardThemeId, PieceSet, SoundSet};
|
||||
use crate::settings::Settings;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum Tab {
|
||||
#[default]
|
||||
Engines,
|
||||
Board,
|
||||
Sound,
|
||||
Interface,
|
||||
}
|
||||
|
||||
pub enum SettingsAction {
|
||||
AddEngine,
|
||||
TestSound,
|
||||
/// The active engine (or its options) changed; a running analysis should restart.
|
||||
EngineChanged,
|
||||
}
|
||||
|
||||
pub struct SettingsWindow {
|
||||
pub open: bool,
|
||||
pub tab: Tab,
|
||||
pub checking_engine: bool,
|
||||
}
|
||||
|
||||
impl SettingsWindow {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
open: false,
|
||||
tab: Tab::default(),
|
||||
checking_engine: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns actions and whether settings changed (to be saved).
|
||||
pub fn show(&mut self, ctx: &egui::Context, s: &mut Settings) -> (Vec<SettingsAction>, bool) {
|
||||
let mut actions = Vec::new();
|
||||
let mut changed = false;
|
||||
let mut open = self.open;
|
||||
egui::Window::new(tr("Settings"))
|
||||
.open(&mut open)
|
||||
.default_size(vec2(560.0, 680.0))
|
||||
// Open at the right edge so the board stays visible for live preview.
|
||||
.pivot(egui::Align2::RIGHT_TOP)
|
||||
.default_pos(ctx.content_rect().right_top() + vec2(-16.0, 60.0))
|
||||
.collapsible(false)
|
||||
.show(ctx, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.selectable_value(&mut self.tab, Tab::Engines, tr("Engines"));
|
||||
ui.selectable_value(&mut self.tab, Tab::Board, tr("Board & pieces"));
|
||||
ui.selectable_value(&mut self.tab, Tab::Sound, tr("Sound"));
|
||||
ui.selectable_value(&mut self.tab, Tab::Interface, tr("Interface"));
|
||||
});
|
||||
ui.separator();
|
||||
egui::ScrollArea::vertical().show(ui, |ui| match self.tab {
|
||||
Tab::Engines => self.engines(ui, s, &mut actions, &mut changed),
|
||||
Tab::Board => board_tab(ui, s, &mut changed),
|
||||
Tab::Sound => sound_tab(ui, s, &mut actions, &mut changed),
|
||||
Tab::Interface => {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Language:"));
|
||||
egui::ComboBox::from_id_salt("language")
|
||||
.selected_text(s.language.label())
|
||||
.show_ui(ui, |ui| {
|
||||
for lang in Lang::ALL {
|
||||
if ui
|
||||
.selectable_value(&mut s.language, lang, lang.label())
|
||||
.changed()
|
||||
{
|
||||
crate::i18n::set_lang(lang);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Theme:"));
|
||||
changed |= ui
|
||||
.selectable_value(&mut s.dark_mode, true, tr("Dark"))
|
||||
.changed();
|
||||
changed |= ui
|
||||
.selectable_value(&mut s.dark_mode, false, tr("Light"))
|
||||
.changed();
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
self.open = open;
|
||||
(actions, changed)
|
||||
}
|
||||
|
||||
fn engines(
|
||||
&mut self,
|
||||
ui: &mut Ui,
|
||||
s: &mut Settings,
|
||||
actions: &mut Vec<SettingsAction>,
|
||||
changed: &mut bool,
|
||||
) {
|
||||
ui.label(
|
||||
RichText::new(tr("UCI engines. The active one is used for game analysis. Time, lines, threads and memory are set with ⚙ in the analysis panel.")).weak(),
|
||||
);
|
||||
ui.add_space(6.0);
|
||||
let mut remove = None;
|
||||
for i in 0..s.engines.len() {
|
||||
let active = s.active_engine == Some(i);
|
||||
egui::Frame::group(ui.style()).show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.horizontal(|ui| {
|
||||
if ui
|
||||
.radio(active, "")
|
||||
.on_hover_text(tr("Make active"))
|
||||
.clicked()
|
||||
&& !active
|
||||
{
|
||||
s.active_engine = Some(i);
|
||||
*changed = true;
|
||||
actions.push(SettingsAction::EngineChanged);
|
||||
}
|
||||
let e = &mut s.engines[i];
|
||||
*changed |= ui
|
||||
.add(egui::TextEdit::singleline(&mut e.name).desired_width(220.0))
|
||||
.changed();
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui
|
||||
.button("🗑")
|
||||
.on_hover_text(tr("Remove from list"))
|
||||
.clicked()
|
||||
{
|
||||
remove = Some(i);
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.label(
|
||||
RichText::new(s.engines[i].path.display().to_string())
|
||||
.small()
|
||||
.weak(),
|
||||
);
|
||||
});
|
||||
}
|
||||
if let Some(i) = remove {
|
||||
s.engines.remove(i);
|
||||
s.active_engine = match s.active_engine {
|
||||
Some(a) if a == i => (!s.engines.is_empty()).then_some(0),
|
||||
Some(a) if a > i => Some(a - 1),
|
||||
a => a,
|
||||
};
|
||||
*changed = true;
|
||||
actions.push(SettingsAction::EngineChanged);
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
ui.horizontal(|ui| {
|
||||
if ui
|
||||
.add_enabled(
|
||||
!self.checking_engine,
|
||||
egui::Button::new(tr("+ Add engine…")),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
actions.push(SettingsAction::AddEngine);
|
||||
}
|
||||
if self.checking_engine {
|
||||
ui.spinner();
|
||||
ui.label(tr("Checking engine…"));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn board_tab(ui: &mut Ui, s: &mut Settings, changed: &mut bool) {
|
||||
ui.label(RichText::new(tr("Piece set")).strong());
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for set in PieceSet::ALL {
|
||||
let selected = s.piece_set == set;
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(110.0, 64.0), Sense::click());
|
||||
let v = ui.visuals();
|
||||
let fill = if selected {
|
||||
v.selection.bg_fill
|
||||
} else if resp.hovered() {
|
||||
v.widgets.hovered.weak_bg_fill
|
||||
} else {
|
||||
v.faint_bg_color
|
||||
};
|
||||
ui.painter().rect_filled(rect, 6.0, fill);
|
||||
let size = 44.0;
|
||||
let board = s.board_theme.theme();
|
||||
for (k, role) in [Role::Knight, Role::Queen].into_iter().enumerate() {
|
||||
let color = if k == 0 { Color::White } else { Color::Black };
|
||||
let r = egui::Rect::from_min_size(
|
||||
rect.left_top() + vec2(8.0 + k as f32 * 48.0, 2.0),
|
||||
vec2(size, size),
|
||||
);
|
||||
// Preview on the current board colours so dark sets stay readable.
|
||||
let square = if k == 0 { board.light } else { board.dark };
|
||||
ui.painter().rect_filled(r, 3.0, square);
|
||||
set.paint(ui, Piece { color, role }, r);
|
||||
}
|
||||
ui.painter().text(
|
||||
rect.center_bottom() - vec2(0.0, 4.0),
|
||||
egui::Align2::CENTER_BOTTOM,
|
||||
set.name(),
|
||||
egui::FontId::proportional(12.0),
|
||||
v.text_color(),
|
||||
);
|
||||
if resp.clicked() {
|
||||
s.piece_set = set;
|
||||
*changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
ui.label(RichText::new(tr("Board")).strong());
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for id in BoardThemeId::ALL {
|
||||
let t = id.theme();
|
||||
let selected = s.board_theme == id;
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(64.0, 64.0), Sense::click());
|
||||
let sq = rect.width() / 2.0;
|
||||
if let Some(uri) = t.texture {
|
||||
// A quarter of the full-board image = 2×2 squares, like the flat swatches.
|
||||
egui::Image::new(uri)
|
||||
.uv(egui::Rect::from_min_max(
|
||||
egui::pos2(0.0, 0.75),
|
||||
egui::pos2(0.25, 1.0),
|
||||
))
|
||||
.paint_at(ui, rect);
|
||||
}
|
||||
for (k, c) in [t.light, t.dark, t.dark, t.light]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter(|_| t.texture.is_none())
|
||||
{
|
||||
let r = egui::Rect::from_min_size(
|
||||
rect.min + vec2((k % 2) as f32 * sq, (k / 2) as f32 * sq),
|
||||
vec2(sq, sq),
|
||||
);
|
||||
ui.painter().rect_filled(r, 0.0, c);
|
||||
}
|
||||
if selected {
|
||||
ui.painter().rect_stroke(
|
||||
rect,
|
||||
2.0,
|
||||
egui::Stroke::new(3.0, ui.visuals().selection.bg_fill),
|
||||
egui::StrokeKind::Outside,
|
||||
);
|
||||
}
|
||||
if resp.on_hover_text(id.label()).clicked() {
|
||||
s.board_theme = id;
|
||||
*changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
*changed |= ui
|
||||
.checkbox(&mut s.show_coords, tr("Show coordinates"))
|
||||
.changed();
|
||||
*changed |= ui
|
||||
.checkbox(&mut s.show_best_arrow, tr("Show engine best-move arrows"))
|
||||
.changed();
|
||||
}
|
||||
|
||||
fn sound_tab(ui: &mut Ui, s: &mut Settings, actions: &mut Vec<SettingsAction>, changed: &mut bool) {
|
||||
*changed |= ui
|
||||
.checkbox(&mut s.sound_enabled, tr("Move sounds"))
|
||||
.changed();
|
||||
ui.add_enabled_ui(s.sound_enabled, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Set:"));
|
||||
for set in SoundSet::ALL {
|
||||
if ui
|
||||
.selectable_value(&mut s.sound_set, set, set.label())
|
||||
.changed()
|
||||
{
|
||||
*changed = true;
|
||||
actions.push(SettingsAction::TestSound);
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Volume:"));
|
||||
let r = ui.add(egui::Slider::new(&mut s.volume, 0.0..=1.0).show_value(false));
|
||||
*changed |= r.changed();
|
||||
if r.drag_stopped() {
|
||||
actions.push(SettingsAction::TestSound);
|
||||
}
|
||||
if ui.button(tr("▶ Test")).clicked() {
|
||||
actions.push(SettingsAction::TestSound);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
52
apps/desktop/src/sound.rs
Normal file
52
apps/desktop/src/sound.rs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
//! Sound playback on a dedicated thread; missing audio devices are tolerated silently.
|
||||
|
||||
use std::io::Cursor;
|
||||
use std::sync::mpsc::{Sender, channel};
|
||||
|
||||
use crate::assets::{Sound, SoundSet, sound_bytes};
|
||||
|
||||
pub struct SoundPlayer {
|
||||
tx: Option<Sender<(SoundSet, Sound, f32)>>,
|
||||
}
|
||||
|
||||
impl SoundPlayer {
|
||||
pub fn new() -> Self {
|
||||
let (tx, rx) = channel::<(SoundSet, Sound, f32)>();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("sound".into())
|
||||
.spawn(move || {
|
||||
let sink = match rodio::DeviceSinkBuilder::open_default_sink() {
|
||||
Ok(mut s) => {
|
||||
s.log_on_drop(false);
|
||||
s
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("sound disabled: {e}");
|
||||
// Drain so senders never block; nothing is played.
|
||||
for _ in rx {}
|
||||
return;
|
||||
}
|
||||
};
|
||||
for (set, sound, volume) in rx {
|
||||
let Ok(decoder) =
|
||||
rodio::Decoder::try_from(Cursor::new(sound_bytes(set, sound)))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let player = rodio::Player::connect_new(sink.mixer());
|
||||
player.set_volume(volume);
|
||||
player.append(decoder);
|
||||
player.detach();
|
||||
}
|
||||
});
|
||||
Self {
|
||||
tx: spawned.ok().map(|_| tx),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn play(&self, set: SoundSet, sound: Sound, volume: f32) {
|
||||
if let Some(tx) = &self.tx {
|
||||
let _ = tx.send((set, sound, volume));
|
||||
}
|
||||
}
|
||||
}
|
||||
26
apps/desktop/src/widgets.rs
Normal file
26
apps/desktop/src/widgets.rs
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
//! Small shared widgets.
|
||||
|
||||
use crate::i18n::tr;
|
||||
use egui::{Color32, Sense, Stroke, Ui, vec2};
|
||||
|
||||
/// Window close button (the app runs undecorated under tiling compositors).
|
||||
pub fn close_button(ui: &mut Ui) -> egui::Response {
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(32.0, 28.0), Sense::click());
|
||||
if resp.hovered() {
|
||||
ui.painter()
|
||||
.rect_filled(rect, 4.0, Color32::from_rgb(0xc4, 0x2b, 0x1c));
|
||||
}
|
||||
let color = if resp.hovered() {
|
||||
Color32::WHITE
|
||||
} else {
|
||||
ui.visuals().text_color()
|
||||
};
|
||||
let c = rect.center();
|
||||
let d = 6.0;
|
||||
let stroke = Stroke::new(1.6, color);
|
||||
ui.painter()
|
||||
.line_segment([c + vec2(-d, -d), c + vec2(d, d)], stroke);
|
||||
ui.painter()
|
||||
.line_segment([c + vec2(-d, d), c + vec2(d, -d)], stroke);
|
||||
resp.on_hover_text(tr("Close the application"))
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue