From d92d93fc1437ae84e01a3889368674e499045779 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Wed, 21 Oct 2026 21:18:53 +0300 Subject: [PATCH] Move notation: Latin letters, figurines or the interface language's letters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Settings › Board & pieces: Nf3, ♘f3 as on Lichess, or Кр Ф Л С К (German K D T L S, French R D T F C, Spanish and Italian R D T A C; in English the Latin letters), with a sample per option and a line of a game. Only the shown label changes (san::show): the game, PGN, copied games, the analysis written into a game, the reference cache and every comparison stay Latin SAN. Applied in the move list, engine lines, the reference tab, board search and the analysis report. The figurines are egui's chess glyphs cut out to a 4.7 KB font, a little smaller and on the baseline. Latin remains the default. Reviewed by the designer and the tester agents. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 + THIRD_PARTY_NOTICES.md | 2 + apps/desktop/assets/fonts/figurines.ttf | Bin 0 -> 4764 bytes apps/desktop/src/app.rs | 1 + apps/desktop/src/assets.rs | 19 +++ apps/desktop/src/board_search.rs | 13 +- apps/desktop/src/game_view.rs | 1 + apps/desktop/src/i18n.rs | 65 ++++++++ apps/desktop/src/main.rs | 1 + apps/desktop/src/notation.rs | 3 + apps/desktop/src/reference.rs | 16 +- apps/desktop/src/review.rs | 3 +- apps/desktop/src/san.rs | 192 ++++++++++++++++++++++++ apps/desktop/src/settings.rs | 3 + apps/desktop/src/settings_ui.rs | 88 +++++++++++ docs/dev/desktop.md | 1 + 16 files changed, 402 insertions(+), 11 deletions(-) create mode 100644 apps/desktop/assets/fonts/figurines.ttf create mode 100644 apps/desktop/src/san.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 321c7c5..4a55a44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https ## [Unreleased] +- Move notation (Settings › Board & pieces): Latin letters (Nf3), figurines as on Lichess + (♘f3), or the piece letters of the interface language — Russian Кр Ф Л С К, German + K D T L S, French R D T F C, Spanish and Italian R D T A C. It applies to the move list, + engine lines, the reference tab, board search and the analysis report; PGN files and + copied games always stay in K Q R B N. Latin remains the default. - Translation of game comments: when a game's comments are in another language, ChessPenguin offers to translate them into yours. Sign in with your ChatGPT Plus or Pro subscription (no key), or use an API key — DeepSeek, OpenAI, Google Gemini — or a model on this computer diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 8f39928..5bd6232 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -101,3 +101,5 @@ egui's bundled fonts are part of the program: Ubuntu Light (Ubuntu Font Licence (MIT and Bitstream Vera licence), Noto Emoji (SIL OFL 1.1), emoji-icon-font (MIT). Three evaluation signs (⩲ ⩱ ⌓) come from Noto Sans Math (Copyright 2022 Google LLC, SIL OFL 1.1), cut down to those glyphs: `apps/desktop/assets/fonts/NotoSansMath-nag.ttf`, licence beside it. +The figurines of the move notation (♔♕♖♗♘) are the five chess glyphs of egui's +emoji-icon-font (MIT), cut out to `apps/desktop/assets/fonts/figurines.ttf`. diff --git a/apps/desktop/assets/fonts/figurines.ttf b/apps/desktop/assets/fonts/figurines.ttf new file mode 100644 index 0000000000000000000000000000000000000000..dbc3e1b225a296e9645ab575935f01045e0edf13 GIT binary patch literal 4764 zcmZ`-S&SS<8LqCQtNOmDdybvi*|BHiBU$gxuE&mJt)nO>ik$@KP#!{-#JOb07O|CZ zM2ZANARr_NA%S=zL5YAM4iWKy6h9!62gE5JcmWB40P%nn6cmAWm+$YHSsNp|cW1i# zuj8+(@B9A0hFOd;k3Gi(J87;oZT<@WQ+;-$46gDDQgg%=u^J zt=1zbA3!-iefFV^@J{Dzc>D{>;hBwR&aqMS1(e@LdH%_bGpFPWa~bMWe;+${_Nnvm z6IXhk>`bu}+kY3|6<=i;JI21j-m(reX6d|VjSr3wuB|Q(7l(rdZR>HPY!o>ja7Pkv zmt<{R9ImZW)$zg6O4%sI5{GT46;-y190u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?n@^Y1+Sf#|w-nJ4S2zj*cW&(gym zGgEEZUFE4vmtih^j9lL&i zik)F+*%Rz>b{9Lv9%UEUX|};WgiQ1lKA*z-v+PNDw9Kx-fBhQ{x$u83i&^kD`VTWc B*KYs- literal 0 HcmV?d00001 diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 09b10ec..ad285d2 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -735,6 +735,7 @@ impl App { impl eframe::App for App { fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + crate::san::set(self.settings.move_notation); // The window has shown its first frame: this graphics mode works. if ui.ctx().cumulative_frame_nr() >= 1 { crate::graphics::started(); diff --git a/apps/desktop/src/assets.rs b/apps/desktop/src/assets.rs index 658517a..c99ec21 100644 --- a/apps/desktop/src/assets.rs +++ b/apps/desktop/src/assets.rs @@ -162,6 +162,25 @@ pub fn install(ctx: &egui::Context) { "../assets/fonts/NotoSansMath-nag.ttf" ))), ); + // Figurines in move notation (♔♕♖♗♘): a copy of egui's icon glyphs, a little + // smaller and on the baseline (the icons themselves stay as they are). + fonts.font_data.insert( + "figurine".into(), + std::sync::Arc::new( + egui::FontData::from_static(include_bytes!("../assets/fonts/figurines.ttf")).tweak( + egui::FontTweak { + scale: 0.85, + y_offset: -1.0, + ..Default::default() + }, + ), + ), + ); + for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { + if let Some(list) = fonts.families.get_mut(&family) { + list.insert(1, "figurine".into()); + } + } let mono = fonts .families .get(&egui::FontFamily::Monospace) diff --git a/apps/desktop/src/board_search.rs b/apps/desktop/src/board_search.rs index 5e4eeec..84757ef 100644 --- a/apps/desktop/src/board_search.rs +++ b/apps/desktop/src/board_search.rs @@ -160,7 +160,7 @@ impl SearchBoard { for m in &self.line[..i] { pos.play_unchecked(*m); } - Some(move_label(&pos, *self.line.get(i)?, true)) + Some(crate::san::show(&move_label(&pos, *self.line.get(i)?, true)).into_owned()) } /// Text of the position chip: the moves up to 8 half-moves, then "after 14…Nf6". @@ -168,7 +168,10 @@ impl SearchBoard { let moves = self.san_line(self.cursor); let prefix = if self.start_fen.is_some() { "⌂ " } else { "" }; if moves.len() <= 8 { - let text: Vec = moves.into_iter().map(|(s, _)| s).collect(); + let text: Vec = moves + .into_iter() + .map(|(s, _)| crate::san::show(&s).into_owned()) + .collect(); format!("{prefix}{}", text.join(" ")) } else { let last = self.last_label().unwrap_or_default(); @@ -551,7 +554,8 @@ impl SearchBoard { let mut clicked = None; for (label, n) in all { let current = n == self.cursor; - let mut text = RichText::new(label).size(14.0); + let mut text = + RichText::new(crate::san::show(&label).into_owned()).size(14.0); if n > self.cursor { text = text.weak(); } @@ -704,8 +708,9 @@ pub fn continuation_row( .to_move(pos) .map(|m| move_label(pos, m, true)) .unwrap_or_else(|_| stat.san.clone()); + let label = crate::san::show(&label); text(x, &label, text_color, egui::Align2::LEFT_CENTER); - x += 70.0; + x += 78.0; let games = crate::large_db::grouped(stat.tally.games as usize); if books { text( diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 7f7e33d..a0177ad 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -1023,6 +1023,7 @@ impl GameView { } None => san.clone(), }; + let label = crate::san::show(&label).into_owned(); let selected = self.preview.as_ref().is_some_and(|p| { p.base == base && p.shown == i + 1 && p.san == line.san }); diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index fbd1577..d77b5de 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -1773,6 +1773,70 @@ const ROWS: &[[&str; 6]] = &[ "indonesio", "indonesiano", ], + [ + "Move notation", + "Запись ходов", + "Notation des coups", + "Zugnotation", + "Notación de jugadas", + "Notazione delle mosse", + ], + [ + "Letters (K Q R B N)", + "Латинские буквы (K Q R B N)", + "Lettres anglaises (K Q R B N)", + "Englische Buchstaben (K Q R B N)", + "Letras inglesas (K Q R B N)", + "Lettere inglesi (K Q R B N)", + ], + [ + "Figurines", + "Фигурки", + "Figurines", + "Figurinen", + "Figurines", + "Figurine", + ], + [ + "Interface language letters", + "Русские буквы", + "Lettres françaises", + "Deutsche Buchstaben", + "Letras españolas", + "Lettere italiane", + ], + [ + "International notation, as in PGN files and engine output", + "Международная запись, как в PGN-файлах и у движков", + "Notation internationale, comme dans les fichiers PGN et chez les moteurs", + "Internationale Notation, wie in PGN-Dateien und bei Engines", + "Notación internacional, como en los archivos PGN y en los motores", + "Notazione internazionale, come nei file PGN e nei motori", + ], + [ + "Piece symbols, as on Lichess. They look the same in every language.", + "Значки фигур, как на Lichess. Одинаковы на любом языке.", + "Symboles de pièces, comme sur Lichess. Identiques dans toutes les langues.", + "Figurensymbole wie auf Lichess. In jeder Sprache gleich.", + "Símbolos de piezas, como en Lichess. Iguales en cualquier idioma.", + "Simboli dei pezzi, come su Lichess. Uguali in ogni lingua.", + ], + [ + "Follows the interface language", + "Меняется вместе с языком интерфейса", + "Suit la langue de l’interface", + "Folgt der Sprache der Oberfläche", + "Sigue el idioma de la interfaz", + "Segue la lingua dell’interfaccia", + ], + [ + "Only how moves look on screen. PGN files and copied games always use K Q R B N.", + "Только вид на экране. В PGN и при копировании всегда K Q R B N.", + "Seulement l’affichage. Les fichiers PGN et les parties copiées utilisent toujours K Q R B N.", + "Nur die Anzeige. PGN-Dateien und kopierte Partien verwenden immer K Q R B N.", + "Solo cambia la vista. Los archivos PGN y las partidas copiadas siempre usan K Q R B N.", + "Cambia solo la visualizzazione. I file PGN e le partite copiate usano sempre K Q R B N.", + ], [ "Piece animation", "Анимация фигур", @@ -5816,6 +5880,7 @@ mod tests { include_str!("translate.rs"), include_str!("translate_ui.rs"), include_str!("chatgpt.rs"), + include_str!("san.rs"), ]; let mut missing = Vec::new(); let mut found = 0; diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index 4ddd287..6e327ad 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -22,6 +22,7 @@ mod online_ui; mod reference; mod report; mod review; +mod san; mod settings; mod settings_ui; mod sound; diff --git a/apps/desktop/src/notation.rs b/apps/desktop/src/notation.rs index ccf5d4f..bfef7c0 100644 --- a/apps/desktop/src/notation.rs +++ b/apps/desktop/src/notation.rs @@ -210,6 +210,7 @@ fn paint_move_cell( } let node = game.node(id); let san = game.game_move(id).map(|m| m.san.as_str()).unwrap_or("?"); + let san = crate::san::show(san); let (sym, color) = node .map(|n| move_glyph(n.nags())) .unwrap_or((String::new(), None)); @@ -297,6 +298,7 @@ fn mark_block(ui: &mut Ui, n: &Notation, id: NodeId, mark: &Mark, out: &mut Nota } None => san.clone(), }; + let label = crate::san::show(&label).into_owned(); let text = RichText::new(label).size(14.5); let current = shown == Some(i + 1); let button = if current { @@ -524,6 +526,7 @@ fn inline_line(ui: &mut Ui, n: &Notation, first: NodeId, out: &mut NotationRespo } 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 san = crate::san::show(san); let (sym, sym_color) = move_glyph(nd.nags()); let label = match (color, need_number) { (Color::White, _) => format!("{num}.{san}{sym}"), diff --git a/apps/desktop/src/reference.rs b/apps/desktop/src/reference.rs index 06f8ac8..f269f5e 100644 --- a/apps/desktop/src/reference.rs +++ b/apps/desktop/src/reference.rs @@ -228,15 +228,17 @@ fn node_label(game: &Game, node: NodeId) -> Option { let m = game.game_move(node)?; let before = game.position(game.parent(node)?)?; let n = before.fullmoves().get(); + let san = crate::san::show(&m.san); Some(match before.turn() { - Color::White => format!("{n}.{}", m.san), - Color::Black => format!("{n}…{}", m.san), + Color::White => format!("{n}.{san}"), + Color::Black => format!("{n}…{san}"), }) } /// "5.Nc3" / "5…Nc6". fn move_label(pos: &Chess, m: Move) -> String { let san = shakmaty::san::SanPlus::from_move(pos.clone(), m).to_string(); + let san = crate::san::show(&san); let n = pos.fullmoves().get(); match pos.turn() { Color::White => format!("{n}.{san}"), @@ -341,6 +343,7 @@ fn then_from(game: &Game, node: NodeId, next: Option) -> String { break; }; let n = before.fullmoves().get(); + // Latin here (made in the background, kept): shown through `san::show_line`. out.push(match before.turn() { Color::White => format!("{n}.{}", m.san), Color::Black if k == 0 => format!("{n}…{}", m.san), @@ -1127,7 +1130,7 @@ impl Reference { let width = ui.available_width(); let gap = ui.spacing().item_spacing.x; let show_bar = !books; - let mut used = 86.0 + 64.0 + 44.0 + 3.0 * gap; + let mut used = 96.0 + 64.0 + 44.0 + 3.0 * gap; if show_bar { used += 86.0 + gap; } @@ -1151,7 +1154,8 @@ impl Reference { .max_scroll_height(height) .min_scrolled_height(height) .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) - .column(Column::exact(86.0)) + // "12…Крxe2+" and figurines are wider than Latin letters. + .column(Column::exact(96.0).clip(true)) .column(Column::exact(64.0)) .column(Column::exact(44.0)); if show_bar { @@ -1222,7 +1226,7 @@ impl Reference { .uci .to_move(pos) .map(|m| move_label(pos, m)) - .unwrap_or_else(|_| s.san.clone()), + .unwrap_or_else(|_| crate::san::show(&s.san).into_owned()), // In the start position "ended" are games recorded without moves. None if start => tr("Without moves").to_owned(), None => tr("Game over").to_owned(), @@ -1560,7 +1564,7 @@ impl Reference { } if show_then { row.col(|ui| { - ui.label(&g.then); + ui.label(crate::san::show_line(&g.then)); }); } if show_event { diff --git a/apps/desktop/src/review.rs b/apps/desktop/src/review.rs index 5a7760c..c874988 100644 --- a/apps/desktop/src/review.rs +++ b/apps/desktop/src/review.rs @@ -539,6 +539,7 @@ impl Review { let text = match &mark.best_label { Some(best) => trf( "{judgement}. {best} was best.", + // Written into the game: Latin, as PGN always is. &[("judgement", &name), ("best", best)], ), None => format!("{name}."), @@ -706,7 +707,7 @@ impl Review { let label = if i == 0 { tr("Start position").to_string() } else { - game.move_label(self.line[i]).unwrap_or_default() + crate::san::show(&game.move_label(self.line[i]).unwrap_or_default()).into_owned() }; let eval = self.values[i] .map(Eval::format) diff --git a/apps/desktop/src/san.rs b/apps/desktop/src/san.rs new file mode 100644 index 0000000..a6a9249 --- /dev/null +++ b/apps/desktop/src/san.rs @@ -0,0 +1,192 @@ +//! How moves look on screen (docs/design/move-notation.md): Latin letters, figurines as +//! on Lichess, or the piece letters of the interface language. Only the shown label +//! changes — the game, PGN, the clipboard and everything compared stay Latin SAN. + +use std::borrow::Cow; +use std::sync::atomic::{AtomicU8, Ordering}; + +use serde::{Deserialize, Deserializer, Serialize}; + +use crate::i18n::Lang; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Default)] +#[serde(rename_all = "lowercase")] +pub enum MoveNotation { + /// K Q R B N, as in PGN files and engine output. + #[default] + Latin, + /// ♔ ♕ ♖ ♗ ♘ (one outline style for both colours, no pawn sign). + Figurine, + /// The letters of the interface language (Кр Ф Л С К in Russian); Latin in English. + Local, +} + +/// An unknown value (a newer version) is read as Latin, not as broken settings. +impl<'de> Deserialize<'de> for MoveNotation { + fn deserialize>(d: D) -> Result { + let v = serde_json::Value::deserialize(d)?; + Ok(match v.as_str().unwrap_or("") { + "figurine" => MoveNotation::Figurine, + "local" => MoveNotation::Local, + _ => MoveNotation::Latin, + }) + } +} + +static MODE: AtomicU8 = AtomicU8::new(0); + +/// The notation chosen in the settings (set by the application every frame). +pub fn set(mode: MoveNotation) { + MODE.store(mode as u8, Ordering::Relaxed); +} + +fn mode() -> MoveNotation { + match MODE.load(Ordering::Relaxed) { + 1 => MoveNotation::Figurine, + 2 => MoveNotation::Local, + _ => MoveNotation::Latin, + } +} + +/// King, queen, rook, bishop, knight in a language (`None`: as Latin). +pub fn local_letters(lang: Lang) -> Option<[&'static str; 5]> { + match lang { + Lang::En => None, + Lang::Ru => Some(["Кр", "Ф", "Л", "С", "К"]), + Lang::De => Some(["K", "D", "T", "L", "S"]), + Lang::Fr => Some(["R", "D", "T", "F", "C"]), + Lang::Es | Lang::It => Some(["R", "D", "T", "A", "C"]), + } +} + +fn piece(c: char, mode: MoveNotation, lang: Lang) -> Option<&'static str> { + let i = "KQRBN".find(c)?; + match mode { + MoveNotation::Latin => None, + MoveNotation::Figurine => Some(["♔", "♕", "♖", "♗", "♘"][i]), + MoveNotation::Local => local_letters(lang).map(|l| l[i]), + } +} + +/// A SAN move as shown: the piece letter at the start and after "=" replaced. +pub fn display_san(san: &str, mode: MoveNotation, lang: Lang) -> Cow<'_, str> { + if mode == MoveNotation::Latin || (mode == MoveNotation::Local && lang == Lang::En) { + return Cow::Borrowed(san); + } + let mut out = String::with_capacity(san.len() + 4); + let mut first = true; + let mut after_eq = false; + let mut changed = false; + for c in san.chars() { + match (first || after_eq).then(|| piece(c, mode, lang)).flatten() { + Some(p) => { + out.push_str(p); + changed = true; + } + None => out.push(c), + } + first = false; + after_eq = c == '='; + } + if changed { + Cow::Owned(out) + } else { + Cow::Borrowed(san) + } +} + +/// A label as shown: "12.Nf3", "12…Nf3", "12...Nf3" or "Nf3", in the chosen notation. +pub fn show(label: &str) -> Cow<'_, str> { + show_in(label, mode(), crate::i18n::current()) +} + +/// A line of labels separated by spaces ("5.Nc3 a6 6.Be2"), as shown. +pub fn show_line(line: &str) -> String { + line.split(' ') + .map(|w| show(w)) + .collect::>() + .join(" ") +} + +pub fn show_in(label: &str, mode: MoveNotation, lang: Lang) -> Cow<'_, str> { + let number = label + .char_indices() + .find(|(_, c)| !(c.is_ascii_digit() || matches!(c, '.' | '…' | ' '))) + .map_or(label.len(), |(i, _)| i); + let (prefix, san) = label.split_at(number); + match display_san(san, mode, lang) { + Cow::Borrowed(_) => Cow::Borrowed(label), + Cow::Owned(s) => Cow::Owned(format!("{prefix}{s}")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_piece_letters_change() { + let f = |s| display_san(s, MoveNotation::Figurine, Lang::Ru).into_owned(); + assert_eq!(f("Nf3"), "♘f3"); + assert_eq!(f("Qxd8+"), "♕xd8+"); + assert_eq!(f("exd8=Q#"), "exd8=♕#"); + assert_eq!(f("e8=N"), "e8=♘"); + assert_eq!(f("O-O-O"), "O-O-O"); + assert_eq!(f("--"), "--"); + assert_eq!(f("Nbd7"), "♘bd7"); + assert_eq!(f("Rxb7"), "♖xb7"); + assert_eq!(f("e4"), "e4"); + let r = |s| display_san(s, MoveNotation::Local, Lang::Ru).into_owned(); + assert_eq!(r("Kxe2+"), "Крxe2+"); + assert_eq!(r("Bb5"), "Сb5"); + assert_eq!(r("a8=Q"), "a8=Ф"); + let de = |s| display_san(s, MoveNotation::Local, Lang::De).into_owned(); + assert_eq!(de("Nf3"), "Sf3"); + assert_eq!(de("Qd1"), "Dd1"); + let fr = |s| display_san(s, MoveNotation::Local, Lang::Fr).into_owned(); + assert_eq!(fr("Kg1"), "Rg1"); + assert_eq!(fr("Rg1"), "Tg1"); + // Applied once, to Latin: a shown label is never shown again. + assert_eq!(show_in("Kg1", MoveNotation::Local, Lang::Fr), "Rg1"); + } + + #[test] + fn latin_and_english_borrow() { + assert!(matches!( + display_san("Nf3", MoveNotation::Latin, Lang::Ru), + Cow::Borrowed(_) + )); + assert!(matches!( + display_san("Nf3", MoveNotation::Local, Lang::En), + Cow::Borrowed(_) + )); + assert!(matches!( + display_san("e4", MoveNotation::Figurine, Lang::Ru), + Cow::Borrowed(_) + )); + } + + #[test] + fn labels_keep_their_numbers() { + let s = |l| show_in(l, MoveNotation::Figurine, Lang::En).into_owned(); + assert_eq!(s("12.Nf3"), "12.♘f3"); + assert_eq!(s("12…Nf6"), "12…♘f6"); + assert_eq!(s("12...Bb4+"), "12...♗b4+"); + assert_eq!(s("Kh1"), "♔h1"); + assert_eq!(s("3.e4"), "3.e4"); + assert_eq!(s("12. Nf3"), "12. ♘f3"); + assert_eq!(s("12... Nf6"), "12... ♘f6"); + } + + #[test] + fn settings_values() { + let v: MoveNotation = serde_json::from_str("\"figurine\"").unwrap(); + assert_eq!(v, MoveNotation::Figurine); + let v: MoveNotation = serde_json::from_str("\"klingon\"").unwrap(); + assert_eq!(v, MoveNotation::Latin); + assert_eq!( + serde_json::to_string(&MoveNotation::Local).unwrap(), + "\"local\"" + ); + } +} diff --git a/apps/desktop/src/settings.rs b/apps/desktop/src/settings.rs index 5d6d90f..cd1070d 100644 --- a/apps/desktop/src/settings.rs +++ b/apps/desktop/src/settings.rs @@ -102,6 +102,8 @@ pub struct Settings { pub show_coords: bool, /// How fast moves slide on the board. pub animation: Animation, + /// How moves are shown: Latin letters, figurines or the interface language's letters. + pub move_notation: crate::san::MoveNotation, /// Translating game comments (docs/design/translation.md). pub translation: crate::translate::TranslationSettings, pub sound_enabled: bool, @@ -170,6 +172,7 @@ impl Default for Settings { board_theme: BoardThemeId::default(), show_coords: true, animation: Animation::default(), + move_notation: Default::default(), translation: Default::default(), sound_enabled: true, sound_set: SoundSet::default(), diff --git a/apps/desktop/src/settings_ui.rs b/apps/desktop/src/settings_ui.rs index 2595d9d..3ab2de7 100644 --- a/apps/desktop/src/settings_ui.rs +++ b/apps/desktop/src/settings_ui.rs @@ -475,6 +475,8 @@ fn board_tab(ui: &mut Ui, s: &mut Settings, changed: &mut bool) { } }); ui.add_space(8.0); + notation_section(ui, s, changed); + ui.add_space(8.0); ui.label(RichText::new(tr("Board")).strong()); ui.horizontal_wrapped(|ui| { for id in BoardThemeId::ALL { @@ -533,6 +535,92 @@ fn board_tab(ui: &mut Ui, s: &mut Settings, changed: &mut bool) { .changed(); } +/// "Move notation": Latin letters, figurines, the interface language's letters, with a +/// sample for each and a line of a game as it will look. +fn notation_section(ui: &mut Ui, s: &mut Settings, changed: &mut bool) { + use crate::san::{MoveNotation, local_letters, show_in}; + let lang = crate::i18n::current(); + ui.label(RichText::new(tr("Move notation")).strong()); + // In English the language's letters are the Latin ones: that option is not shown. + let local = local_letters(lang); + let shown = if s.move_notation == MoveNotation::Local && local.is_none() { + MoveNotation::Latin + } else { + s.move_notation + }; + let sample = |m: MoveNotation| { + ["Nf3", "Qxd8+", "e8=Q"] + .map(|x| show_in(x, m, lang).into_owned()) + .join(" ") + }; + let mut options = vec![ + ( + MoveNotation::Latin, + tr("Letters (K Q R B N)").to_owned(), + tr("International notation, as in PGN files and engine output"), + ), + ( + MoveNotation::Figurine, + tr("Figurines").to_owned(), + tr("Piece symbols, as on Lichess. They look the same in every language."), + ), + ]; + if let Some(l) = local { + options.push(( + MoveNotation::Local, + format!("{} ({})", tr("Interface language letters"), l.join(" ")), + tr("Follows the interface language"), + )); + } + egui::Grid::new("move_notation") + .num_columns(2) + .spacing(vec2(24.0, 4.0)) + .show(ui, |ui| { + for (mode, label, tip) in options { + let r = ui.radio(shown == mode, label).on_hover_text(tip); + let r2 = ui + .add( + egui::Label::new(RichText::new(sample(mode)).size(15.0)) + .sense(Sense::click()), + ) + .on_hover_text(tip); + if (r.clicked() || r2.clicked()) && s.move_notation != mode { + s.move_notation = mode; + *changed = true; + } + ui.end_row(); + } + }); + // A line of a game, the current move highlighted as in the notation. + let line = "1.e4 e5 2.Nf3 Nc6 3.Bb5 a6 4.Ba4 Nf6 5.O-O Be7 6.Re1 b5"; + let mode = shown; + egui::Frame::group(ui.style()).show(ui, |ui| { + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + for word in line.split(' ') { + let text = RichText::new(show_in(word, mode, lang).into_owned()).size(16.0); + if word == "3.Bb5" { + let sel = ui.visuals().selection; + let galley = egui::Label::new(text.color(sel.stroke.color).strong()); + egui::Frame::new() + .fill(sel.bg_fill) + .corner_radius(2.0) + .inner_margin(egui::Margin::symmetric(3, 0)) + .show(ui, |ui| ui.add(galley)); + } else { + ui.label(text); + } + } + }); + }); + ui.label( + RichText::new(tr( + "Only how moves look on screen. PGN files and copied games always use K Q R B N.", + )) + .weak(), + ); +} + const SITE: &str = "https://chess.vrubel.xyz"; const REPO: &str = "https://github.com/vrubelroman/chessPenguin"; const EMAIL: &str = "vrubelroman@gmail.com"; diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index bb342e3..db5213d 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -13,6 +13,7 @@ egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `i | `update_ui.rs` | Окно «Обновление ChessPenguin»: «Вышла версия X · У вас Y · Что нового», один сценарий на вид установки с главной кнопкой, «Не сейчас», «Пропустить эту версию» (`skipped_version`); скачивание с прогрессом (окно можно закрыть, кнопка у «Настроек» показывает проценты); итог: «Перезапустить сейчас / Позже», шаги для macOS с «Закрыть ChessPenguin», команда с «Копировать», «Открыть папку» и шагами для пакетов; ошибки понятными словами, исходный текст — в «Подробностях». Перезапуск: `request_close(QuitApp)`, в `finish_close` настройки сохраняются, новый процесс запускается без переменных `CP_*`; отмена вопроса о партиях отменяет и перезапуск | | `online.rs` | Онлайн-партии: проба обоих API при старте (повтор через 5 минут), поиск ника, загрузка в PGN-базу в `/online/` с файлом состояния `.online.json` (аккаунты базы, отметки Lichess `since`/незаконченные партии и Chess.com месяц/время, число партий, длина файла и его последние байты — хвост после аварии обрезается), одна загрузка на файл (`Claim`), имена `Ник (Lichess + Chess.com).pgn` или `A (Lichess) + B (Chess.com).pgn`. Живой тест `online_live` (ник — только через `CP_ONLINE_NICK`). | | `online_ui.rs` | Окно «Партии с Lichess и Chess.com»: ник игрока (любого: свой, ученика, соперника; другой ник для Chess.com), площадки, ответившие на пробу, «Найти» (Enter), найденное, «Объединить партии с обоих сайтов в одну базу» (по умолчанию), строка «В базу …» (`targets`: база, где эти аккаунты уже есть, иначе новая), «Скачать», прогресс по сайту (Lichess: из N, оставшееся время; Chess.com: месяц i из n), «Остановить», итоги с «Открыть базу» / «Попробовать снова» и «Подробностями»; при закрытом окне итог — тостом; `stop_all` при выходе. | +| `san.rs` | Вид ходов на экране (docs/design/move-notation.md): `MoveNotation` (латиница / фигурки ♔♕♖♗♘ / буквы языка интерфейса, в английском — латиница), `display_san` меняет только букву фигуры в начале хода и после «=», `show(label)` сохраняет номер хода; режим ставится каждый кадр из настроек (`set`). Данные партии, PGN, буфер, сравнения — всегда латинский SAN | | `translate.rs` | Перевод комментариев (docs/design/translation.md): подключения (`Connection`: ChatGPT / ключ API; `Preset`: DeepSeek, OpenAI, Gemini, Ollama, LM Studio, свой адрес), `TranslationSettings` в настройках, ключи и токены — в `credentials.json` (0600) рядом с настройками; `comments()` — тексты комментариев партии как в нотации (без команд `[%…]`), `plan()` — что переводить (whatlang, короткие наследуют язык партии, предлагаем от 3 комментариев или 150 букв), инструкция модели со словарём терминов, проверка ответа `same_moves` (те же ходы и поля), пачки по 5 000 символов, `Job` в фоне с событиями `Done / Bad / Failed / Finished`, повтор с паузами при 429 / 5xx (`WAITING`), кэш `/translations/<язык>.jsonl` по sha256 текста | | `chatgpt.rs` | Вход через ChatGPT (оплата из подписки, preview OpenAI для открытых локальных программ): OAuth с PKCE в системном браузере и слушатель на `127.0.0.1` (`/auth/callback`), первая регистрация `dynamic_agent_client`, выданный `client_id` и `host_id` (`urn:uuid`) — в настройках; обновление токенов по одному, ротация; выход с отзывом через `revocation_endpoint`; Responses API потоком (`store: false`), разбор ошибок `subscription_sharing_*` | | `translate_ui.rs` | Интерфейс перевода (docs/design/translation-ui.md): `GameTranslation` у каждой партии — строка над нотацией со всеми состояниями, пометки ⇄ / ⋯ / ⚠ для нотации, автозапуск после первого согласия (порог 60 000 символов), переключатель «Оригинал / Перевод» (Ctrl+Shift+T); `Hub` в приложении — окно «Как переводить?», согласие один раз на сервис, ожидание входа в браузере, проверка подключения фразой «The knight is strong on d5.», вкладка Настройки › Перевод |