From 112fee89a574e0114b6077668b9a188448f12dab Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 13:55:54 +0300 Subject: [PATCH] task 43: arrows/circles hint above the notation, sign by moves with [%cal]/[%csl], apply_shape tests, CP_HINT_RESET --- apps/desktop/src/app.rs | 5 + apps/desktop/src/board.rs | 67 +++++ apps/desktop/src/game_view.rs | 393 +++++++++++++++++++++++++++++- apps/desktop/src/i18n.rs | 77 ++++++ apps/desktop/src/notation.rs | 201 ++++++++++++++- apps/desktop/src/opening_lines.rs | 1 + apps/desktop/src/settings.rs | 74 ++++++ apps/desktop/src/settings_ui.rs | 7 + 8 files changed, 817 insertions(+), 8 deletions(-) diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index f820a21..2d866bd 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -443,6 +443,10 @@ impl App { if let Ok(dark) = std::env::var("CP_DARK") { settings.dark_mode = dark != "0"; } + // Dev hook (screenshots, tests): `CP_HINT_RESET=1` shows the one-time hints anew. + if std::env::var("CP_HINT_RESET").as_deref() == Ok("1") { + settings.hints = Default::default(); + } } // Before the samples, which are named in this language. crate::i18n::set_lang(settings.language); @@ -4146,6 +4150,7 @@ impl eframe::App for App { self.settings_ui.tab = Tab::Translation; } GameAction::Toast(m) => self.toast(&ctx, m), + GameAction::HintsChanged => self.settings_dirty = true, GameAction::PauseLive => { if self.analysis.is_on() { self.analysis.stop(); diff --git a/apps/desktop/src/board.rs b/apps/desktop/src/board.rs index 9629a34..3081f3a 100644 --- a/apps/desktop/src/board.rs +++ b/apps/desktop/src/board.rs @@ -1170,6 +1170,73 @@ mod tests { assert!(state.temporary_shapes.is_empty()); } + /// A right-button drag in the analysis of a game: one arrow, handed over once, in + /// the colour of the modifiers held as the button is let go. + #[test] + fn analysis_arrow_is_drawn_by_a_right_drag() { + let ctx = egui::Context::default(); + let pos = Chess::default(); + let mut state = BoardState::default(); + let from = egui::pos2(225.0, 325.0); + let to = egui::pos2(225.0, 225.0); + let shift_alt = egui::Modifiers::SHIFT | egui::Modifiers::ALT; + board_frame(&ctx, &mut state, &pos, 0.0, Vec::new(), false); + board_frame( + &ctx, + &mut state, + &pos, + 0.1, + vec![ + egui::Event::PointerMoved(from), + egui::Event::PointerButton { + pos: from, + button: egui::PointerButton::Secondary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }, + ], + false, + ); + board_frame( + &ctx, + &mut state, + &pos, + 0.2, + vec![egui::Event::PointerMoved(to)], + false, + ); + assert!( + state.take_shape().is_none(), + "nothing before the button is let go" + ); + board_frame( + &ctx, + &mut state, + &pos, + 0.3, + vec![ + egui::Event::ModifiersChanged(shift_alt), + egui::Event::PointerButton { + pos: to, + button: egui::PointerButton::Secondary, + pressed: false, + modifiers: shift_alt, + }, + ], + false, + ); + assert!(state.temporary_shapes.is_empty()); + assert_eq!( + state.take_shape(), + Some(Drawn::Arrow( + chess_core::ShapeColor::Yellow, + "e2".parse().unwrap(), + "e4".parse().unwrap() + )) + ); + assert!(state.take_shape().is_none()); + } + #[test] fn analysis_shapes_remain_one_shot_events() { let ctx = egui::Context::default(); diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 500e9dc..787e0f1 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -15,10 +15,12 @@ use crate::analysis::{self, Analysis, PvLine, Status}; use crate::assets::Sound; use crate::board::{self, Arrow, BoardState, BoardView}; use crate::notation::{ - CommentEditor, EditorOutcome, MOVE_NAGS, Notation, NotationCommand, Slot, toggle_nag, + CommentEditor, EditorOutcome, MOVE_NAGS, Notation, NotationCommand, ShapeCount, Slot, + toggle_nag, }; use crate::review::{ReportAction, Review}; use crate::settings::Settings; +use std::collections::HashMap; /// Where an opened game came from (to return to the same library row, to save into). #[derive(Clone, Debug)] @@ -112,6 +114,14 @@ pub struct GameView { translation: crate::translate_ui::GameTranslation, /// "Translate comments" was chosen (menu, Ctrl+Shift+T): done once the settings are at hand. translate_now: bool, + /// The moves whose comments draw on the board, for the notation's sign; by the + /// revision of the game they were counted at. + shape_counts: Option<(u64, HashMap)>, + /// The hint about drawing arrows above the notation: decided as the notation is + /// first drawn (`None`: not yet). + shapes_hint: Option, + /// An arrow or a circle went into the game on this frame (the hint has done its job). + shape_drawn: bool, } #[derive(Clone, Copy, PartialEq, Eq)] @@ -184,6 +194,8 @@ pub enum GameAction { DownloadPgn, /// Settings → Translation. OpenTranslationSettings, + /// A hint was shown or put away: the settings are to be written. + HintsChanged, } impl GameView { @@ -231,6 +243,9 @@ impl GameView { update: None, translation: Default::default(), translate_now: false, + shape_counts: None, + shapes_hint: None, + shape_drawn: false, } } @@ -665,7 +680,108 @@ impl GameView { } } let comments = chess_core::with_shapes(node.comments_after(), &arrows, &squares); - let _ = self.game.annotate(id, node.nags().to_vec(), comments); + if self + .game + .annotate(id, node.nags().to_vec(), comments) + .is_ok() + { + self.shape_drawn = true; + } + } + + /// The moves with arrows or circles in their comments, counted again after an edit. + fn shape_counts(&mut self) -> &HashMap { + let revision = self.game.revision(); + if self + .shape_counts + .as_ref() + .is_none_or(|(r, _)| *r != revision) + { + self.shape_counts = Some((revision, crate::notation::shape_counts(&self.game))); + } + &self.shape_counts.get_or_insert_default().1 + } + + /// Who this game is among those opened in the session (a hint counts a game once). + fn session_key(&self) -> String { + match &self.source { + Some(s) => format!("{}#{}", s.path.display(), s.index), + None => format!("view#{}", self.serial), + } + } + + /// Whether the hint about drawing on the board stands above the notation + /// (docs/design/tasks-42-43-2026-11-27.md §43.3). Decided once, as the notation is + /// first drawn: only where shapes go into the game, never with the translation strip + /// (then not counted either). Returns whether the hint's settings changed. + fn decide_shapes_hint( + &mut self, + hint: &mut crate::settings::Hint, + seen: &mut std::collections::HashSet, + translating: bool, + ) -> bool { + if self.shapes_hint.is_some() { + return false; + } + let possible = + !translating && self.preview.is_none() && self.play.is_none() && self.train.is_none(); + let key = self.session_key(); + let fresh = !seen.contains(&key); + let show = possible && hint.offer(fresh); + if show { + seen.insert(key); + } + self.shapes_hint = Some(show); + show && fresh + } + + /// The hint's strip: the translation strip's look, closed for good by its ×. + /// Returns whether the hint's settings changed. + fn shapes_hint_strip(&mut self, ui: &mut Ui, hint: &mut crate::settings::Hint) -> bool { + let mut closed = false; + egui::Frame::new() + .fill(ui.visuals().faint_bg_color) + .inner_margin(egui::Margin::symmetric(8, 4)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + let row_h = ui.spacing().interact_size.y; + ui.horizontal_top(|ui| { + let close_w = 22.0 + ui.spacing().item_spacing.x; + ui.allocate_ui_with_layout( + vec2((ui.available_width() - close_w).max(120.0), 0.0), + egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true), + |ui| { + ui.set_min_height(row_h); + ui.add( + egui::Label::new(RichText::new(tr( + "Arrows and circles: drag or click with the right mouse button on the board. They are saved in the game.", + )).weak()) + .wrap(), + ) + .on_hover_text(tr( + "No key — green, Shift — red, Alt — blue, Shift+Alt — yellow. Draw the same one again to remove it. Ctrl+Z undoes.", + )); + }, + ); + ui.allocate_ui_with_layout( + vec2(22.0, row_h), + egui::Layout::left_to_right(egui::Align::Center), + |ui| { + if crate::widgets::small_close_button(ui) + .on_hover_text(tr("Don't show again")) + .clicked() + { + closed = true; + } + }, + ); + }); + }); + if closed { + hint.done = true; + self.shapes_hint = Some(false); + } + closed } /// Assessment of the move that led to the current position, for the board: the @@ -813,6 +929,18 @@ impl GameView { egui::CentralPanel::default().show(ui, |ui| { self.board_area(ui, &*settings, analysis, hover, &mut actions) }); + // Drawn on the board: the hint has done its job (gone after the button is let go). + if std::mem::take(&mut self.shape_drawn) { + let hint = &mut settings.hints.board_shapes; + if !hint.done { + hint.done = true; + actions.push(GameAction::HintsChanged); + } + if self.shapes_hint == Some(true) { + self.shapes_hint = Some(false); + ui.ctx().request_repaint(); + } + } self.sync_analysis(analysis); // «Analyse»: at once — the search is the same for everyone, nothing to choose. @@ -1552,11 +1680,25 @@ impl GameView { } return; } + let strip_top = ui.cursor().top(); let strip = if crate::platform::CAPS.translation { self.translation.strip(ui, settings, hub) } else { None }; + let translating = ui.cursor().top() > strip_top; + let seen_id = egui::Id::new("shapes_hint_games"); + let mut seen: std::collections::HashSet = + ui.data_mut(|d| d.get_temp(seen_id)).unwrap_or_default(); + let mut hints_changed = + self.decide_shapes_hint(&mut settings.hints.board_shapes, &mut seen, translating); + ui.data_mut(|d| d.insert_temp(seen_id, seen)); + if self.shapes_hint == Some(true) && !translating && self.preview.is_none() { + hints_changed |= self.shapes_hint_strip(ui, &mut settings.hints.board_shapes); + } + if hints_changed { + actions.push(GameAction::HintsChanged); + } match strip { Some(crate::translate_ui::StripAction::OpenSettings) => { actions.push(GameAction::OpenTranslationSettings) @@ -1569,6 +1711,7 @@ impl GameView { if std::mem::take(&mut self.translate_now) { self.translation.translate(ui.ctx(), settings, hub); } + self.shape_counts(); egui::ScrollArea::vertical() .auto_shrink(false) .show(ui, |ui| { @@ -1586,6 +1729,7 @@ impl GameView { read_only: self.play.is_some(), dim_until: None, mistakes: None, + shapes: self.shape_counts.as_ref().map(|(_, c)| c), } .show(ui); if let Some(id) = resp.clicked { @@ -3418,6 +3562,7 @@ impl GameView { .and_then(|s| self.game.node(s.floor)) .map(|n| n.ply()), mistakes: None, + shapes: None, } .show(ui); if let Some(id) = resp.clicked { @@ -4081,6 +4226,7 @@ impl GameView { editor: None, read_only: true, dim_until: None, + shapes: None, mistakes: marks.as_ref(), } .show(ui); @@ -5334,3 +5480,246 @@ fn paste_line_full(line: &[(u32, Color, String)]) -> String { .collect::>() .join(" ") } + +#[cfg(test)] +mod tests { + use super::*; + use crate::settings::Hint; + use std::collections::HashSet; + + type Shapes = (Vec<(ShapeColor, Square, Square)>, Vec<(ShapeColor, Square)>); + + fn view(pgn: &str) -> GameView { + let parsed = chess_core::parse_str(pgn); + GameView::new(parsed.game, None, parsed.diagnostics) + } + + /// The node reached by these moves from the start, through any variation. + fn at(game: &Game, moves: &[&str]) -> NodeId { + moves.iter().fold(NodeId::ROOT, |node, san| { + *game + .children(node) + .iter() + .find(|c| game.game_move(**c).is_some_and(|m| m.san == *san)) + .unwrap_or_else(|| panic!("no {san} after {node:?}")) + }) + } + + fn sq(s: &str) -> Square { + s.parse().unwrap() + } + + fn arrow(color: ShapeColor, from: &str, to: &str) -> board::Drawn { + board::Drawn::Arrow(color, sq(from), sq(to)) + } + + fn shapes_at(game: &Game, id: NodeId) -> Shapes { + chess_core::shapes(game.node(id).unwrap().comments_after()) + } + + /// Written to PGN and read again: the shapes of the same node. + fn reread(game: &Game, moves: &[&str]) -> Shapes { + let text = chess_core::write_game(game, &Default::default()); + let back = chess_core::parse_str(&text).game; + shapes_at(&back, at(&back, moves)) + } + + #[test] + fn a_shape_goes_into_the_current_move_and_back_out() { + let mut v = view("1. e4 e5 {Open game [%clk 0:05:00]} $1 2. Nf3 *"); + let e5 = at(&v.game, &["e4", "e5"]); + v.goto(e5); + v.apply_shape(arrow(ShapeColor::Green, "g1", "f3")); + assert_eq!( + shapes_at(&v.game, e5), + (vec![(ShapeColor::Green, sq("g1"), sq("f3"))], vec![]) + ); + let node = v.game.node(e5).unwrap(); + assert_eq!(node.nags(), &[Nag(1)]); + let text = node.comments_after().join(" "); + assert!( + text.contains("Open game") && text.contains("[%clk 0:05:00]"), + "{text}" + ); + assert_eq!( + reread(&v.game, &["e4", "e5"]).0, + vec![(ShapeColor::Green, sq("g1"), sq("f3"))] + ); + + // Another colour repaints it, the same colour again takes it off. + v.apply_shape(arrow(ShapeColor::Red, "g1", "f3")); + assert_eq!( + shapes_at(&v.game, e5).0, + vec![(ShapeColor::Red, sq("g1"), sq("f3"))] + ); + v.apply_shape(arrow(ShapeColor::Red, "g1", "f3")); + assert!(shapes_at(&v.game, e5).0.is_empty()); + + // One step of undo per shape. + v.game.undo(); + assert_eq!( + shapes_at(&v.game, e5).0, + vec![(ShapeColor::Red, sq("g1"), sq("f3"))] + ); + v.game.undo(); + v.game.undo(); + assert_eq!(shapes_at(&v.game, e5), (vec![], vec![])); + assert!(!v.game.is_modified()); + } + + #[test] + fn circles_toggle_and_recolour() { + let mut v = view("1. d4 *"); + let d4 = at(&v.game, &["d4"]); + v.goto(d4); + v.apply_shape(board::Drawn::Circle(ShapeColor::Green, sq("d5"))); + v.apply_shape(board::Drawn::Circle(ShapeColor::Blue, sq("e5"))); + v.apply_shape(board::Drawn::Circle(ShapeColor::Yellow, sq("d5"))); + assert_eq!( + shapes_at(&v.game, d4).1, + vec![(ShapeColor::Yellow, sq("d5")), (ShapeColor::Blue, sq("e5"))] + ); + v.apply_shape(board::Drawn::Circle(ShapeColor::Blue, sq("e5"))); + assert_eq!( + shapes_at(&v.game, d4).1, + vec![(ShapeColor::Yellow, sq("d5"))] + ); + } + + #[test] + fn a_shape_at_the_start_stays_with_the_start() { + let mut v = view("{Intro} 1. e4 e5 *"); + v.apply_shape(arrow(ShapeColor::Blue, "e2", "e4")); + assert_eq!( + reread(&v.game, &[]).0, + vec![(ShapeColor::Blue, sq("e2"), sq("e4"))] + ); + let text = chess_core::write_game(&v.game, &Default::default()); + assert!(text.contains("Intro"), "{text}"); + assert!(shapes_at(&v.game, at(&v.game, &["e4"])).0.is_empty()); + } + + #[test] + fn a_shape_in_a_nested_variation_stays_there() { + let mut v = view("1. e4 e5 (1... c5 2. Nf3 (2. c3 d5) 2... d6) 2. Nf3 *"); + let path = ["e4", "c5", "c3", "d5"]; + let d5 = at(&v.game, &path); + v.goto(d5); + v.apply_shape(arrow(ShapeColor::Green, "e4", "d5")); + assert_eq!( + reread(&v.game, &path).0, + vec![(ShapeColor::Green, sq("e4"), sq("d5"))] + ); + assert!(reread(&v.game, &["e4", "e5"]).0.is_empty()); + } + + #[test] + fn a_shape_after_a_null_move_and_from_a_fen_with_move_zero() { + let mut v = view("1. e4 -- 2. d4 *"); + let null = at(&v.game, &["e4", "--"]); + v.goto(null); + v.apply_shape(board::Drawn::Circle(ShapeColor::Red, sq("d4"))); + assert_eq!( + reread(&v.game, &["e4", "--"]).1, + vec![(ShapeColor::Red, sq("d4"))] + ); + + let mut v = + view("[FEN \"4k3/8/8/8/8/8/8/4K3 b - - 0 0\"]\n[SetUp \"1\"]\n\n0... Kd7 1. Ke2 *"); + let kd7 = at(&v.game, &["Kd7"]); + v.goto(kd7); + v.apply_shape(arrow(ShapeColor::Yellow, "e1", "e2")); + assert_eq!( + reread(&v.game, &["Kd7"]).0, + vec![(ShapeColor::Yellow, sq("e1"), sq("e2"))] + ); + } + + #[test] + fn a_shape_drawn_marks_the_hint_done_and_counts_for_the_notation() { + let mut v = view("1. e4 e5 {[%csl Gd5]} *"); + assert_eq!(v.shape_counts().len(), 1); + let e4 = at(&v.game, &["e4"]); + v.goto(e4); + v.apply_shape(arrow(ShapeColor::Green, "g1", "f3")); + assert!(v.shape_drawn); + assert_eq!( + v.shape_counts().get(&e4), + Some(&ShapeCount { + arrows: 1, + circles: 0 + }) + ); + assert_eq!(v.shape_counts().len(), 2); + v.game.undo(); + assert_eq!(v.shape_counts().len(), 1); + } + + #[test] + fn the_hint_is_decided_once_per_game_and_not_beside_the_translation() { + let mut hint = Hint::default(); + let mut seen = HashSet::new(); + + // With the translation strip: not shown, not counted. + let mut v = view("1. e4 *"); + assert!(!v.decide_shapes_hint(&mut hint, &mut seen, true)); + assert_eq!(v.shapes_hint, Some(false)); + assert_eq!(hint.shown, 0); + assert!(seen.is_empty()); + + // Decided on the first frame only. + let mut v = view("1. e4 *"); + assert!(v.decide_shapes_hint(&mut hint, &mut seen, false)); + assert!(!v.decide_shapes_hint(&mut hint, &mut seen, false)); + assert_eq!((v.shapes_hint, hint.shown), (Some(true), 1)); + + // The same game opened again in the session: shown, not counted. + let source = |index| GameSource { + path: PathBuf::from("/tmp/a.pgn"), + index, + block: None, + }; + let open = |index| { + let mut v = view("1. e4 *"); + v.source = Some(source(index)); + v + }; + let mut a = open(0); + assert!(a.decide_shapes_hint(&mut hint, &mut seen, false)); + let mut again = open(0); + assert!(!again.decide_shapes_hint(&mut hint, &mut seen, false)); + assert_eq!((again.shapes_hint, hint.shown), (Some(true), 2)); + + let mut b = open(1); + b.decide_shapes_hint(&mut hint, &mut seen, false); + assert_eq!(hint.shown, 3); + // The fourth game: gone by itself. + let mut c = open(2); + assert!(!c.decide_shapes_hint(&mut hint, &mut seen, false)); + assert_eq!(c.shapes_hint, Some(false)); + } + + #[test] + fn the_hint_is_not_shown_while_playing_or_after_it_is_done() { + let mut seen = HashSet::new(); + let mut hint = Hint { + done: true, + shown: 0, + }; + let mut v = view("1. e4 *"); + v.decide_shapes_hint(&mut hint, &mut seen, false); + assert_eq!(v.shapes_hint, Some(false)); + + let mut hint = Hint::default(); + let mut v = view("1. e4 *"); + v.preview = Some(Preview { + base: NodeId::ROOT, + root: Chess::default(), + moves: Vec::new(), + san: Vec::new(), + shown: 0, + }); + v.decide_shapes_hint(&mut hint, &mut seen, false); + assert_eq!((v.shapes_hint, hint.shown), (Some(false), 0)); + } +} diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 9600344..2a7b6ba 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -3495,6 +3495,83 @@ const ROWS: &[[&str; 9]] = &[ "Bu partiya uchun yashirish", "Бұл партия үшін жасыру", ], + [ + "Arrows and circles: drag or click with the right mouse button on the board. They are saved in the game.", + "Стрелки и круги: правая кнопка мыши на доске — протяните или щёлкните. Сохраняются в партии.", + "Flèches et cercles : faites glisser ou cliquez avec le bouton droit de la souris sur l’échiquier. Ils sont enregistrés dans la partie.", + "Pfeile und Kreise: mit der rechten Maustaste auf dem Brett ziehen oder klicken. Sie werden in der Partie gespeichert.", + "Flechas y círculos: arrastra o haz clic con el botón derecho del ratón en el tablero. Se guardan en la partida.", + "Frecce e cerchi: trascina o fai clic con il tasto destro del mouse sulla scacchiera. Vengono salvati nella partita.", + "Setas e círculos: arraste ou clique com o botão direito do mouse no tabuleiro. Eles são salvos na partida.", + "Strelkalar va doiralar: taxtada sichqonchaning o‘ng tugmasi bilan torting yoki bosing. Ular partiyada saqlanadi.", + "Көрсеткілер мен шеңберлер: тақтада тышқанның оң жақ батырмасымен сүйреңіз немесе басыңыз. Олар партияда сақталады.", + ], + [ + "No key — green, Shift — red, Alt — blue, Shift+Alt — yellow. Draw the same one again to remove it. Ctrl+Z undoes.", + "Без клавиши — зелёный, Shift — красный, Alt — синий, Shift+Alt — жёлтый. Та же фигура ещё раз — убрать. Ctrl+Z — отменить.", + "Sans touche — vert, Maj — rouge, Alt — bleu, Maj+Alt — jaune. Tracez la même forme à nouveau pour la retirer. Ctrl+Z annule.", + "Ohne Taste — grün, Umschalt — rot, Alt — blau, Umschalt+Alt — gelb. Dieselbe Form noch einmal zeichnen entfernt sie. Strg+Z macht rückgängig.", + "Sin tecla — verde, Mayús — rojo, Alt — azul, Mayús+Alt — amarillo. Dibuja la misma otra vez para quitarla. Ctrl+Z deshace.", + "Senza tasto — verde, Maiusc — rosso, Alt — blu, Maiusc+Alt — giallo. Disegna di nuovo la stessa per toglierla. Ctrl+Z annulla.", + "Sem tecla — verde, Shift — vermelho, Alt — azul, Shift+Alt — amarelo. Desenhe a mesma de novo para removê-la. Ctrl+Z desfaz.", + "Tugmasiz — yashil, Shift — qizil, Alt — ko‘k, Shift+Alt — sariq. Xuddi shuni yana chizsangiz, olib tashlanadi. Ctrl+Z — bekor qilish.", + "Пернесіз — жасыл, Shift — қызыл, Alt — көк, Shift+Alt — сары. Сол пішінді қайта салсаңыз — алынып тасталады. Ctrl+Z — болдырмау.", + ], + [ + "Don't show again", + "Больше не показывать", + "Ne plus afficher", + "Nicht mehr anzeigen", + "No volver a mostrar", + "Non mostrare più", + "Não mostrar novamente", + "Boshqa ko‘rsatilmasin", + "Енді көрсетпеу", + ], + [ + "Arrows: {a} · circles: {c} — shown on the board at this move", + "Стрелки: {a} · круги: {c} — видны на доске на этом ходу", + "Flèches : {a} · cercles : {c} — affichés sur l’échiquier à ce coup", + "Pfeile: {a} · Kreise: {c} — bei diesem Zug auf dem Brett zu sehen", + "Flechas: {a} · círculos: {c} — se ven en el tablero en esta jugada", + "Frecce: {a} · cerchi: {c} — visibili sulla scacchiera a questa mossa", + "Setas: {a} · círculos: {c} — aparecem no tabuleiro neste lance", + "Strelkalar: {a} · doiralar: {c} — shu yurishda taxtada ko‘rinadi", + "Көрсеткілер: {a} · шеңберлер: {c} — осы жүрісте тақтада көрінеді", + ], + [ + "Arrows: {a} — shown on the board at this move", + "Стрелки: {a} — видны на доске на этом ходу", + "Flèches : {a} — affichées sur l’échiquier à ce coup", + "Pfeile: {a} — bei diesem Zug auf dem Brett zu sehen", + "Flechas: {a} — se ven en el tablero en esta jugada", + "Frecce: {a} — visibili sulla scacchiera a questa mossa", + "Setas: {a} — aparecem no tabuleiro neste lance", + "Strelkalar: {a} — shu yurishda taxtada ko‘rinadi", + "Көрсеткілер: {a} — осы жүрісте тақтада көрінеді", + ], + [ + "Circles: {c} — shown on the board at this move", + "Круги: {c} — видны на доске на этом ходу", + "Cercles : {c} — affichés sur l’échiquier à ce coup", + "Kreise: {c} — bei diesem Zug auf dem Brett zu sehen", + "Círculos: {c} — se ven en el tablero en esta jugada", + "Cerchi: {c} — visibili sulla scacchiera a questa mossa", + "Círculos: {c} — aparecem no tabuleiro neste lance", + "Doiralar: {c} — shu yurishda taxtada ko‘rinadi", + "Шеңберлер: {c} — осы жүрісте тақтада көрінеді", + ], + [ + "Arrows and circles: right mouse button on the board; Shift — red, Alt — blue, Shift+Alt — yellow. Saved in the move's comment ([%cal], [%csl]).", + "Стрелки и круги — правая кнопка мыши на доске; Shift — красный, Alt — синий, Shift+Alt — жёлтый. Сохраняются в комментарии хода ([%cal], [%csl]).", + "Flèches et cercles : bouton droit de la souris sur l’échiquier ; Maj — rouge, Alt — bleu, Maj+Alt — jaune. Enregistrés dans le commentaire du coup ([%cal], [%csl]).", + "Pfeile und Kreise: rechte Maustaste auf dem Brett; Umschalt — rot, Alt — blau, Umschalt+Alt — gelb. Gespeichert im Kommentar des Zuges ([%cal], [%csl]).", + "Flechas y círculos: botón derecho del ratón en el tablero; Mayús — rojo, Alt — azul, Mayús+Alt — amarillo. Se guardan en el comentario de la jugada ([%cal], [%csl]).", + "Frecce e cerchi: tasto destro del mouse sulla scacchiera; Maiusc — rosso, Alt — blu, Maiusc+Alt — giallo. Salvati nel commento della mossa ([%cal], [%csl]).", + "Setas e círculos: botão direito do mouse no tabuleiro; Shift — vermelho, Alt — azul, Shift+Alt — amarelo. Salvos no comentário do lance ([%cal], [%csl]).", + "Strelkalar va doiralar — taxtada sichqonchaning o‘ng tugmasi; Shift — qizil, Alt — ko‘k, Shift+Alt — sariq. Yurish izohida saqlanadi ([%cal], [%csl]).", + "Көрсеткілер мен шеңберлер — тақтада тышқанның оң жақ батырмасы; Shift — қызыл, Alt — көк, Shift+Alt — сары. Жүріс түсініктемесінде сақталады ([%cal], [%csl]).", + ], [ "The model is loading into memory — this can take up to a minute…", "Модель загружается в память — это бывает до минуты…", diff --git a/apps/desktop/src/notation.rs b/apps/desktop/src/notation.rs index 262c271..c753981 100644 --- a/apps/desktop/src/notation.rs +++ b/apps/desktop/src/notation.rs @@ -29,6 +29,83 @@ pub struct Notation<'a> { pub dim_until: Option, /// Mistakes on main-line moves (learning an opening): how many, the move was shown. pub mistakes: Option<&'a HashMap>, + /// Arrows and circles of the moves' comments (`[%cal]`, `[%csl]`): a quiet sign by + /// the move ([`shape_counts`]). + pub shapes: Option<&'a HashMap>, +} + +/// How many arrows and circles a move's comment draws on the board. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ShapeCount { + pub arrows: usize, + pub circles: usize, +} + +impl ShapeCount { + /// «Arrows: 2 · circles: 1 — shown on the board at this move»; a count of none is left out. + pub fn hint(self) -> String { + let (a, c) = (self.arrows, self.circles); + match (a, c) { + (_, 0) => crate::i18n::trf( + "Arrows: {a} — shown on the board at this move", + &[("a", &a)], + ), + (0, _) => crate::i18n::trf( + "Circles: {c} — shown on the board at this move", + &[("c", &c)], + ), + _ => crate::i18n::trf( + "Arrows: {a} · circles: {c} — shown on the board at this move", + &[("a", &a), ("c", &c)], + ), + } + } +} + +/// The nodes of the game whose comment after them draws arrows or circles. +pub fn shape_counts(game: &Game) -> HashMap { + game.all_nodes() + .filter_map(|id| { + let (arrows, circles) = chess_core::shapes(game.node(id)?.comments_after()); + let count = ShapeCount { + arrows: arrows.len(), + circles: circles.len(), + }; + (count != ShapeCount::default()).then_some((id, count)) + }) + .collect() +} + +/// The sign's box; it is drawn this far after the move. +const SIGN: f32 = 10.0; +const SIGN_GAP: f32 = 4.0; + +/// The sign of a move whose comment draws on the board: an arrow if it has one, a ring +/// otherwise. Painted (no font has both at the height of a move's text), so it is sharp +/// at any scale; it does not repeat the shapes' colours, which would argue with NAGs. +fn paint_shapes_sign( + painter: &egui::Painter, + center: egui::Pos2, + count: ShapeCount, + color: Color32, +) { + let stroke = Stroke::new(1.5, color); + if count.arrows > 0 { + let h = SIGN / 2.0 - 0.5; + let (from, tip) = (center + vec2(-h, h), center + vec2(h, -h)); + let dir = (tip - from).normalized(); + let head = 4.5; + let base = tip - dir * head; + let side = vec2(-dir.y, dir.x) * (head * 0.55); + painter.line_segment([from, base + dir * 0.5], stroke); + painter.add(egui::Shape::convex_polygon( + vec![tip, base + side, base - side], + color, + Stroke::NONE, + )); + } else { + painter.circle_stroke(center, SIGN / 2.0 - 0.5, stroke); + } } /// Result of a frame of the notation panel. @@ -325,6 +402,7 @@ impl Row { resp.hovered(), dim, ); + let mut right = text_right; if let Some(&(count, shown)) = n.mistakes.and_then(|m| m.get(&id)) { let color = if shown { ui.visuals().warn_fg_color @@ -347,6 +425,7 @@ impl Row { ui.painter().rect_filled(pill, 7.0, color); ui.painter() .galley(pill.min + vec2(4.0, 1.0), galley, Color32::WHITE); + right = pill.right(); let tip = if shown { crate::i18n::trf("Mistakes: {n}; the move was shown", &[("n", &count)]) } else { @@ -354,6 +433,22 @@ impl Row { }; resp.clone().on_hover_text(tip); } + if let Some(&count) = n.shapes.and_then(|s| s.get(&id)) { + let color = if id == n.cursor { + ui.visuals().selection.stroke.color + } else { + ui.visuals().weak_text_color() + }; + let x = + (right + SIGN_GAP + SIGN / 2.0).min(cell.right() - SIGN / 2.0 - 2.0); + paint_shapes_sign( + ui.painter(), + egui::pos2(x, cell.center().y), + count, + color, + ); + resp.clone().on_hover_text(count.hint()); + } handle_move_response(ui, &resp, n, id, out); } None => { @@ -662,7 +757,7 @@ fn mark_block(ui: &mut Ui, n: &Notation, id: NodeId, mark: &Mark, out: &mut Nota }; let label = crate::san::show(&label).into_owned(); let current = shown == Some(i + 1); - let resp = move_chip(ui, &label, None, current) + let resp = move_chip(ui, &label, None, current, None) .on_hover_text(tr("Show this line on the board")); if current && n.scroll_to_cursor { resp.scroll_to_me(Some(egui::Align::Center)); @@ -838,11 +933,16 @@ const MARK_ROOM: f32 = 18.0; fn comment_block(ui: &mut Ui, n: &Notation, text: &str, slot: Slot, out: &mut NotationResponse) { let (shown, mark) = translated(n, text); + // The start of the game draws on the board: the sign at the block's right edge. + let shapes = (slot == Slot::After(NodeId::ROOT)) + .then(|| n.shapes.and_then(|s| s.get(&NodeId::ROOT)).copied()) + .flatten(); + let room = MARK_ROOM * (u8::from(mark.is_some()) + u8::from(shapes.is_some())) as f32; let mut frame = block_frame(ui); - if mark.is_some() { + if room > 0.0 { frame = frame.inner_margin(egui::Margin { left: 10, - right: 10 + MARK_ROOM as i8, + right: 10 + room as i8, top: 6, bottom: 6, }); @@ -867,6 +967,18 @@ fn comment_block(ui: &mut Ui, n: &Notation, text: &str, slot: Slot, out: &mut No let at = r.response.rect.right_top() + vec2(-8.0, 7.0); translation_mark(ui, at, m, text); } + if let Some(count) = shapes { + let shift = if mark.is_some() { MARK_ROOM } else { 0.0 }; + let center = r.response.rect.right_top() + vec2(-8.0 - shift - SIGN / 2.0, 6.0 + 9.0); + paint_shapes_sign(ui.painter(), center, count, ui.visuals().weak_text_color()); + let id = ui.id().with("root_shapes"); + ui.interact( + egui::Rect::from_center_size(center, vec2(SIGN, SIGN) + vec2(4.0, 4.0)), + id, + Sense::hover(), + ) + .on_hover_text(count.hint()); + } } /// A double click opens the comment for editing; the right button offers that and @@ -1154,6 +1266,7 @@ enum Token { /// The label with the move number, for the move that starts a piece of the flow. numbered: String, color: Option, + shapes: Option, }, Comment { slot: Slot, @@ -1209,7 +1322,13 @@ fn variation_block( /// A move in flowing text: the current one highlighted as in the main-line table, /// the others lit under the mouse. Painted by hand, so its size never changes with the /// mouse (a button's frame does). -fn move_chip(ui: &mut Ui, label: &str, color: Option, current: bool) -> egui::Response { +fn move_chip( + ui: &mut Ui, + label: &str, + color: Option, + current: bool, + shapes: Option, +) -> egui::Response { let sel = ui.visuals().selection; let font = FontId::proportional(15.0); let text_color = if current { @@ -1221,7 +1340,13 @@ fn move_chip(ui: &mut Ui, label: &str, color: Option, current: bool) -> .painter() .layout_no_wrap(label.to_owned(), font, text_color); let pad = vec2(4.0, 2.0); - let (rect, resp) = ui.allocate_exact_size(galley.size() + 2.0 * pad, Sense::click()); + let sign = if shapes.is_some() { + SIGN_GAP + SIGN + } else { + 0.0 + }; + let (rect, resp) = + ui.allocate_exact_size(galley.size() + 2.0 * pad + vec2(sign, 0.0), Sense::click()); if current { ui.painter().rect( rect, @@ -1234,7 +1359,18 @@ fn move_chip(ui: &mut Ui, label: &str, color: Option, current: bool) -> ui.painter() .rect_filled(rect, 2.0, ui.visuals().widgets.hovered.weak_bg_fill); } + let text_right = rect.min.x + pad.x + galley.size().x; ui.painter().galley(rect.min + pad, galley, text_color); + if let Some(count) = shapes { + let color = if current { + sel.stroke.color + } else { + ui.visuals().weak_text_color() + }; + let center = egui::pos2(text_right + SIGN_GAP + SIGN / 2.0, rect.center().y); + paint_shapes_sign(ui.painter(), center, count, color); + return resp.on_hover_text(count.hint()); + } resp } @@ -1258,6 +1394,7 @@ fn flow( label, numbered, color, + shapes, } => { let current = *id == n.cursor; // After the editor the flow starts anew: with the move number. @@ -1266,7 +1403,7 @@ fn flow( } else { label }; - let resp = move_chip(ui, label, *color, current); + let resp = move_chip(ui, label, *color, current, *shapes); handle_move_response(ui, &resp, n, *id, out); } Token::Comment { slot, text } => { @@ -1332,6 +1469,7 @@ fn line_tokens(n: &Notation, first: NodeId, dark: bool, tokens: &mut Vec) label, numbered, color: sym_color, + shapes: n.shapes.and_then(|s| s.get(&node)).copied(), }); let after = comment_text(nd.comments_after()); if !after.is_empty() { @@ -1362,3 +1500,54 @@ fn line_tokens(n: &Notation, first: NodeId, dark: bool, tokens: &mut Vec) } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn shape_counts_find_arrows_and_circles_of_comments_only() { + let game = chess_core::parse_str( + "{[%csl Re4]} 1. e4 {[%cal Gg1f3,Gf1c4] [%csl Ga8] [%clk 0:01:00]} e5 {plain} \ + (1... c5 {[%csl Yd5]}) 2. Nf3 {[%eval 0.3]} *", + ) + .game; + let counts = shape_counts(&game); + let e4 = game.main_child(NodeId::ROOT).unwrap(); + let c5 = game.variations(e4)[0]; + assert_eq!(counts.len(), 3, "{counts:?}"); + assert_eq!( + counts[&NodeId::ROOT], + ShapeCount { + arrows: 0, + circles: 1 + } + ); + assert_eq!( + counts[&e4], + ShapeCount { + arrows: 2, + circles: 1 + } + ); + assert_eq!( + counts[&c5], + ShapeCount { + arrows: 0, + circles: 1 + } + ); + } + + #[test] + fn the_sign_hint_leaves_out_a_count_of_none() { + crate::i18n::set_lang(crate::i18n::Lang::En); + let hint = |arrows, circles| ShapeCount { arrows, circles }.hint(); + assert_eq!( + hint(2, 1), + "Arrows: 2 · circles: 1 — shown on the board at this move" + ); + assert_eq!(hint(2, 0), "Arrows: 2 — shown on the board at this move"); + assert_eq!(hint(0, 1), "Circles: 1 — shown on the board at this move"); + } +} diff --git a/apps/desktop/src/opening_lines.rs b/apps/desktop/src/opening_lines.rs index a6e09f0..48f0f58 100644 --- a/apps/desktop/src/opening_lines.rs +++ b/apps/desktop/src/opening_lines.rs @@ -391,6 +391,7 @@ impl OpeningLinesUi { read_only: true, dim_until: None, mistakes: None, + shapes: None, } .show(ui) }) diff --git a/apps/desktop/src/settings.rs b/apps/desktop/src/settings.rs index e69d746..459eeb1 100644 --- a/apps/desktop/src/settings.rs +++ b/apps/desktop/src/settings.rs @@ -177,6 +177,41 @@ pub struct Settings { #[serde(default)] pub repertoire_context_policies: std::collections::HashMap, + /// Hints shown until the user reacts (docs/design/tasks-42-43-2026-11-27.md §43.3). + pub hints: Hints, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Hints { + /// «Arrows and circles: the right mouse button on the board» above the notation. + pub board_shapes: Hint, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Hint { + /// Closed, or what it tells was done: never shown again. + pub done: bool, + /// Games it was shown in without a reaction. + pub shown: u32, +} + +impl Hint { + /// Shown in this many games without a reaction, the hint goes by itself. + pub const SHOWS: u32 = 3; + + /// A game opens where the hint can stand: whether it is shown there. A show counts + /// once per game (`fresh`: the game was not opened before in this session). + pub fn offer(&mut self, fresh: bool) -> bool { + if self.done || self.shown >= Self::SHOWS { + return false; + } + if fresh { + self.shown += 1; + } + true + } } /// Options of the opponent preparation; its engine search is the game analysis's. @@ -249,6 +284,7 @@ impl Default for Settings { repertoire_priorities: Default::default(), repertoire_context_policies: Default::default(), repertoire_flow_version: 0, + hints: Hints::default(), } } } @@ -359,6 +395,44 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { mod tests { use super::*; + #[test] + fn a_hint_goes_after_three_games_without_a_reaction() { + let mut hint = Hint::default(); + assert!(hint.offer(true)); + // The same game opened again in the session: shown, not counted. + assert!(hint.offer(false)); + assert!(hint.offer(true)); + assert!(hint.offer(true)); + assert_eq!(hint.shown, 3); + assert!(!hint.offer(true)); + assert!(!hint.offer(false)); + assert_eq!(hint.shown, 3); + } + + #[test] + fn a_hint_done_is_never_shown() { + let mut hint = Hint { + done: true, + shown: 0, + }; + assert!(!hint.offer(true)); + assert_eq!(hint.shown, 0); + } + + #[test] + fn hints_survive_saving_and_old_settings_have_none() { + let mut s = Settings::default(); + s.hints.board_shapes = Hint { + done: false, + shown: 2, + }; + let json = serde_json::to_string(&s).unwrap(); + let back: Settings = serde_json::from_str(&json).unwrap(); + assert_eq!(back.hints, s.hints); + let old: Settings = serde_json::from_str(r#"{"show_coords": false}"#).unwrap(); + assert_eq!(old.hints, Hints::default()); + } + /// A database put on the shelf again by a link to its file stays itself, once. #[cfg(unix)] #[test] diff --git a/apps/desktop/src/settings_ui.rs b/apps/desktop/src/settings_ui.rs index ca52add..39be1fa 100644 --- a/apps/desktop/src/settings_ui.rs +++ b/apps/desktop/src/settings_ui.rs @@ -559,6 +559,13 @@ fn board_tab(ui: &mut Ui, s: &mut Settings, changed: &mut bool) { } } }); + // The hint above the notation goes away; what it told stays here. + ui.label( + RichText::new(tr( + "Arrows and circles: right mouse button on the board; Shift — red, Alt — blue, Shift+Alt — yellow. Saved in the move's comment ([%cal], [%csl]).", + )) + .weak(), + ); ui.add_space(8.0); ui.horizontal(|ui| { ui.label(tr("Piece animation"));