diff --git a/CHANGELOG.md b/CHANGELOG.md index 421d24a..8897a4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,24 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). +## [Unreleased] + +- Paste a line from the clipboard (Ctrl+V on a game, or the move menu): moves («Nf3 d5», + «12...Rd8», UCI) go after the selected move or instead of it; a PGN game goes where its + moves part from this game — along any branch, or by another move order — with its + comments, symbols and variations and the players' names at the end. A game that shares + no position with this one is not pasted, with a message; a line starting before the + selected move is asked about. One Ctrl+Z takes it all back. +- Play on from here (the move menu, Ctrl+G on a game): a game against Maia from the + position, its moves up to it kept (Maia sees the history, repetitions count); the + game you came from waits under it, «⬅ Back to the game» returns to it. The side to + move plays by default; a rematch keeps the colour. +- Learn the opening (the move menu): replay from memory the moves of both sides up to + the chosen move. A wrong move is counted, shown for a moment with a short sound and + taken back; from the third mistake on a move you may ask to see it. At the end: the + mistakes by move, the runs of the line (last, best, clean in a row, recent), «Again». + The runs are kept by the line itself, across games. + ## [1.3.0] — 2026-10-25 - Play against the computer (desktop): «♞ Play» in the library (Ctrl+G) starts a game diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 8597612..b278436 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -51,14 +51,18 @@ Downloaded unmodified (files renamed `wk.svg` → `wK.svg`) from https://github. "Interface Sounds" (https://kenney.nl, CC0 1.0): leading silence trimmed, loudness matched to the other sets, re-encoded as Ogg Vorbis. -| Set | Move | Capture | Check | Checkmate | Defeat | -| --- | --- | --- | --- | --- | --- | -| wood | impactWood_light_002 | impactWood_heavy_002 | impactPlank_medium_002 | impactBell_heavy_001 | minimize_008 | -| glass | impactGlass_light_001 | impactGlass_heavy_001 | glass_002 | impactBell_heavy_000 | minimize_004 | -| clicks | click_002 | drop_002 | confirmation_001 | maximize_006 | minimize_006 | +| Set | Move | Capture | Check | Checkmate | Defeat | Success | +| --- | --- | --- | --- | --- | --- | --- | +| wood | impactWood_light_002 | impactWood_heavy_002 | impactPlank_medium_002 | impactBell_heavy_001 | minimize_008 | confirmation_004 | +| glass | impactGlass_light_001 | impactGlass_heavy_001 | glass_002 | impactBell_heavy_000 | minimize_004 | confirmation_002 | +| clicks | click_002 | drop_002 | confirmation_001 | maximize_006 | minimize_006 | confirmation_003 | -The Defeat sounds of the Lichess sets (`Defeat.ogg` of `public/sound/sfx`, `piano`, -`futuristic`, `nes`, by Enigmahack, AGPLv3+) were downloaded unmodified on 2026-10-25. +`apps/desktop/assets/sounds/common/Wrong.ogg` (a wrong move while learning an opening, every +set) is Kenney's `error_003` of "Interface Sounds" (CC0), made the same way. + +The Defeat and Success sounds of the Lichess sets (`Defeat.ogg` and `Victory.ogg` of +`public/sound/sfx`, `piano`, `futuristic`, `nes`, by Enigmahack, AGPLv3+) were downloaded +unmodified on 2026-10-25. Notes: - Lichess keeps a set's checkmate sound as a link to its check sound; ChessPenguin plays the check diff --git a/apps/desktop/assets/sounds/clicks/Success.ogg b/apps/desktop/assets/sounds/clicks/Success.ogg new file mode 100644 index 0000000..e04af48 Binary files /dev/null and b/apps/desktop/assets/sounds/clicks/Success.ogg differ diff --git a/apps/desktop/assets/sounds/common/Wrong.ogg b/apps/desktop/assets/sounds/common/Wrong.ogg new file mode 100644 index 0000000..4db14dc Binary files /dev/null and b/apps/desktop/assets/sounds/common/Wrong.ogg differ diff --git a/apps/desktop/assets/sounds/futuristic/Success.ogg b/apps/desktop/assets/sounds/futuristic/Success.ogg new file mode 100644 index 0000000..0522e55 Binary files /dev/null and b/apps/desktop/assets/sounds/futuristic/Success.ogg differ diff --git a/apps/desktop/assets/sounds/glass/Success.ogg b/apps/desktop/assets/sounds/glass/Success.ogg new file mode 100644 index 0000000..4331f4a Binary files /dev/null and b/apps/desktop/assets/sounds/glass/Success.ogg differ diff --git a/apps/desktop/assets/sounds/nes/Success.ogg b/apps/desktop/assets/sounds/nes/Success.ogg new file mode 100644 index 0000000..537115f Binary files /dev/null and b/apps/desktop/assets/sounds/nes/Success.ogg differ diff --git a/apps/desktop/assets/sounds/piano/Success.ogg b/apps/desktop/assets/sounds/piano/Success.ogg new file mode 100644 index 0000000..fa2cc74 Binary files /dev/null and b/apps/desktop/assets/sounds/piano/Success.ogg differ diff --git a/apps/desktop/assets/sounds/sfx/Success.ogg b/apps/desktop/assets/sounds/sfx/Success.ogg new file mode 100644 index 0000000..e8646a3 Binary files /dev/null and b/apps/desktop/assets/sounds/sfx/Success.ogg differ diff --git a/apps/desktop/assets/sounds/wood/Success.ogg b/apps/desktop/assets/sounds/wood/Success.ogg new file mode 100644 index 0000000..32d3b4f Binary files /dev/null and b/apps/desktop/assets/sounds/wood/Success.ogg differ diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index faa4073..3e1d899 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -169,7 +169,8 @@ pub fn overlay_open_besides(ctx: &egui::Context, own: &[egui::Id]) -> bool { /// What starts once the played game is closed. enum PlayNext { Rematch(crate::play::Start), - Dialog, + /// The play dialog again (from the same position, for a game from a position). + Dialog(Option>), } #[derive(Clone, Copy, PartialEq)] @@ -239,6 +240,8 @@ pub struct App { #[derive(Default)] struct DebugStartup { open: Option, + /// `CP_PLAY_FROM=white|black`: the game against Maia from the move reached. + play_from: Option, ply: usize, analyze: bool, /// `CP_SCREENSHOT=`: go fullscreen, wait `CP_SCREENSHOT_DELAY` seconds, @@ -264,6 +267,7 @@ impl DebugStartup { let num = |k| std::env::var(k).ok().and_then(|v| v.parse::().ok()); Self { open: num("CP_OPEN"), + play_from: None, 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), @@ -482,6 +486,7 @@ impl App { user_elo: self.settings.rating, user_name: self.settings.your_name.clone(), clock, + from: None, }, ); } @@ -572,6 +577,39 @@ impl App { if std::env::var_os("CP_COMMENT_EDIT").is_some() { g.debug_comment_edit(); } + if let Ok(text) = std::env::var("CP_PASTE_LINE") { + g.debug_paste(&text); + } + // `CP_PLAY_FROM=dialog`: the play dialog from the move reached; + // `white|black[,strength]`: the game at once. + if let Ok(spec) = std::env::var("CP_PLAY_FROM") + && let Some(from) = g.debug_play_from() + { + let mut parts = spec.split(','); + let side = parts.next().unwrap_or("dialog"); + let strength = parts.next().and_then(|s| s.parse().ok()).unwrap_or(1500); + let user = match side { + "white" => Some(chess_core::shakmaty::Color::White), + "black" => Some(chess_core::shakmaty::Color::Black), + _ => None, + }; + match user { + Some(user) => { + self.debug.play_from = Some(crate::play::Start { + user, + strength, + user_elo: self.settings.rating, + user_name: self.settings.your_name.clone(), + clock: self.settings.play.clock, + from: Some(Box::new(from)), + }) + } + None => { + self.play_dialog = + Some(crate::play::Dialog::new_from(&self.settings, from)); + } + } + } if std::env::var("CP_ENGINE_PANEL").is_ok() { g.debug_open_engine_settings(); } @@ -586,6 +624,19 @@ impl App { g.debug_review(&self.settings, ctx, v != "dialog"); } } + if let Some(start) = self.debug.play_from.take() { + self.start_play(ctx, start); + } + // `CP_TRAIN=1`: learning the opening up to the move reached; `CP_TRAIN_MOVES`: + // moves made in it (UCI). + if std::env::var_os("CP_TRAIN").is_some() + && let Some(start) = self.game.as_ref().and_then(|g| g.debug_train()) + { + self.open_training(start); + if let (Ok(moves), Some(g)) = (std::env::var("CP_TRAIN_MOVES"), self.game.as_mut()) { + g.debug_train_moves(&moves); + } + } if self.debug.analyze { self.toggle_engine(ctx); } @@ -1284,6 +1335,70 @@ impl App { self.game = Some(GameView::new(g, None, Vec::new())); } + /// What comes after a game against Maia was closed: a rematch, the dialog. + fn play_next_now(&mut self, ctx: &egui::Context) { + match self.play_next.take() { + Some(PlayNext::Rematch(s)) => self.start_play(ctx, s), + Some(PlayNext::Dialog(None)) => { + self.play_dialog = Some(crate::play::Dialog::new(&self.settings)) + } + Some(PlayNext::Dialog(Some(from))) => { + self.play_dialog = Some(crate::play::Dialog::new_from(&self.settings, *from)) + } + None => {} + } + } + + /// A game from a position of another game: its moves to that position, the game + /// it comes from waiting under it (as a game opened from the reference does). + fn game_from(&mut self, from: &crate::play::StartFrom) { + let mut g = match from + .start_fen + .as_deref() + .and_then(|f| chess_core::StartPosition::from_fen(f).ok()) + { + Some(start) => Game::from_start(start), + None => Game::new(), + }; + g.set_tag("Date", &chrono::Local::now().format("%Y.%m.%d").to_string()); + if !from.moves.is_empty() { + let _ = g.add_line(chess_core::NodeId::ROOT, &from.moves); + } + g.forget_history(); + g.mark_saved(); + self.open_over(g); + } + + /// `g` opens over the current game, which waits under it as it is (as a game + /// opened from the reference does); the engine stops. + fn open_over(&mut self, g: Game) { + self.analysis.stop(); + let title = self.game.as_ref().map(|g| g.title()); + if let Some(mut prev) = self.game.take() { + prev.suspend(); + self.previous_games.push(prev); + } + let mut view = GameView::new(g, None, Vec::new()); + view.previous = title; + self.game = Some(view); + } + + /// Learning the opening of the current game: the training opens over it. + fn open_training(&mut self, start: crate::train::TrainStart) { + let g = match start + .start_fen + .as_deref() + .and_then(|f| chess_core::StartPosition::from_fen(f).ok()) + { + Some(s) => Game::from_start(s), + None => Game::new(), + }; + self.open_over(g); + if let Some(view) = self.game.as_mut() { + view.start_training(start); + } + } + /// A new game against Maia (the weights are there: the dialog saw to it). fn start_play(&mut self, ctx: &egui::Context, start: crate::play::Start) { let Some(weights) = crate::maia_download::installed() else { @@ -1299,7 +1414,10 @@ impl App { .and_then(|e| e.executable()) .filter(|p| p.is_file()) }); - self.new_game(); + match &start.from { + Some(from) => self.game_from(from), + None => self.new_game(), + } if let Some(g) = self.game.as_mut() { g.start_play(start, weights, judge, ctx); } @@ -1781,6 +1899,8 @@ impl App { let closed = self.game.take(); if intent == CloseIntent::ReturnToPrevious { self.game = self.previous_games.pop(); + // A rematch from a position goes on over the same game. + self.play_next_now(ctx); return; } // Games left for others (reference tab) with unsaved edits are asked about one @@ -1804,13 +1924,7 @@ impl App { { self.library.reveal(&src.path, src.index); } - match self.play_next.take() { - Some(PlayNext::Rematch(s)) => self.start_play(ctx, s), - Some(PlayNext::Dialog) => { - self.play_dialog = Some(crate::play::Dialog::new(&self.settings)) - } - None => {} - } + self.play_next_now(ctx); if let Some((path, start, line, flipped)) = self.find_after_close.take() { self.library.show_position(&path, start, line, flipped, ctx); } @@ -2154,7 +2268,9 @@ impl eframe::App for App { self.own.then_close = None; self.new_base_dialog(own_db::AfterCreate::Shelf); } - if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::G))) && self.game.is_none() { + // In the library a game from the start; on a game's screen the game plays on + // from its position (the game view takes Ctrl+G there). + if self.game.is_none() && ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::G))) { self.play_dialog = Some(crate::play::Dialog::new(&self.settings)); } if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::N))) && self.game.is_none() { @@ -2246,7 +2362,9 @@ impl eframe::App for App { .and_then(|g| g.play_end.clone()) .map(|e| { let mut s = e.start; + // From a position the colour is part of the task: the same. s.user = match self.settings.play.color { + _ if s.from.is_some() => s.user, crate::play::ColorChoice::Random => { if crate::play::random_unit() < 0.5 { chess_core::shakmaty::Color::White @@ -2259,13 +2377,34 @@ impl eframe::App for App { s }); if let Some(s) = next { + // From a position: back over the game it came from. + let intent = if s.from.is_some() && !self.previous_games.is_empty() { + CloseIntent::ReturnToPrevious + } else { + CloseIntent::BackToLibrary + }; self.play_next = Some(PlayNext::Rematch(s)); - self.request_close(&ctx, CloseIntent::BackToLibrary); + self.request_close(&ctx, intent); } } GameAction::PlayAgain => { - self.play_next = Some(PlayNext::Dialog); - self.request_close(&ctx, CloseIntent::BackToLibrary); + let from = self + .game + .as_ref() + .and_then(|g| g.play_end.as_ref()) + .and_then(|e| e.start.from.clone()); + let intent = if from.is_some() && !self.previous_games.is_empty() { + CloseIntent::ReturnToPrevious + } else { + CloseIntent::BackToLibrary + }; + self.play_next = Some(PlayNext::Dialog(from)); + self.request_close(&ctx, intent); + } + GameAction::Train(start) => self.open_training(*start), + GameAction::PlayFrom(from) => { + self.play_dialog = + Some(crate::play::Dialog::new_from(&self.settings, *from)); } GameAction::AddToDatabase => { if let Some(g) = self.game.as_mut() { @@ -2538,8 +2677,12 @@ impl eframe::App for App { .order(egui::Order::Foreground) .show(&ctx, |ui| { egui::Frame::popup(ui.style()).show(ui, |ui| { - ui.horizontal(|ui| { - ui.label(RichText::new(msg.as_str()).size(14.0)); + // Long messages wrap: at most 560 wide, inside a narrow window. + ui.set_max_width((ctx.content_rect().width() - 32.0).min(560.0)); + ui.horizontal_wrapped(|ui| { + ui.add( + egui::Label::new(RichText::new(msg.as_str()).size(14.0)).wrap(), + ); if undo && ui.button(tr("Undo")).on_hover_text("Ctrl+Z").clicked() { undo_clicked = true; } diff --git a/apps/desktop/src/assets.rs b/apps/desktop/src/assets.rs index 4ec5503..74e734e 100644 --- a/apps/desktop/src/assets.rs +++ b/apps/desktop/src/assets.rs @@ -558,6 +558,10 @@ pub enum Sound { Checkmate, /// A game lost — here: Maia offers to resign. Defeat, + /// Not the move of the line (learning an opening). + Wrong, + /// The line done (learning an opening). + Success, } pub fn sound_bytes(set: SoundSet, sound: Sound) -> &'static [u8] { @@ -599,6 +603,15 @@ pub fn sound_bytes(set: SoundSet, sound: Sound) -> &'static [u8] { (SoundSet::Wood, Sound::Defeat) => s!("wood", "Defeat"), (SoundSet::Glass, Sound::Defeat) => s!("glass", "Defeat"), (SoundSet::Clicks, Sound::Defeat) => s!("clicks", "Defeat"), + // One short falling tone for every set (Kenney, CC0). + (_, Sound::Wrong) => s!("common", "Wrong"), + (SoundSet::Sfx, Sound::Success) => s!("sfx", "Success"), + (SoundSet::Piano, Sound::Success) => s!("piano", "Success"), + (SoundSet::Futuristic, Sound::Success) => s!("futuristic", "Success"), + (SoundSet::Nes, Sound::Success) => s!("nes", "Success"), + (SoundSet::Wood, Sound::Success) => s!("wood", "Success"), + (SoundSet::Glass, Sound::Success) => s!("glass", "Success"), + (SoundSet::Clicks, Sound::Success) => s!("clicks", "Success"), } } diff --git a/apps/desktop/src/board.rs b/apps/desktop/src/board.rs index a913096..1a7ae8a 100644 --- a/apps/desktop/src/board.rs +++ b/apps/desktop/src/board.rs @@ -176,6 +176,8 @@ pub struct BoardView<'a> { pub premove: Option, /// A pawn reaching the last rank becomes a queen without asking. pub auto_queen: bool, + /// The squares of a wrong move, in red (learning an opening). + pub alert: Option<(Square, Square)>, } impl BoardView<'_> { @@ -327,6 +329,11 @@ impl BoardView<'_> { if let Some(sel) = state.selected { hl(&painter, sel, self.theme.selected); } + if let Some((from, to)) = self.alert { + let red = ui.visuals().error_fg_color.gamma_multiply(0.45); + hl(&painter, from, red); + hl(&painter, to, red); + } if self.pos.is_check() && let Some(k) = self.pos.board().king_of(self.pos.turn()) { diff --git a/apps/desktop/src/board_search.rs b/apps/desktop/src/board_search.rs index 887ade2..76445fc 100644 --- a/apps/desktop/src/board_search.rs +++ b/apps/desktop/src/board_search.rs @@ -525,6 +525,7 @@ impl SearchBoard { animation: settings.animation.seconds(), premove: None, auto_queen: settings.auto_queen, + alert: None, }; let played = ui .allocate_ui(vec2(side, side), |ui| view.show(ui, &mut self.board)) diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 4d82ad7..4f4c4d8 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -71,6 +71,12 @@ pub struct GameView { /// «The game is on» asked (leaving during a game); the clocks wait meanwhile. /// Where leaving goes, and since when the question is open. play_leave: Option<(crate::app::CloseIntent, std::time::Instant)>, + /// Learning an opening (this screen is the training). + pub train: Option, + /// A line from the clipboard that would go elsewhere than the user stands: asked. + paste_pending: Option, + /// Text to paste on the next frame (dev hook `CP_PASTE_LINE`). + paste_request: Option, show_diagnostics: bool, engine_settings_open: bool, review: Review, @@ -97,6 +103,10 @@ enum SideTab { pub enum GameAction { Back, + /// «Play on from here»: the play dialog for this position. + PlayFrom(Box), + /// «Learn the opening up to this move»: the training over this game. + Train(Box), Sound(Sound), CopyText(String, &'static str), /// Ctrl+S: into the game's own database, else "Add to database…". @@ -159,6 +169,9 @@ impl GameView { play_end: None, play_start: None, play_leave: None, + paste_pending: None, + train: None, + paste_request: None, show_diagnostics: false, engine_settings_open: false, review, @@ -193,6 +206,12 @@ impl GameView { } pub fn title(&self) -> String { + if let Some(t) = &self.train { + return match &t.start.game { + Some(game) => trf("Learning the opening: {game}", &[("game", game)]), + None => tr("Learning the opening").to_owned(), + }; + } let g = &self.game; // In a game against Maia an unnamed user is «You». let user = self.play.as_ref().map(|s| s.user); @@ -261,6 +280,13 @@ impl GameView { } fn subtitle(&self) -> String { + if let Some(t) = &self.train { + let up_to = trf("up to {move}", &[("move", &t.start.up_to)]); + return match &t.start.event { + Some(e) => format!("{e} · {up_to}"), + None => up_to, + }; + } let g = &self.game; let mut parts = Vec::new(); for t in ["Event", "Site", "Date", "ECO", "Annotator"] { @@ -277,6 +303,10 @@ impl GameView { /// A move made on the board or picked in the reference tab: goes to it if the /// game has it, else adds it (undoable). fn play_move(&mut self, m: Move, actions: &mut Vec) { + if self.train.is_some() { + self.train_move(m, actions); + return; + } if self.play.is_some() { self.user_move(m, actions); return; @@ -726,6 +756,12 @@ impl GameView { None => {} } + // A line from the clipboard: pasted, or asked about. + if let Some(text) = self.paste_request.take() { + self.paste_text(&text, &mut actions); + } + self.paste_question(ui.ctx(), &mut actions); + // Leaving during a game asks first; the question itself. self.guard_leaving(&mut actions); self.leave_question(ui.ctx(), &mut actions); @@ -962,7 +998,7 @@ impl GameView { // The title opens the game's data (players, event, date…). let label = egui::Label::new(RichText::new(&title).strong().size(16.0)) .truncate(); - if self.play.is_some() { + if self.play.is_some() || self.train.is_some() { ui.add(label); } else if ui .add(label.sense(Sense::click())) @@ -1010,7 +1046,7 @@ impl GameView { let searchable = self.search_line().is_some(); let why = tr("After a null move (--) this is a teaching scheme, not a position of a game: it is not searched"); // Not during a game against Maia: it would leave the game. - let playing = self.play.is_some(); + let playing = self.play.is_some() || self.train.is_some(); if !playing { ui.add_enabled_ui(searchable && !databases.is_empty(), |ui| { ui.menu_button("⏷", |ui| { for db in databases { @@ -1056,6 +1092,7 @@ impl GameView { reference_hover: Option, actions: &mut Vec, ) { + self.train_tick(ui.ctx()); let preview_pos = self.preview.as_ref().map(|p| p.position()); let Some(game_pos) = self.game.position(self.cursor) else { return; @@ -1147,6 +1184,33 @@ impl GameView { }); } + // Learning an opening: a wrong move stands on the board for a moment, in red; a + // hint is the arrow of the right move. + let flash = self + .train + .as_ref() + .and_then(|t| t.flash.as_ref()) + .map(|f| (f.after.clone(), (f.from, f.to))); + let alert = flash.as_ref().map(|(_, sq)| *sq); + let last_move = flash.as_ref().map_or(last_move, |(_, sq)| Some(*sq)); + let pos = flash.map_or(pos, |(p, _)| p); + if let Some(t) = &self.train + && t.hint + && self.cursor == self.game.line_end(NodeId::ROOT) + && let Some(sq) = t + .start + .line + .get(self.game.mainline().len()) + .and_then(move_squares) + { + arrows.push(Arrow { + from: sq.0, + to: sq.1, + color: shape_color(ShapeColor::Green), + weight: 1.0, + }); + } + // Center the eval bar + board horizontally between the left edge and the side panel. let area = ui.available_rect_before_wrap(); let show_bar = analysis.is_on(); @@ -1224,13 +1288,21 @@ impl GameView { } else { None }, - interactive: self.preview.is_none() && self.user_may_move(), + interactive: self.preview.is_none() + && self.user_may_move() + && self.train.as_ref().is_none_or(|t| { + !t.done + && t.flash.is_none() + && self.cursor == self.game.line_end(NodeId::ROOT) + }), show_coords: settings.show_coords, theme: settings.board_theme.theme(), pieces: settings.piece_set, animation: settings.animation.seconds(), premove: self.premove_side(), - auto_queen: settings.auto_queen, + // Training: the piece is always chosen (a queen for a knight is a mistake). + auto_queen: settings.auto_queen && self.train.is_none(), + alert, }; if let Some(m) = view.show(ui, &mut self.board) { self.play_move(m, actions); @@ -1238,6 +1310,7 @@ impl GameView { if let Some(drawn) = self.board.take_shape() && self.preview.is_none() && self.play.is_none() + && self.train.is_none() { self.apply_shape(drawn); } @@ -1273,6 +1346,10 @@ impl GameView { self.play_side(ui, settings, analysis, reference, hub, actions); return; } + if self.train.is_some() { + self.train_side(ui, actions); + return; + } if self.play_end.is_some() { egui::Panel::top("play_result").show(ui, |ui| self.result_strip(ui, actions)); } @@ -1371,6 +1448,8 @@ impl GameView { translations: self.translation.shown(), editor: self.editor.as_mut(), read_only: self.play.is_some(), + dim_until: None, + mistakes: None, } .show(ui); if let Some(id) = resp.clicked { @@ -1412,8 +1491,17 @@ impl GameView { shown: shown.min(mark.best.len()), }); } - if let Some((id, cmd)) = resp.context { + if let Some((_, NotationCommand::Paste)) = resp.context { + self.paste_clipboard(actions); + } else if let Some((id, NotationCommand::PlayFrom)) = resp.context { + self.play_from(id, actions); + } else if let Some((id, NotationCommand::Train)) = resp.context { + self.train_from(id, actions); + } else if let Some((id, cmd)) = resp.context { let result = match cmd { + NotationCommand::Paste + | NotationCommand::PlayFrom + | NotationCommand::Train => Ok(self.cursor), NotationCommand::Promote => { self.game.promote_variation(id).map(|_| self.cursor) } @@ -1789,6 +1877,39 @@ impl GameView { } ui.close(); } + if self.play.is_none() + && ui + .button(tr("Paste a line from the clipboard (Ctrl+V)")) + .clicked() + { + self.paste_clipboard(actions); + ui.close(); + } + if self.play.is_none() { + ui.separator(); + if ui.button(tr("Play on from here… (Ctrl+G)")).clicked() { + let at = self.cursor; + self.play_from(at, actions); + ui.close(); + } + let line = crate::train::TrainStart::from_game(&self.game, self.cursor); + if ui + .add_enabled( + line.is_some(), + egui::Button::new(tr("Learn the opening up to this move")), + ) + .on_disabled_hover_text(if self.cursor == NodeId::ROOT { + tr("Select the move to learn up to") + } else { + tr("The line has a null move (--): it cannot be played on the board") + }) + .clicked() + { + let at = self.cursor; + self.train_from(at, actions); + ui.close(); + } + } if !self.diagnostics.is_empty() && ui.button(tr("Compatibility notes")).clicked() { self.show_diagnostics = true; ui.close(); @@ -2012,7 +2133,44 @@ impl GameView { "TimeControl", &start.clock.map_or_else(|| "-".to_owned(), |tc| tc.pgn()), ); + // From a position of another game: its moves are already here; after the last + // of them, where the game comes from (a comment of the game, written in PGN). + let floor = match &start.from { + Some(from) => { + let floor = g.line_end(NodeId::ROOT); + let elo = start.strength.to_string(); + let note = match (&from.game, &from.after) { + (Some(game), Some(m)) => trf( + "Continued from {game}, after {move}. From here on, a game against Maia {elo}.", + &[("game", game), ("move", m), ("elo", &elo)], + ), + (None, Some(m)) => trf( + "Continued after {move}. From here on, a game against Maia {elo}.", + &[("move", m), ("elo", &elo)], + ), + (Some(game), None) => trf( + "Continued from {game}. From here on, a game against Maia {elo}.", + &[("game", game), ("elo", &elo)], + ), + (None, None) => { + trf("From here on, a game against Maia {elo}.", &[("elo", &elo)]) + } + }; + let (nags, mut comments) = g + .node(floor) + .map(|n| (n.nags().to_vec(), n.comments_after().to_vec())) + .unwrap_or_default(); + comments.push(note); + let _ = g.annotate(floor, nags, comments); + g.forget_history(); + floor + } + None => NodeId::ROOT, + }; g.mark_saved(); + if floor != NodeId::ROOT { + self.goto(floor); + } self.flipped = start.user == Color::Black; self.play_end = None; self.play = Some(Session { @@ -2026,6 +2184,7 @@ impl GameView { hopeless: 0, resign_offer: None, play_on: false, + floor, }); self.play_start = Some(start); self.ask_maia(); @@ -2370,7 +2529,134 @@ impl GameView { /// Before both sides have moved there is nothing to lose: the game is dropped. fn play_started(&self) -> bool { - self.game.mainline().len() >= 2 + self.played().len() >= 2 + } + + /// The moves of the game against Maia: the main line after the position it + /// started from. + fn played(&self) -> Vec { + let floor = self.play.as_ref().map_or(NodeId::ROOT, |s| s.floor); + let line = self.game.mainline(); + match line.iter().position(|&n| n == floor) { + Some(k) => line[k + 1..].to_vec(), + None => line, + } + } + + /// The user has made a move of the game against Maia. + fn user_moved(&self, user: Color) -> bool { + self.played().iter().any(|&n| { + self.game + .parent(n) + .and_then(|p| self.game.position(p)) + .is_some_and(|p| p.turn() == user) + }) + } + + /// Leaving a game before its first moves: back to the game it went on from, if + /// there is one, else to the library. + fn leave_action(&self) -> GameAction { + if self.previous.is_some() { + GameAction::ReturnToPrevious + } else { + GameAction::Back + } + } + + /// «Play on from here»: the dialog for a game against Maia from the position of + /// `at` (a finished position says why not). + fn play_from(&mut self, at: NodeId, actions: &mut Vec) { + if self.play.is_some() { + return; + } + self.commit_editor(); + self.preview = None; + match self.start_from(at) { + Ok(from) => actions.push(GameAction::PlayFrom(Box::new(from))), + Err(why) => actions.push(GameAction::Toast(why)), + } + } + + /// Where a game from the position of `at` starts: the moves to it (after the last + /// null move), the position, how to name it. + fn start_from(&self, at: NodeId) -> Result { + let g = &self.game; + let pos = g.position(at).ok_or_else(String::new)?.clone(); + let over = if pos.is_checkmate() { + Some(tr("checkmate")) + } else if pos.is_stalemate() { + Some(tr("stalemate")) + } else if pos.is_insufficient_material() { + Some(tr("neither side can checkmate")) + } else { + None + }; + if let Some(why) = over { + return Err(trf("The game is over here: {why}", &[("why", &why)])); + } + let path = g.path(at); + // A teaching null move: the game starts after the last one. + let null = path + .iter() + .rposition(|&n| g.game_move(n).is_some_and(|m| m.is_null())); + let (start_fen, from_k) = match null { + Some(k) => (g.fen(path[k]), k + 1), + None => ((!g.start().is_standard()).then(|| g.start().fen()), 1), + }; + let moves = path[from_k.min(path.len())..] + .iter() + .filter_map(|&n| match g.game_move(n)?.kind { + chess_core::MoveKind::Normal(m) => Some(m), + chess_core::MoveKind::Null => None, + }) + .collect(); + let last = g.game_move(at).and_then(|m| match m.kind { + chess_core::MoveKind::Normal(m) => Some((m.from()?, crate::board::ui_target(&m))), + chess_core::MoveKind::Null => None, + }); + let (after, after_shown) = match (g.move_number(at), g.game_move(at)) { + (Some((n, side)), Some(m)) => ( + Some(match side { + Color::White => format!("{n}.{}", m.san), + Color::Black => format!("{n}...{}", m.san), + }), + Some(move_label(n, side, &m.san, true)), + ), + _ => (None, None), + }; + let name = |t: &str| { + g.tag(t) + .map(str::trim) + .filter(|v| !v.is_empty() && *v != "?") + }; + let players = match (name("White"), name("Black")) { + (None, None) => None, + (w, b) => Some(format!("{} — {}", w.unwrap_or("?"), b.unwrap_or("?"))), + }; + let year = name("Date") + .map(|d| d.chars().take(4).collect::()) + .filter(|y| y.chars().all(|c| c.is_ascii_digit())); + let event = [name("Event").map(str::to_owned), year] + .into_iter() + .flatten() + .collect::>() + .join(" "); + let game = match (players, event.is_empty()) { + (Some(p), false) => Some(format!("{p}, {event}")), + (Some(p), true) => Some(p), + (None, false) => Some(event), + (None, true) => None, + }; + Ok(crate::play::StartFrom { + start_fen, + moves, + position: pos, + last, + after, + after_shown, + game, + null_dropped: null.is_some(), + }) } /// Resigns the game in progress (leaving it, closing the program); before the first @@ -2398,8 +2684,8 @@ impl GameView { } s.opponent.forget(); let user = s.user; - // The last move of the user on the main line. - let line = self.game.mainline(); + // The last move of the user in this game (never one of the game it went on from). + let line = self.played(); let last = line.iter().rev().find(|&&id| { self.game .parent(id) @@ -2410,12 +2696,7 @@ impl GameView { && let Ok(parent) = self.game.delete_variation(id) { self.goto(parent); - let moved = self.game.mainline().iter().any(|&n| { - self.game - .parent(n) - .and_then(|p| self.game.position(p)) - .is_some_and(|p| p.turn() == user) - }); + let moved = self.user_moved(user); if let Some(c) = self.play.as_mut().and_then(|s| s.clock.as_mut()) { c.take_back(user, moved, std::time::Instant::now()); } @@ -2476,7 +2757,7 @@ impl GameView { s.resign_asked = false; } else { ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)); - actions.push(GameAction::Back); + actions.push(self.leave_action()); } } _ => {} @@ -2644,6 +2925,13 @@ impl GameView { translations: None, editor: None, read_only: true, + dim_until: self + .play + .as_ref() + .filter(|s| s.floor != NodeId::ROOT) + .and_then(|s| self.game.node(s.floor)) + .map(|n| n.ply()), + mistakes: None, } .show(ui); if let Some(id) = resp.clicked { @@ -2766,12 +3054,7 @@ impl GameView { } ui.separator(); let user = self.play.as_ref().map_or(Color::White, |s| s.user); - let user_moved = self.game.mainline().iter().any(|&id| { - self.game - .parent(id) - .and_then(|p| self.game.position(p)) - .is_some_and(|p| p.turn() == user) - }); + let user_moved = self.user_moved(user); if ui .add_enabled(user_moved, word(tr("↶ Take back"))) .on_hover_text(tr("Take back a move (Ctrl+Z)")) @@ -2785,7 +3068,7 @@ impl GameView { .on_hover_text(tr("Leave without a result: no moves made yet")) .clicked() { - actions.push(GameAction::Back); + actions.push(self.leave_action()); } } else if self.play.as_ref().is_some_and(|s| s.resign_asked) { ui.label(RichText::new(tr("Resign?")).size(14.0)); @@ -2887,6 +3170,8 @@ impl GameView { }) .sum(); let fits = one_row <= ui.available_width(); + // A rematch from a position keeps the colour (the position is the task). + let from_side = end.start.from.as_ref().map(|_| end.user); let mut clicked = [false; 4]; let mut button = |ui: &mut Ui, k: usize, w: f32| { let mut text = RichText::new(labels[k]).size(14.0); @@ -2897,7 +3182,11 @@ impl GameView { } let mut r = ui.add(b.min_size(vec2(w, 30.0))); if k == 1 { - r = r.on_hover_text(tr("Same settings, colours swapped")); + r = r.on_hover_text(match &from_side { + Some(Color::White) => tr("The same position, you play White again"), + Some(Color::Black) => tr("The same position, you play Black again"), + None => tr("Same settings, colours swapped"), + }); } if k == 3 { r = r.on_hover_text("Ctrl+S"); @@ -2964,6 +3253,819 @@ impl GameView { } } + // ----- learning an opening (docs/design/opening-trainer.md) ---------------------- + + /// «Learn the opening up to this move»: the training opens over this game. + fn train_from(&mut self, at: NodeId, actions: &mut Vec) { + if self.play.is_some() { + return; + } + self.commit_editor(); + self.preview = None; + if let Some(mut t) = crate::train::TrainStart::from_game(&self.game, at) { + t.flipped = self.flipped; + actions.push(GameAction::Train(Box::new(t))); + } + } + + /// This screen becomes the training of `start` (its game: the line's start). + pub fn start_training(&mut self, start: crate::train::TrainStart) { + self.flipped = start.flipped; + self.train = Some(crate::train::Training::new(start)); + self.goto(NodeId::ROOT); + } + + /// The wrong move shown long enough: taken back. + fn train_tick(&mut self, ctx: &egui::Context) { + if let Some(t) = self.train.as_mut() + && let Some(f) = &t.flash + { + let now = std::time::Instant::now(); + if now >= f.until { + t.flash = None; + } else { + ctx.request_repaint_after(f.until - now); + } + } + } + + /// A move on the board while training: the line's move goes on, another one is a + /// mistake (shown for a moment, then taken back). + fn train_move(&mut self, m: Move, actions: &mut Vec) { + let end = self.game.line_end(NodeId::ROOT); + if self.cursor != end { + // A move in a past position: back to the training. + self.goto(end); + return; + } + let k = self.game.mainline().len(); + let Some(pos) = self.game.position(end).cloned() else { + return; + }; + let Some(t) = self.train.as_mut() else { return }; + if t.done || t.flash.is_some() { + return; + } + let Some(&want) = t.start.line.get(k) else { + return; + }; + if m == want { + t.hint = false; + let last = k + 1 == t.start.line.len(); + if let Ok(id) = self.game.add_move(end, m) { + // The game of the training is never «modified»: nothing to save. + self.game.forget_history(); + self.game.mark_saved(); + self.goto(id); + if last { + if let Some(t) = self.train.as_mut() { + t.finish(); + } + actions.push(GameAction::Sound(Sound::Success)); + } else if let Some(s) = self.sound_for(id) { + actions.push(GameAction::Sound(s)); + } + } + } else { + t.mistakes[k] += 1; + let mut after = pos; + after.play_unchecked(m); + t.flash = Some(crate::train::Flash { + after, + from: m.from().unwrap_or(m.to()), + to: crate::board::ui_target(&m), + until: std::time::Instant::now() + crate::train::WRONG_SHOWN, + }); + actions.push(GameAction::Sound(Sound::Wrong)); + } + } + + /// The run again from the start (after the end, or «Restart»). + fn train_again(&mut self) { + if let Some(first) = self.game.main_child(NodeId::ROOT) { + let _ = self.game.delete_variation(first); + } + self.game.forget_history(); + self.game.mark_saved(); + self.goto(NodeId::ROOT); + if let Some(t) = self.train.as_mut() { + t.again(); + } + } + + /// Leaving the training: back to the game it came from. + fn train_leave(&self) -> GameAction { + if self.previous.is_some() { + GameAction::ReturnToPrevious + } else { + GameAction::Back + } + } + + /// The side panel while training: the task above, the moves made, the user's card + /// below; at the end the result instead of both cards. + fn train_side(&mut self, ui: &mut Ui, actions: &mut Vec) { + let done = self.train.as_ref().is_some_and(|t| t.done); + egui::Panel::bottom("train_toolbar").show(ui, |ui| self.train_toolbar(ui, actions)); + if !done { + egui::Panel::bottom("train_you") + .show_separator_line(false) + .show(ui, |ui| self.train_you(ui)); + } + egui::Panel::top("train_task") + .show_separator_line(false) + .show(ui, |ui| { + if done { + self.train_result(ui, actions); + } else { + self.train_task(ui); + } + }); + let end = self.game.line_end(NodeId::ROOT); + if !done && self.cursor != end { + egui::Panel::bottom("train_viewing") + .show_separator_line(false) + .show(ui, |ui| { + if ui + .link( + RichText::new(tr( + "Viewing an earlier position · back to training — End", + )) + .weak(), + ) + .clicked() + { + self.goto(end); + } + }); + } + // At the end the moves with mistakes are marked. + let marks: Option> = + self.train.as_ref().filter(|t| t.done).map(|t| { + self.game + .mainline() + .into_iter() + .zip(t.mistakes.iter().zip(&t.shown)) + .filter(|(_, (n, _))| **n > 0) + .map(|(id, (&n, &s))| (id, (n, s))) + .collect() + }); + egui::CentralPanel::default().show(ui, |ui| { + egui::ScrollArea::vertical() + .auto_shrink(false) + .show(ui, |ui| { + let resp = Notation { + game: &self.game, + cursor: self.cursor, + scroll_to_cursor: self.scroll_to_cursor, + marks: None, + preview: None, + translations: None, + editor: None, + read_only: true, + dim_until: None, + mistakes: marks.as_ref(), + } + .show(ui); + if let Some(id) = resp.clicked { + self.goto(id); + } + self.scroll_to_cursor = false; + }); + }); + } + + /// The frame of a training card (as a clock card); red while a mistake is shown. + fn train_card(ui: &Ui, alert: bool) -> egui::Frame { + let color = if alert { + ui.visuals().error_fg_color + } else { + ui.visuals().widgets.noninteractive.bg_stroke.color + }; + egui::Frame::new() + .inner_margin(egui::Margin::symmetric(10, 6)) + .corner_radius(4) + .stroke(egui::Stroke::new(if alert { 1.5 } else { 1.0 }, color)) + } + + /// «Move 7 of 12 · ♔ White to move», «up to 12…Rd8», the progress bar. + fn train_task(&self, ui: &mut Ui) { + let Some(t) = &self.train else { return }; + let end = self.game.line_end(NodeId::ROOT); + let Some(pos) = self.game.position(end) else { + return; + }; + let played = self.game.mainline().len() as f32; + let total = t.start.line.len().max(1) as f32; + ui.add_space(4.0); + let frame = Self::train_card(ui, false).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.label( + RichText::new(trf( + "Move {n} of {last}", + &[("n", &pos.fullmoves()), ("last", &t.start.last_number)], + )) + .size(15.0), + ); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let (short, long) = match pos.turn() { + Color::White => ("♔", tr("♔ White to move")), + Color::Black => ("♚", tr("♚ Black to move")), + }; + // In a narrow panel the king alone says who moves. + let text = if ui.available_width() < 110.0 { + short + } else { + long + }; + ui.label(RichText::new(text).strong().size(15.0)) + .on_hover_text(long); + }); + }); + ui.label( + RichText::new(trf("up to {move}", &[("move", &t.start.up_to)])) + .weak() + .size(13.0), + ); + ui.add_space(3.0); + }); + // The progress: a bar of 3 along the bottom, inside the frame. + let r = frame.response.rect.shrink2(vec2(10.0, 0.0)); + let bar = egui::Rect::from_min_max( + egui::pos2(r.left(), r.bottom() - 6.0), + egui::pos2(r.right(), r.bottom() - 3.0), + ); + let p = ui.painter(); + p.rect_filled( + bar, + 1.0, + ui.visuals().widgets.noninteractive.bg_stroke.color, + ); + let done = egui::Rect::from_min_max( + bar.min, + egui::pos2(bar.left() + bar.width() * played / total, bar.bottom()), + ); + p.rect_filled(done, 1.0, ui.visuals().selection.bg_fill); + } + + /// «Mistakes: 2 · Run 3», then the history of the line — or, after a wrong move, + /// «× The game has another move here» (and from the third: «Show the move»). + fn train_you(&mut self, ui: &mut Ui) { + let k = self.game.mainline().len(); + let Some(t) = self.train.as_mut() else { return }; + let total = t.total(); + let here = t.mistakes.get(k).copied().unwrap_or(0); + let alert = t.flash.is_some(); + let mut show = false; + ui.add_space(4.0); + Self::train_card(ui, alert).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + let text = RichText::new(trf("Mistakes: {n}", &[("n", &total)])).size(15.0); + ui.label(if total == 0 { text.weak() } else { text }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label( + RichText::new(trf("Run {n}", &[("n", &(t.before.runs + 1))])) + .weak() + .size(13.0), + ); + }); + }); + let error = ui.visuals().error_fg_color; + if t.hint { + ui.label( + RichText::new(tr("Play the move on the arrow")) + .weak() + .size(13.0), + ); + } else if here > 0 { + ui.horizontal_wrapped(|ui| { + ui.label( + RichText::new(tr("× The game has another move here")) + .color(error) + .size(13.0), + ); + if here >= crate::train::HINT_AFTER { + ui.label(RichText::new("·").color(error).size(13.0)); + if ui + .link( + RichText::new(tr("Show the move")) + .color(error) + .size(13.0) + .underline(), + ) + .clicked() + { + show = true; + } + } + }); + } else { + let b = &t.before; + let history = match b.last { + None => tr("Not done before").to_owned(), + Some(last) if b.clean_streak >= 2 => trf( + "Last time: {n} · clean in a row: {k}", + &[("n", &last), ("k", &b.clean_streak)], + ), + Some(last) => trf( + "Last time: {n} · best: {m}", + &[ + ("n", &last), + ("m", &b.best.map_or("—".to_owned(), |x| x.to_string())), + ], + ), + }; + ui.add(egui::Label::new(RichText::new(history).weak().size(13.0)).truncate()); + } + }); + if show { + t.hint = true; + if let Some(s) = t.shown.get_mut(k) { + *s = true; + } + } + } + + /// The end of a run: how it went, the runs so far, «Again» and «Back to the game». + fn train_result(&mut self, ui: &mut Ui, actions: &mut Vec) { + let Some(t) = &self.train else { return }; + let Some(after) = t.after.clone() else { return }; + let total = t.total(); + let hinted = t.hinted(); + let heading = if hinted { + trf("Done with a hint · mistakes: {n}", &[("n", &total)]) + } else if total == 0 { + tr("Done without mistakes").to_owned() + } else { + trf("Done · mistakes: {n}", &[("n", &total)]) + }; + let line = trf( + "Run {n} · best: {m}", + &[ + ("n", &after.runs), + ("m", &after.best.map_or("—".to_owned(), |x| x.to_string())), + ], + ); + let streak = (after.clean_streak >= 2) + .then(|| trf("clean in a row: {k}", &[("k", &after.clean_streak)])); + // «Recent: 3 · 2 · 1 · 0», this run (the last) bold. + let recent = (after.recent.len() > 1).then(|| { + let runs: Vec = after + .recent + .iter() + .map(|(n, h)| if *h { format!("{n}*") } else { n.to_string() }) + .collect(); + let (last, rest) = runs.split_last().unwrap_or((&runs[0], &[])); + let mut head = rest.join(" · "); + head.push_str(" · "); + let text = trf("Recent: {runs}", &[("runs", &format!("{head}{last}"))]); + let weak = ui.visuals().weak_text_color(); + let strong = ui.visuals().strong_text_color(); + let font = egui::FontId::proportional(13.0); + let mut job = egui::text::LayoutJob::default(); + let cut = text.len() - last.len(); + job.append( + &text[..cut], + 0.0, + egui::TextFormat::simple(font.clone(), weak), + ); + job.append(&text[cut..], 0.0, egui::TextFormat::simple(font, strong)); + job + }); + let mut again = false; + let mut back = false; + ui.add_space(4.0); + egui::Frame::new() + .inner_margin(egui::Margin::symmetric(10, 8)) + .corner_radius(4) + .fill(ui.visuals().extreme_bg_color) + .stroke(egui::Stroke::new( + 1.0, + ui.visuals().widgets.noninteractive.bg_stroke.color, + )) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + let color = if total == 0 && !hinted { + // Lichess's «good move» green. + Color32::from_rgb(98, 153, 36) + } else { + ui.visuals().strong_text_color() + }; + ui.label(RichText::new(heading).strong().size(17.0).color(color)); + ui.label(RichText::new(line).size(13.0)); + if let Some(s) = streak { + ui.label(RichText::new(s).size(13.0)); + } + if let Some(r) = recent { + ui.add(egui::Label::new(r).wrap()); + } + ui.add_space(6.0); + let w = ui.available_width(); + let row = w >= 300.0; + let half = if row { + (w - ui.spacing().item_spacing.x) / 2.0 + } else { + w + }; + let mut buttons = |ui: &mut Ui| { + if ui + .add_sized( + [half, 30.0], + egui::Button::new(RichText::new(tr("↻ Again")).strong().size(14.0)) + .fill(ui.visuals().selection.bg_fill), + ) + .on_hover_text("Enter") + .clicked() + { + again = true; + } + if ui + .add_sized( + [half, 30.0], + egui::Button::new(RichText::new(tr("⬅ Back to the game")).size(14.0)), + ) + .on_hover_text("Esc") + .clicked() + { + back = true; + } + }; + if row { + ui.horizontal(|ui| buttons(ui)); + } else { + buttons(ui); + } + }); + if again { + self.train_again(); + } + if back { + actions.push(self.train_leave()); + } + } + + /// ⏮ ◀ ▶ ⏭ │ 🔃 │ ↻ Restart │ × Leave + fn train_toolbar(&mut self, ui: &mut Ui, actions: &mut Vec) { + ui.add_space(4.0); + ui.horizontal_wrapped(|ui| { + let big = |s: &str| RichText::new(s).size(18.0); + let word = + |s: &str| egui::Button::new(RichText::new(s).size(14.0)).min_size(vec2(0.0, 28.0)); + if ui.button(big("⏮")).clicked() { + self.goto(NodeId::ROOT); + } + if ui.button(big("◀")).clicked() { + self.step_back(); + } + if ui.button(big("▶")).clicked() { + self.step_forward(actions); + } + if ui.button(big("⏭")).clicked() { + let end = self.game.line_end(NodeId::ROOT); + self.goto(end); + } + ui.separator(); + if ui + .button(big("🔃")) + .on_hover_text(tr("Flip board (F)")) + .clicked() + { + self.flipped = !self.flipped; + } + let done = self.train.as_ref().is_some_and(|t| t.done); + if !done { + ui.separator(); + let started = self.game.main_child(NodeId::ROOT).is_some(); + if ui + .add_enabled(started, word(tr("↻ Restart"))) + .on_hover_text(tr("Start the run again; this one is not counted")) + .clicked() + { + self.train_again(); + } + if ui + .add(word(tr("× Leave"))) + .on_hover_text(tr("Back to the game; the run is not counted (Esc)")) + .clicked() + { + actions.push(self.train_leave()); + } + } + }); + ui.add_space(4.0); + } + + /// Keys while training: looking through the moves, flipping, Esc back to the game, + /// Enter again after the end; the engine stays off. + fn train_keys(&mut self, ui: &Ui, actions: &mut Vec) { + let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k); + let done = self.train.as_ref().is_some_and(|t| t.done); + let mut cmds = Vec::new(); + ui.input_mut(|i| { + if i.consume_shortcut(&ctrl(Key::W)) { + cmds.push("library"); + } + if !i.modifiers.any() { + for (key, cmd) in [ + (Key::ArrowLeft, "back1"), + (Key::ArrowRight, "fwd1"), + (Key::ArrowUp, "end"), + (Key::ArrowDown, "home"), + (Key::Home, "home"), + (Key::End, "end"), + (Key::F, "flip"), + (Key::L, "engine"), + ] { + if i.key_pressed(key) { + cmds.push(cmd); + } + } + // Esc first lets go of a piece or the choice of a promotion. + if !self.board.is_busy() && i.consume_key(Modifiers::NONE, Key::Escape) { + cmds.push("leave"); + } + if done && i.consume_key(Modifiers::NONE, Key::Enter) { + cmds.push("again"); + } + } + if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::A)) { + cmds.push("engine"); + } + }); + for cmd in cmds { + match cmd { + "back1" => self.step_back(), + "fwd1" => self.step_forward(actions), + "home" => self.goto(NodeId::ROOT), + "end" => { + let end = self.game.line_end(NodeId::ROOT); + self.goto(end); + } + "flip" => self.flipped = !self.flipped, + "engine" => actions.push(GameAction::Toast( + tr("The engine is off while training").to_owned(), + )), + "leave" => actions.push(self.train_leave()), + "library" => actions.push(GameAction::Back), + "again" => self.train_again(), + _ => {} + } + } + } + + /// Dev hook (`CP_TRAIN`): the training up to the current move. + pub fn debug_train(&self) -> Option { + let mut t = crate::train::TrainStart::from_game(&self.game, self.cursor)?; + t.flipped = self.flipped; + Some(t) + } + + /// Dev hook (`CP_TRAIN_MOVES`): moves of the training made as on the board (UCI; + /// a wrong one is a mistake). + pub fn debug_train_moves(&mut self, uci: &str) { + let mut sink = Vec::new(); + for w in uci.split_whitespace() { + self.train_tick_now(); + let end = self.game.line_end(NodeId::ROOT); + let Some(pos) = self.game.position(end).cloned() else { + return; + }; + if let Some(m) = w + .parse::() + .ok() + .and_then(|u| u.to_move(&pos).ok()) + { + self.train_move(m, &mut sink); + } + } + } + + /// The wrong move taken back at once (the hook makes moves without waiting). + fn train_tick_now(&mut self) { + if let Some(t) = self.train.as_mut() + && t.flash + .as_ref() + .is_some_and(|_| std::env::var_os("CP_TRAIN_KEEP").is_none()) + { + t.flash = None; + } + } + + /// Dev hook (`CP_PLAY_FROM`): «Play on from here» at the current move. + pub fn debug_play_from(&mut self) -> Option { + self.start_from(self.cursor).ok() + } + + /// Dev hook (`CP_PASTE_LINE`): the text pasted as a line, as by Ctrl+V. + pub fn debug_paste(&mut self, text: &str) { + self.paste_request = Some(text.to_owned()); + } + + // ----- a line from the clipboard (docs/design/paste-variation.md) ---------------- + + /// The menu's «Paste a line from the clipboard»: the clipboard read now. + fn paste_clipboard(&mut self, actions: &mut Vec) { + let text = arboard::Clipboard::new() + .and_then(|mut c| c.get_text()) + .unwrap_or_default(); + self.paste_text(&text, actions); + } + + /// Pastes `text` as a line: at once where the user stands, a question when it + /// goes elsewhere, a message when it does not fit (the game then unchanged). + fn paste_text(&mut self, text: &str, actions: &mut Vec) { + use chess_core::paste::PasteError; + if self.play.is_some() { + return; + } + self.commit_editor(); + self.preview = None; + match chess_core::paste::plan(&self.game, self.cursor, text) { + Ok(plan) if self.paste_elsewhere(&plan) => self.paste_pending = Some(plan), + Ok(plan) => self.paste_apply(plan, actions), + Err(e) => { + let msg = match &e { + PasteError::NoMoves => tr("The clipboard holds no moves").to_owned(), + PasteError::DoesNotFit => trf( + "These moves fit neither after {move} nor instead of it", + &[("move", &self.node_label(self.cursor))], + ), + PasteError::Illegal { number, side, san } => trf( + "The move {move} is impossible — nothing inserted", + &[("move", &move_label(*number, *side, san, true))], + ), + PasteError::Unrelated => tr( + "The game in the clipboard does not fit: none of its positions occur in this game", + ) + .to_owned(), + PasteError::AlreadyThere { comments: false, .. } => { + tr("These moves are already in the game").to_owned() + } + PasteError::AlreadyThere { comments: true, .. } => tr( + "These moves are already in the game — the comments from the clipboard were not carried over", + ) + .to_owned(), + }; + // «Already there»: here they are. + if let PasteError::AlreadyThere { at, .. } = e { + self.goto(at); + self.scroll_to_cursor = true; + } + actions.push(GameAction::Toast(msg)); + } + } + } + + /// The line would not go where the user looks: not the selected move, not after + /// it, not instead of it (and the start of the game looks at everything). + fn paste_elsewhere(&self, plan: &chess_core::paste::PastePlan) -> bool { + let c = self.cursor; + !(c == NodeId::ROOT + || plan.at == c + || self.game.parent(c) == Some(plan.at) + || self.game.path(plan.at).contains(&c)) + } + + /// Inserts the line: the cursor on its first move, a message naming it. + fn paste_apply( + &mut self, + mut plan: chess_core::paste::PastePlan, + actions: &mut Vec, + ) { + // The note on the move order is written in the interface's language. + plan.transposition = plan + .transposition + .take() + .map(|m| trf("By another move order: {moves}", &[("moves", &m)])); + let line = paste_line(&plan.line); + let after = (plan.at != NodeId::ROOT).then(|| self.node_label(plan.at)); + match self.game.apply_paste(&plan) { + Ok(first) => { + self.goto(first); + self.scroll_to_cursor = true; + let mut msg = if plan.continuation && plan.at != NodeId::ROOT { + trf( + "The game is continued: {moves} (Ctrl+Z to undo)", + &[("moves", &line)], + ) + } else { + match after { + Some(m) => trf( + "Line {moves} inserted after {move} (Ctrl+Z to undo)", + &[("moves", &line), ("move", &m)], + ), + None => trf( + "Line {moves} inserted at the start of the game (Ctrl+Z to undo)", + &[("moves", &line)], + ), + } + }; + if plan.games > 1 { + msg.push(' '); + msg.push_str(&trf( + "The clipboard has {count} games — the first one is inserted.", + &[("count", &plan.games)], + )); + } + actions.push(GameAction::Toast(msg)); + } + Err(e) => actions.push(GameAction::Toast(e.to_string())), + } + } + + /// «12.Nf3» / «12…Nf6» of a node, as shown (the start: «the start of the game»). + fn node_label(&self, id: NodeId) -> String { + match (self.game.move_number(id), self.game.game_move(id)) { + (Some((n, side)), Some(m)) => move_label(n, side, &m.san, true), + _ => tr("the start of the game").to_owned(), + } + } + + /// «Insert the line earlier?»: Enter inserts, Esc does not. + fn paste_question(&mut self, ctx: &egui::Context, actions: &mut Vec) { + let Some(plan) = &self.paste_pending else { + return; + }; + let from = (plan.at != NodeId::ROOT).then(|| self.node_label(plan.at)); + let cursor = self.node_label(self.cursor); + let earlier = self.game.path(self.cursor).contains(&plan.at); + let text = match (&from, earlier) { + (None, _) => { + tr("The game in the clipboard parts from this one at the start of the game.") + .to_owned() + } + (Some(f), true) => trf( + "The game in the clipboard parts from this one before the selected move: after {from}, not after {cursor}.", + &[("from", f), ("cursor", &cursor)], + ), + (Some(f), false) => trf( + "The game in the clipboard parts from this one in another line: after {from}.", + &[("from", f)], + ), + }; + let button = match &from { + Some(f) => trf("Insert after {move}", &[("move", f)]), + None => tr("Insert at the start").to_owned(), + }; + let line = paste_line_full(&plan.line); + let source = plan.source_ref.clone(); + let mut choice = None; + let width = (ctx.content_rect().width() - 32.0).min(460.0); + egui::Modal::new(egui::Id::new("paste_question")).show(ctx, |ui| { + ui.set_width(width); + ui.heading(tr("Insert the line earlier?")); + ui.add_space(4.0); + ui.label(text); + ui.add_space(8.0); + egui::Frame::new() + .inner_margin(egui::Margin::same(8)) + .corner_radius(4) + .stroke(egui::Stroke::new( + 1.0, + ui.visuals().widgets.noninteractive.bg_stroke.color, + )) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.add(egui::Label::new(RichText::new(&line).size(14.0)).truncate()); + if let Some(s) = &source { + ui.label(RichText::new(s).weak().size(13.0)); + } + }); + ui.add_space(10.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::widgets::primary(ui, &button).clicked() { + choice = Some(true); + } + if ui + .add(egui::Button::new(tr("Cancel")).min_size(vec2(0.0, 30.0))) + .clicked() + { + choice = Some(false); + } + }); + }); + if choice.is_none() { + ctx.input_mut(|i| { + if i.consume_key(Modifiers::NONE, Key::Enter) { + choice = Some(true); + } else if i.consume_key(Modifiers::NONE, Key::Escape) { + choice = Some(false); + } + }); + } + match choice { + Some(true) => { + if let Some(plan) = self.paste_pending.take() { + self.paste_apply(plan, actions); + } + } + Some(false) => self.paste_pending = None, + None => {} + } + } + /// Dev hook (`CP_COMMENT_EDIT`): the editor on the current move. pub fn debug_comment_edit(&mut self) { self.open_editor(Slot::After(self.cursor)); @@ -3026,10 +4128,31 @@ impl GameView { if ui.ctx().egui_wants_keyboard_input() { return; } + // A modal question or dialog over the game has the keys (its Enter and Esc); + // the game under it does not change. + if self.paste_pending.is_some() || ui.ctx().memory(|m| m.top_modal_layer()).is_some() { + return; + } if self.play.is_some() { self.play_keys(ui, actions); return; } + if self.train.is_some() { + self.train_keys(ui, actions); + return; + } + // Ctrl+V: egui gives it as the text pasted, not as a key. + let pasted = ui.input(|i| { + i.events.iter().find_map(|e| match e { + egui::Event::Paste(t) => Some(t.clone()), + _ => None, + }) + }); + if let Some(text) = pasted + && self.paste_pending.is_none() + { + self.paste_text(&text, actions); + } let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k); let ctrl_shift = |k| KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, k); let overlay = crate::app::overlay_open(ui.ctx()); @@ -3059,6 +4182,9 @@ impl GameView { if i.consume_shortcut(&ctrl(Key::W)) { cmds.push("back"); } + if i.consume_shortcut(&ctrl(Key::G)) { + cmds.push("play_from"); + } if i.consume_shortcut(&ctrl_shift(Key::F)) { cmds.push("find"); } @@ -3132,6 +4258,10 @@ impl GameView { } "copy" => actions.push(self.copy_pgn()), "save" => actions.push(GameAction::Save), + "play_from" => { + let at = self.cursor; + self.play_from(at, actions); + } "add_to_db" => actions.push(GameAction::AddToDatabase), "game_data" => actions.push(GameAction::EditGameData), "back" => actions.push(GameAction::Back), @@ -3491,3 +4621,31 @@ pub(crate) fn text_width(ui: &Ui, text: &str, style: egui::TextStyle) -> f32 { .size() .x } + +/// A move as shown: «12.Nf3», «12…Nf6» (`numbered`: black's number too). +fn move_label(n: u32, side: Color, san: &str, numbered: bool) -> String { + let label = match side { + Color::White => format!("{n}.{san}"), + Color::Black if numbered => format!("{n}…{san}"), + Color::Black => san.to_owned(), + }; + crate::san::show(&label).into_owned() +} + +/// The moves of a pasted line as shown: all of a short one, else «first … last». +fn paste_line(line: &[(u32, Color, String)]) -> String { + if line.len() <= 3 { + return paste_line_full(line); + } + let one = |(n, side, san): &(u32, Color, String)| move_label(*n, *side, san, true); + format!("{} … {}", one(&line[0]), one(&line[line.len() - 1])) +} + +/// Every move of a line, numbered as in the notation. +fn paste_line_full(line: &[(u32, Color, String)]) -> String { + line.iter() + .enumerate() + .map(|(i, (n, side, san))| move_label(*n, *side, san, i == 0)) + .collect::>() + .join(" ") +} diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 54b96b2..f902e49 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -11001,6 +11001,779 @@ const ROWS: &[[&str; 9]] = &[ "taslim bo‘lmoqda", "беріледі", ], + // --- paste a line --- + [ + "Paste a line from the clipboard (Ctrl+V)", + "Вставить вариант из буфера (Ctrl+V)", + "Coller une variante depuis le presse-papiers (Ctrl+V)", + "Variante aus der Zwischenablage einfügen (Ctrl+V)", + "Pegar una variante del portapapeles (Ctrl+V)", + "Incolla una variante dagli appunti (Ctrl+V)", + "Colar uma variante da área de transferência (Ctrl+V)", + "Buferdan variant qo‘yish (Ctrl+V)", + "Буферден вариант қою (Ctrl+V)", + ], + [ + "The clipboard holds no moves", + "В буфере нет ходов", + "Le presse-papiers ne contient aucun coup", + "Die Zwischenablage enthält keine Züge", + "El portapapeles no contiene jugadas", + "Gli appunti non contengono mosse", + "A área de transferência não contém lances", + "Buferda yurishlar yo‘q", + "Буферде жүрістер жоқ", + ], + [ + "These moves fit neither after {move} nor instead of it", + "Эти ходы нельзя сделать ни после {move}, ни вместо него", + "Ces coups ne peuvent être joués ni après {move}, ni à sa place", + "Diese Züge passen weder nach {move} noch an seiner Stelle", + "Estas jugadas no caben ni después de {move} ni en su lugar", + "Queste mosse non si possono giocare né dopo {move} né al suo posto", + "Estes lances não cabem nem depois de {move} nem no lugar dele", + "Bu yurishlarni {move} yurishidan keyin ham, uning o‘rniga ham qilib bo‘lmaydi", + "Бұл жүрістерді {move} жүрісінен кейін де, оның орнына да жасау мүмкін емес", + ], + [ + "The move {move} is impossible — nothing inserted", + "Ход {move} невозможен — ничего не вставлено", + "Le coup {move} est impossible — rien n’a été inséré", + "Der Zug {move} ist unmöglich — nichts eingefügt", + "La jugada {move} es imposible — no se insertó nada", + "La mossa {move} è impossibile — non è stato inserito nulla", + "O lance {move} é impossível — nada foi inserido", + "{move} yurishi mumkin emas — hech narsa qo‘yilmadi", + "{move} жүрісі мүмкін емес — ештеңе қойылмады", + ], + [ + "The game in the clipboard does not fit: none of its positions occur in this game", + "Партия из буфера сюда не подходит: в этой партии нет её позиций", + "La partie du presse-papiers ne convient pas : aucune de ses positions n’apparaît dans cette partie", + "Die Partie aus der Zwischenablage passt nicht: keine ihrer Stellungen kommt in dieser Partie vor", + "La partida del portapapeles no encaja: ninguna de sus posiciones aparece en esta partida", + "La partita negli appunti non è compatibile: nessuna delle sue posizioni compare in questa partita", + "A partida da área de transferência não se encaixa: nenhuma de suas posições ocorre nesta partida", + "Buferdagi partiya bu yerga mos kelmaydi: uning pozitsiyalari bu partiyada yo‘q", + "Буфердегі партия бұл жерге сәйкес келмейді: оның позициялары бұл партияда жоқ", + ], + [ + "These moves are already in the game", + "Эти ходы уже есть в партии", + "Ces coups figurent déjà dans la partie", + "Diese Züge sind bereits in der Partie", + "Estas jugadas ya están en la partida", + "Queste mosse sono già nella partita", + "Estes lances já estão na partida", + "Bu yurishlar partiyada allaqachon bor", + "Бұл жүрістер партияда бұрыннан бар", + ], + [ + "These moves are already in the game — the comments from the clipboard were not carried over", + "Эти ходы уже есть в партии — комментарии из буфера не перенесены", + "Ces coups figurent déjà dans la partie — les commentaires du presse-papiers n’ont pas été repris", + "Diese Züge sind bereits in der Partie — die Kommentare aus der Zwischenablage wurden nicht übernommen", + "Estas jugadas ya están en la partida — los comentarios del portapapeles no se trasladaron", + "Queste mosse sono già nella partita — i commenti degli appunti non sono stati riportati", + "Estes lances já estão na partida — os comentários da área de transferência não foram transferidos", + "Bu yurishlar partiyada allaqachon bor — buferdagi izohlar ko‘chirilmadi", + "Бұл жүрістер партияда бұрыннан бар — буфердегі түсініктемелер көшірілмеді", + ], + [ + "By another move order: {moves}", + "Другим порядком ходов: {moves}", + "Par un autre ordre de coups : {moves}", + "Mit anderer Zugfolge: {moves}", + "Con otro orden de jugadas: {moves}", + "Con un altro ordine di mosse: {moves}", + "Por outra ordem de lances: {moves}", + "Boshqa yurishlar tartibida: {moves}", + "Басқа жүріс ретімен: {moves}", + ], + [ + "The game is continued: {moves} (Ctrl+Z to undo)", + "Партия продолжена: {moves} (Ctrl+Z — отменить)", + "Partie prolongée : {moves} (Ctrl+Z pour annuler)", + "Partie fortgesetzt: {moves} (Ctrl+Z zum Rückgängigmachen)", + "Partida continuada: {moves} (Ctrl+Z para deshacer)", + "Partita proseguita: {moves} (Ctrl+Z per annullare)", + "Partida continuada: {moves} (Ctrl+Z para desfazer)", + "Partiya davom ettirildi: {moves} (bekor qilish: Ctrl+Z)", + "Партия жалғастырылды: {moves} (болдырмау — Ctrl+Z)", + ], + [ + "Line {moves} inserted after {move} (Ctrl+Z to undo)", + "Вариант {moves} вставлен после {move} (Ctrl+Z — отменить)", + "Variante {moves} insérée après {move} (Ctrl+Z pour annuler)", + "Variante {moves} nach {move} eingefügt (Ctrl+Z zum Rückgängigmachen)", + "Variante {moves} insertada después de {move} (Ctrl+Z para deshacer)", + "Variante {moves} inserita dopo {move} (Ctrl+Z per annullare)", + "Variante {moves} inserida depois de {move} (Ctrl+Z para desfazer)", + "{moves} varianti {move} yurishidan keyin qo‘yildi (bekor qilish: Ctrl+Z)", + "{moves} варианты {move} жүрісінен кейін қойылды (болдырмау — Ctrl+Z)", + ], + [ + "Line {moves} inserted at the start of the game (Ctrl+Z to undo)", + "Вариант {moves} вставлен в начале партии (Ctrl+Z — отменить)", + "Variante {moves} insérée au début de la partie (Ctrl+Z pour annuler)", + "Variante {moves} am Anfang der Partie eingefügt (Ctrl+Z zum Rückgängigmachen)", + "Variante {moves} insertada al inicio de la partida (Ctrl+Z para deshacer)", + "Variante {moves} inserita all’inizio della partita (Ctrl+Z per annullare)", + "Variante {moves} inserida no início da partida (Ctrl+Z para desfazer)", + "{moves} varianti partiya boshiga qo‘yildi (bekor qilish: Ctrl+Z)", + "{moves} варианты партияның басына қойылды (болдырмау — Ctrl+Z)", + ], + [ + "The clipboard has {count} games — the first one is inserted.", + "В буфере партий: {count} — вставлена первая.", + "Parties dans le presse-papiers : {count} — la première est insérée.", + "Partien in der Zwischenablage: {count} — die erste wurde eingefügt.", + "Partidas en el portapapeles: {count} — se insertó la primera.", + "Partite negli appunti: {count} — è stata inserita la prima.", + "Partidas na área de transferência: {count} — a primeira foi inserida.", + "Buferdagi partiyalar: {count} — birinchisi qo‘yildi.", + "Буфердегі партиялар: {count} — біріншісі қойылды.", + ], + [ + "the start of the game", + "начало партии", + "le début de la partie", + "der Partieanfang", + "el inicio de la partida", + "l’inizio della partita", + "o início da partida", + "partiya boshi", + "партия басы", + ], + [ + "The game in the clipboard parts from this one at the start of the game.", + "Партия из буфера расходится с этой в самом начале.", + "La partie du presse-papiers diverge de celle-ci dès le début.", + "Die Partie aus der Zwischenablage weicht von dieser gleich am Anfang ab.", + "La partida del portapapeles se separa de esta desde el inicio.", + "La partita negli appunti si discosta da questa fin dall’inizio.", + "A partida da área de transferência diverge desta logo no início.", + "Buferdagi partiya bu partiyadan boshidanoq ajraladi.", + "Буфердегі партия бұл партиядан ең басында ажырайды.", + ], + [ + "The game in the clipboard parts from this one before the selected move: after {from}, not after {cursor}.", + "Партия из буфера расходится с этой раньше выбранного хода: после {from}, а не после {cursor}.", + "La partie du presse-papiers diverge de celle-ci avant le coup sélectionné : après {from}, et non après {cursor}.", + "Die Partie aus der Zwischenablage weicht von dieser schon vor dem gewählten Zug ab: nach {from}, nicht nach {cursor}.", + "La partida del portapapeles se separa de esta antes de la jugada seleccionada: después de {from}, no después de {cursor}.", + "La partita negli appunti si discosta da questa prima della mossa selezionata: dopo {from}, non dopo {cursor}.", + "A partida da área de transferência diverge desta antes do lance selecionado: depois de {from}, não depois de {cursor}.", + "Buferdagi partiya bu partiyadan tanlangan yurishdan oldin ajraladi: {from} yurishidan keyin, {cursor} yurishidan keyin emas.", + "Буфердегі партия бұл партиядан таңдалған жүрістен бұрын ажырайды: {from} жүрісінен кейін, {cursor} жүрісінен кейін емес.", + ], + [ + "The game in the clipboard parts from this one in another line: after {from}.", + "Партия из буфера расходится с этой в другом варианте: после {from}.", + "La partie du presse-papiers diverge de celle-ci dans une autre variante : après {from}.", + "Die Partie aus der Zwischenablage weicht von dieser in einer anderen Variante ab: nach {from}.", + "La partida del portapapeles se separa de esta en otra variante: después de {from}.", + "La partita negli appunti si discosta da questa in un’altra variante: dopo {from}.", + "A partida da área de transferência diverge desta em outra variante: depois de {from}.", + "Buferdagi partiya bu partiyadan boshqa variantda ajraladi: {from} yurishidan keyin.", + "Буфердегі партия бұл партиядан басқа вариантта ажырайды: {from} жүрісінен кейін.", + ], + [ + "Insert after {move}", + "Вставить после {move}", + "Insérer après {move}", + "Nach {move} einfügen", + "Insertar después de {move}", + "Inserisci dopo {move}", + "Inserir depois de {move}", + "{move} yurishidan keyin qo‘yish", + "{move} жүрісінен кейін қою", + ], + [ + "Insert at the start", + "Вставить в начале", + "Insérer au début", + "Am Anfang einfügen", + "Insertar al inicio", + "Inserisci all’inizio", + "Inserir no início", + "Boshiga qo‘yish", + "Басына қою", + ], + [ + "Insert the line earlier?", + "Вставить вариант раньше?", + "Insérer la variante plus tôt ?", + "Variante früher einfügen?", + "¿Insertar la variante antes?", + "Inserire la variante prima?", + "Inserir a variante antes?", + "Variant oldinroq qo‘yilsinmi?", + "Вариант ертерек қойылсын ба?", + ], + [ + "Paste a line from the clipboard", + "Вставить вариант из буфера", + "Coller une variante depuis le presse-papiers", + "Variante aus der Zwischenablage einfügen", + "Pegar una variante del portapapeles", + "Incolla una variante dagli appunti", + "Colar uma variante da área de transferência", + "Buferdan variant qo‘yish", + "Буферден вариант қою", + ], + [ + "Moves or a PGN game from the clipboard, as a variation from where they part from this game", + "Ходы или партия PGN из буфера — вариантом с того места, где они расходятся с этой партией", + "Des coups ou une partie PGN du presse-papiers, en variante à partir de l’endroit où ils divergent de cette partie", + "Züge oder eine PGN-Partie aus der Zwischenablage, als Variante ab der Stelle, an der sie von dieser Partie abweichen", + "Jugadas o una partida PGN del portapapeles, como variante desde donde se separan de esta partida", + "Mosse o una partita PGN dagli appunti, come variante dal punto in cui si discostano da questa partita", + "Lances ou uma partida PGN da área de transferência, como variante a partir de onde divergem desta partida", + "Buferdagi yurishlar yoki PGN partiya — bu partiyadan ajralgan joyidan variant sifatida", + "Буфердегі жүрістер немесе PGN партиясы — осы партиядан ажырайтын жерден вариант ретінде", + ], + // --- play on from here --- + [ + "Play on from here… (Ctrl+G)", + "Играть отсюда… (Ctrl+G)", + "Jouer à partir d’ici… (Ctrl+G)", + "Von hier aus spielen… (Ctrl+G)", + "Jugar desde aquí… (Ctrl+G)", + "Gioca da qui… (Ctrl+G)", + "Jogar a partir daqui… (Ctrl+G)", + "Shu yerdan o‘ynash… (Ctrl+G)", + "Осы жерден ойнау… (Ctrl+G)", + ], + [ + "Play on from here…", + "Играть отсюда…", + "Jouer à partir d’ici…", + "Von hier aus spielen…", + "Jugar desde aquí…", + "Gioca da qui…", + "Jogar a partir daqui…", + "Shu yerdan o‘ynash…", + "Осы жерден ойнау…", + ], + [ + "A game against Maia from this position", + "Партия с Maia из этой позиции", + "Une partie contre Maia à partir de cette position", + "Eine Partie gegen Maia aus dieser Stellung", + "Una partida contra Maia desde esta posición", + "Una partita contro Maia da questa posizione", + "Uma partida contra Maia a partir desta posição", + "Shu pozitsiyadan Maia bilan o‘yin", + "Осы позициядан Maia-мен партия", + ], + [ + "The game is over here: {why}", + "Здесь партия окончена: {why}", + "La partie est terminée ici : {why}", + "Hier ist die Partie zu Ende: {why}", + "Aquí la partida ha terminado: {why}", + "Qui la partita è finita: {why}", + "Aqui a partida terminou: {why}", + "Bu yerda o‘yin tugagan: {why}", + "Мұнда партия аяқталған: {why}", + ], + [ + "From the position after {move}", + "С позиции после {move}", + "À partir de la position après {move}", + "Aus der Stellung nach {move}", + "Desde la posición tras {move}", + "Dalla posizione dopo {move}", + "A partir da posição após {move}", + "{move} yurishidan keyingi pozitsiyadan", + "{move} жүрісінен кейінгі позициядан", + ], + [ + "From the game's starting position", + "С начальной позиции партии", + "À partir de la position de départ de la partie", + "Aus der Anfangsstellung der Partie", + "Desde la posición inicial de la partida", + "Dalla posizione iniziale della partita", + "A partir da posição inicial da partida", + "O‘yinning boshlang‘ich pozitsiyasidan", + "Партияның бастапқы позициясынан", + ], + [ + "from the game {game}", + "из партии {game}", + "de la partie {game}", + "aus der Partie {game}", + "de la partida {game}", + "dalla partita {game}", + "da partida {game}", + "{game} o‘yinidan", + "{game} партиясынан", + ], + [ + "The moves before the null move (--) are not carried over", + "Ходы до пропуска хода (--) в игру не войдут", + "Les coups avant le coup nul (--) ne sont pas repris", + "Die Züge vor dem Nullzug (--) werden nicht übernommen", + "Las jugadas antes de la jugada nula (--) no se incluyen", + "Le mosse prima della mossa nulla (--) non vengono riprese", + "Os lances antes do lance nulo (--) não são incluídos", + "Bo‘sh yurishdan (--) oldingi yurishlar o‘yinga kirmaydi", + "Бос жүріске (--) дейінгі жүрістер ойынға кірмейді", + ], + [ + "Continued from {game}, after {move}. From here on, a game against Maia {elo}.", + "Продолжение партии {game}, после {move}. Дальше — игра с Maia {elo}.", + "Suite de la partie {game}, après {move}. À partir d’ici, une partie contre Maia {elo}.", + "Fortsetzung der Partie {game} nach {move}. Ab hier eine Partie gegen Maia {elo}.", + "Continuación de la partida {game}, tras {move}. A partir de aquí, una partida contra Maia {elo}.", + "Seguito della partita {game}, dopo {move}. Da qui, una partita contro Maia {elo}.", + "Continuação da partida {game}, após {move}. A partir daqui, uma partida contra Maia {elo}.", + "{game} o‘yinining davomi, {move} dan keyin. Bundan keyin — Maia {elo} bilan o‘yin.", + "{game} партиясының жалғасы, {move} кейін. Бұдан әрі — Maia {elo}-мен ойын.", + ], + [ + "Continued after {move}. From here on, a game against Maia {elo}.", + "Продолжение после {move}. Дальше — игра с Maia {elo}.", + "Suite après {move}. À partir d’ici, une partie contre Maia {elo}.", + "Fortsetzung nach {move}. Ab hier eine Partie gegen Maia {elo}.", + "Continuación tras {move}. A partir de aquí, una partida contra Maia {elo}.", + "Seguito dopo {move}. Da qui, una partita contro Maia {elo}.", + "Continuação após {move}. A partir daqui, uma partida contra Maia {elo}.", + "{move} dan keyingi davomi. Bundan keyin — Maia {elo} bilan o‘yin.", + "{move} кейінгі жалғасы. Бұдан әрі — Maia {elo}-мен ойын.", + ], + [ + "Continued from {game}. From here on, a game against Maia {elo}.", + "Продолжение партии {game}. Дальше — игра с Maia {elo}.", + "Suite de la partie {game}. À partir d’ici, une partie contre Maia {elo}.", + "Fortsetzung der Partie {game}. Ab hier eine Partie gegen Maia {elo}.", + "Continuación de la partida {game}. A partir de aquí, una partida contra Maia {elo}.", + "Seguito della partita {game}. Da qui, una partita contro Maia {elo}.", + "Continuação da partida {game}. A partir daqui, uma partida contra Maia {elo}.", + "{game} o‘yinining davomi. Bundan keyin — Maia {elo} bilan o‘yin.", + "{game} партиясының жалғасы. Бұдан әрі — Maia {elo}-мен ойын.", + ], + [ + "From here on, a game against Maia {elo}.", + "Дальше — игра с Maia {elo}.", + "À partir d’ici, une partie contre Maia {elo}.", + "Ab hier eine Partie gegen Maia {elo}.", + "A partir de aquí, una partida contra Maia {elo}.", + "Da qui, una partita contro Maia {elo}.", + "A partir daqui, uma partida contra Maia {elo}.", + "Bundan keyin — Maia {elo} bilan o‘yin.", + "Бұдан әрі — Maia {elo}-мен ойын.", + ], + // --- learning an opening --- + [ + "Learning the opening: {game}", + "Учим дебют: {game}", + "Apprentissage de l'ouverture : {game}", + "Eröffnung lernen: {game}", + "Aprendiendo la apertura: {game}", + "Studio dell'apertura: {game}", + "Aprendendo a abertura: {game}", + "Debyutni o‘rganish: {game}", + "Дебютті үйрену: {game}", + ], + [ + "Learning the opening", + "Учим дебют", + "Apprentissage de l'ouverture", + "Eröffnung lernen", + "Aprendiendo la apertura", + "Studio dell'apertura", + "Aprendendo a abertura", + "Debyutni o‘rganish", + "Дебютті үйрену", + ], + [ + "up to {move}", + "до {move}", + "jusqu'à {move}", + "bis {move}", + "hasta {move}", + "fino a {move}", + "até {move}", + "{move} gacha", + "{move} дейін", + ], + [ + "Learn the opening up to this move", + "Учить дебют до этого хода", + "Apprendre l'ouverture jusqu'à ce coup", + "Eröffnung bis zu diesem Zug lernen", + "Aprender la apertura hasta esta jugada", + "Studia l'apertura fino a questa mossa", + "Aprender a abertura até este lance", + "Debyutni shu yurishgacha o‘rganish", + "Дебютті осы жүріске дейін үйрену", + ], + [ + "Select the move to learn up to", + "Выберите ход, до которого учить", + "Choisissez le coup jusqu'auquel apprendre", + "Wählen Sie den Zug, bis zu dem gelernt wird", + "Elige la jugada hasta la que aprender", + "Scegli la mossa fino a cui studiare", + "Escolha o lance até onde aprender", + "O‘rganiladigan oxirgi yurishni tanlang", + "Үйренетін соңғы жүрісті таңдаңыз", + ], + [ + "The line has a null move (--): it cannot be played on the board", + "В линии есть пропуск хода (--) — его нельзя сыграть на доске", + "La ligne contient un coup nul (--) : il ne peut pas être joué sur l'échiquier", + "Die Linie enthält einen Nullzug (--): er kann nicht auf dem Brett gespielt werden", + "La línea tiene una jugada nula (--): no se puede jugar en el tablero", + "La linea contiene una mossa nulla (--): non si può giocare sulla scacchiera", + "A linha tem um lance nulo (--): ele não pode ser jogado no tabuleiro", + "Liniyada bo‘sh yurish (--) bor: uni taxtada o‘ynab bo‘lmaydi", + "Линияда бос жүріс (--) бар: оны тақтада ойнауға болмайды", + ], + [ + "Viewing an earlier position · back to training — End", + "Просмотр прошлой позиции · к тренировке — End", + "Position antérieure affichée · retour à l'entraînement — End", + "Frühere Stellung wird angezeigt · zurück zum Training — End", + "Viendo una posición anterior · volver al entrenamiento — End", + "Posizione precedente · torna all'allenamento — End", + "Vendo uma posição anterior · voltar ao treino — End", + "Oldingi pozitsiya ko‘rilmoqda · mashg‘ulotga qaytish — End", + "Бұрынғы позиция көрсетілуде · жаттығуға оралу — End", + ], + [ + "Move {n} of {last}", + "Ход {n} из {last}", + "Coup {n} sur {last}", + "Zug {n} von {last}", + "Jugada {n} de {last}", + "Mossa {n} di {last}", + "Lance {n} de {last}", + "Yurish {n} / {last}", + "Жүріс {n} / {last}", + ], + [ + "♔ White to move", + "♔ ход белых", + "♔ Trait aux Blancs", + "♔ Weiß am Zug", + "♔ Juegan blancas", + "♔ Muove il Bianco", + "♔ Brancas jogam", + "♔ Oqlar yuradi", + "♔ Ақтар жүреді", + ], + [ + "♚ Black to move", + "♚ ход чёрных", + "♚ Trait aux Noirs", + "♚ Schwarz am Zug", + "♚ Juegan negras", + "♚ Muove il Nero", + "♚ Pretas jogam", + "♚ Qoralar yuradi", + "♚ Қаралар жүреді", + ], + [ + "Mistakes: {n}", + "Ошибок: {n}", + "Erreurs : {n}", + "Fehler: {n}", + "Errores: {n}", + "Errori: {n}", + "Erros: {n}", + "Xatolar: {n}", + "Қателер: {n}", + ], + [ + "Run {n}", + "Прохождение {n}", + "Passage {n}", + "Durchgang {n}", + "Repaso {n}", + "Giro {n}", + "Rodada {n}", + "Urinish {n}", + "Әрекет {n}", + ], + [ + "Play the move on the arrow", + "Сделайте ход со стрелки", + "Jouez le coup indiqué par la flèche", + "Spielen Sie den Zug des Pfeils", + "Juega la jugada de la flecha", + "Gioca la mossa indicata dalla freccia", + "Jogue o lance da seta", + "Strelkadagi yurishni qiling", + "Көрсеткідегі жүрісті жасаңыз", + ], + [ + "× The game has another move here", + "× В партии — другой ход", + "× La partie a un autre coup ici", + "× In der Partie folgt hier ein anderer Zug", + "× En la partida hay otra jugada aquí", + "× Nella partita qui c'è un'altra mossa", + "× Na partida há outro lance aqui", + "× Partiyada bu yerda boshqa yurish", + "× Партияда мұнда басқа жүріс", + ], + [ + "Show the move", + "Показать ход", + "Montrer le coup", + "Zug zeigen", + "Mostrar la jugada", + "Mostra la mossa", + "Mostrar o lance", + "Yurishni ko‘rsatish", + "Жүрісті көрсету", + ], + [ + "Not done before", + "Эту линию ещё не проходили", + "Ligne jamais parcourue", + "Diese Linie noch nicht geübt", + "Línea aún no repasada", + "Linea mai ripassata", + "Linha ainda não treinada", + "Bu liniya hali o‘tilmagan", + "Бұл линия әлі өтілмеген", + ], + [ + "Last time: {n} · clean in a row: {k}", + "Прошлое: {n} · без ошибок подряд: {k}", + "La dernière fois : {n} · sans erreur d'affilée : {k}", + "Zuletzt: {n} · fehlerfrei in Folge: {k}", + "La última vez: {n} · sin errores seguidos: {k}", + "L'ultima volta: {n} · senza errori di fila: {k}", + "Última vez: {n} · sem erros seguidos: {k}", + "Oxirgi marta: {n} · ketma-ket xatosiz: {k}", + "Соңғы рет: {n} · қатарынан қатесіз: {k}", + ], + [ + "Last time: {n} · best: {m}", + "Прошлое: {n} · лучшее: {m}", + "La dernière fois : {n} · meilleur : {m}", + "Zuletzt: {n} · Bestwert: {m}", + "La última vez: {n} · mejor: {m}", + "L'ultima volta: {n} · migliore: {m}", + "Última vez: {n} · melhor: {m}", + "Oxirgi marta: {n} · eng yaxshi: {m}", + "Соңғы рет: {n} · ең үздігі: {m}", + ], + [ + "Done with a hint · mistakes: {n}", + "Пройдено с подсказкой · ошибок: {n}", + "Terminé avec un indice · erreurs : {n}", + "Mit Hinweis geschafft · Fehler: {n}", + "Completado con pista · errores: {n}", + "Completato con un aiuto · errori: {n}", + "Concluído com dica · erros: {n}", + "Yordam bilan o‘tildi · xatolar: {n}", + "Көмекпен өтілді · қателер: {n}", + ], + [ + "Done without mistakes", + "Пройдено без ошибок", + "Terminé sans erreur", + "Fehlerfrei geschafft", + "Completado sin errores", + "Completato senza errori", + "Concluído sem erros", + "Xatosiz o‘tildi", + "Қатесіз өтілді", + ], + [ + "Done · mistakes: {n}", + "Пройдено · ошибок: {n}", + "Terminé · erreurs : {n}", + "Geschafft · Fehler: {n}", + "Completado · errores: {n}", + "Completato · errori: {n}", + "Concluído · erros: {n}", + "O‘tildi · xatolar: {n}", + "Өтілді · қателер: {n}", + ], + [ + "Run {n} · best: {m}", + "Прохождение {n} · лучшее: {m}", + "Passage {n} · meilleur : {m}", + "Durchgang {n} · Bestwert: {m}", + "Repaso {n} · mejor: {m}", + "Giro {n} · migliore: {m}", + "Rodada {n} · melhor: {m}", + "Urinish {n} · eng yaxshi: {m}", + "Әрекет {n} · ең үздігі: {m}", + ], + [ + "clean in a row: {k}", + "без ошибок подряд: {k}", + "sans erreur d'affilée : {k}", + "fehlerfrei in Folge: {k}", + "sin errores seguidos: {k}", + "senza errori di fila: {k}", + "sem erros seguidos: {k}", + "ketma-ket xatosiz: {k}", + "қатарынан қатесіз: {k}", + ], + [ + "Recent: {runs}", + "Последние: {runs}", + "Récents : {runs}", + "Letzte: {runs}", + "Recientes: {runs}", + "Recenti: {runs}", + "Recentes: {runs}", + "So‘nggilari: {runs}", + "Соңғылары: {runs}", + ], + [ + "↻ Again", + "↻ Повторить", + "↻ Encore", + "↻ Noch einmal", + "↻ Otra vez", + "↻ Ancora", + "↻ De novo", + "↻ Yana", + "↻ Қайталау", + ], + [ + "⬅ Back to the game", + "⬅ К партии", + "⬅ Retour à la partie", + "⬅ Zurück zur Partie", + "⬅ Volver a la partida", + "⬅ Torna alla partita", + "⬅ Voltar à partida", + "⬅ Partiyaga qaytish", + "⬅ Партияға оралу", + ], + [ + "↻ Restart", + "↻ Сначала", + "↻ Recommencer", + "↻ Neu starten", + "↻ Reiniciar", + "↻ Ricomincia", + "↻ Recomeçar", + "↻ Boshidan", + "↻ Басынан", + ], + [ + "Start the run again; this one is not counted", + "Начать прохождение заново — это не засчитывается", + "Recommencer le passage ; celui-ci n'est pas compté", + "Durchgang neu beginnen; dieser wird nicht gezählt", + "Empezar el repaso de nuevo; este no cuenta", + "Ricomincia il giro; questo non viene contato", + "Começar a rodada de novo; esta não conta", + "Urinishni qaytadan boshlash; bu hisobga olinmaydi", + "Әрекетті қайта бастау; бұл есептелмейді", + ], + [ + "× Leave", + "× Выйти", + "× Quitter", + "× Beenden", + "× Salir", + "× Esci", + "× Sair", + "× Chiqish", + "× Шығу", + ], + [ + "Back to the game; the run is not counted (Esc)", + "К партии — прохождение не засчитывается (Esc)", + "Retour à la partie ; le passage n'est pas compté (Esc)", + "Zurück zur Partie; der Durchgang wird nicht gezählt (Esc)", + "Volver a la partida; el repaso no cuenta (Esc)", + "Torna alla partita; il giro non viene contato (Esc)", + "Voltar à partida; a rodada não conta (Esc)", + "Partiyaga qaytish; urinish hisobga olinmaydi (Esc)", + "Партияға оралу; әрекет есептелмейді (Esc)", + ], + [ + "The engine is off while training", + "Во время тренировки движок выключен", + "Le moteur est désactivé pendant l'entraînement", + "Die Engine ist während des Trainings aus", + "El motor está apagado durante el entrenamiento", + "Il motore è spento durante l'allenamento", + "O motor fica desligado durante o treino", + "Mashg‘ulot paytida dvigatel o‘chiq", + "Жаттығу кезінде қозғалтқыш өшірулі", + ], + [ + "Mistakes: {n}; the move was shown", + "Ошибок: {n}, ход показан", + "Erreurs : {n} ; le coup a été montré", + "Fehler: {n}; der Zug wurde gezeigt", + "Errores: {n}; se mostró la jugada", + "Errori: {n}; la mossa è stata mostrata", + "Erros: {n}; o lance foi mostrado", + "Xatolar: {n}; yurish ko‘rsatildi", + "Қателер: {n}; жүріс көрсетілді", + ], + [ + "Mistakes on this move: {n}", + "Ошибок на этом ходу: {n}", + "Erreurs sur ce coup : {n}", + "Fehler bei diesem Zug: {n}", + "Errores en esta jugada: {n}", + "Errori su questa mossa: {n}", + "Erros neste lance: {n}", + "Shu yurishdagi xatolar: {n}", + "Осы жүрістегі қателер: {n}", + ], + [ + "runs: {n}", + "прохождений: {n}", + "passages : {n}", + "Durchgänge: {n}", + "repasos: {n}", + "giri: {n}", + "rodadas: {n}", + "urinishlar: {n}", + "әрекеттер: {n}", + ], + [ + "Replay from memory the moves of both sides from the start of the game up to this move", + "Повторите по памяти ходы обеих сторон от начала партии до этого хода", + "Rejouez de mémoire les coups des deux camps depuis le début de la partie jusqu'à ce coup", + "Spielen Sie die Züge beider Seiten vom Partiebeginn bis zu diesem Zug aus dem Gedächtnis nach", + "Repite de memoria las jugadas de ambos bandos desde el inicio de la partida hasta esta jugada", + "Ripeti a memoria le mosse di entrambi i lati dall'inizio della partita fino a questa mossa", + "Repita de memória os lances dos dois lados desde o início da partida até este lance", + "Partiya boshidan shu yurishgacha ikkala tomonning yurishlarini yoddan takrorlang", + "Партия басынан осы жүріске дейін екі жақтың жүрістерін жатқа қайталаңыз", + ], + [ + "The same position, you play White again", + "Та же позиция, вы снова за белых", + "La même position, vous jouez de nouveau les Blancs", + "Dieselbe Stellung, Sie spielen wieder Weiß", + "La misma posición, vuelves a jugar con blancas", + "La stessa posizione, giochi di nuovo con il Bianco", + "A mesma posição, você joga de novo de brancas", + "O‘sha pozitsiya, yana oqlar bilan o‘ynaysiz", + "Сол позиция, сіз қайтадан ақтармен ойнайсыз", + ], + [ + "The same position, you play Black again", + "Та же позиция, вы снова за чёрных", + "La même position, vous jouez de nouveau les Noirs", + "Dieselbe Stellung, Sie spielen wieder Schwarz", + "La misma posición, vuelves a jugar con negras", + "La stessa posizione, giochi di nuovo con il Nero", + "A mesma posição, você joga de novo de pretas", + "O‘sha pozitsiya, yana qoralar bilan o‘ynaysiz", + "Сол позиция, сіз қайтадан қаралармен ойнайсыз", + ], ]; #[cfg(test)] diff --git a/apps/desktop/src/large_db.rs b/apps/desktop/src/large_db.rs index f6ffa23..c0a2dfc 100644 --- a/apps/desktop/src/large_db.rs +++ b/apps/desktop/src/large_db.rs @@ -2433,6 +2433,7 @@ fn chip(ui: &mut Ui, c: &Condition) -> (bool, bool) { animation: 0.0, premove: None, auto_queen: false, + alert: None, }; ui.allocate_ui(vec2(160.0, 160.0), |ui| { view.show(ui, &mut crate::board::BoardState::default()) diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index 67411e8..19b68d0 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -28,6 +28,7 @@ mod san; mod settings; mod settings_ui; mod sound; +mod train; mod translate; mod translate_ui; mod update; diff --git a/apps/desktop/src/notation.rs b/apps/desktop/src/notation.rs index 51b538f..c1bcaae 100644 --- a/apps/desktop/src/notation.rs +++ b/apps/desktop/src/notation.rs @@ -24,6 +24,11 @@ pub struct Notation<'a> { pub editor: Option<&'a mut CommentEditor>, /// A game being played: moves only show their position (no menus, no editing). pub read_only: bool, + /// Main-line moves up to this ply are dimmed (the moves of the game a game against + /// Maia goes on from). + pub dim_until: Option, + /// Mistakes on main-line moves (learning an opening): how many, the move was shown. + pub mistakes: Option<&'a HashMap>, } /// Result of a frame of the notation panel. @@ -49,6 +54,12 @@ pub struct NotationResponse { pub enum NotationCommand { Promote, Delete, + /// Paste a line from the clipboard (docs/design/paste-variation.md). + Paste, + /// A game against Maia from this position (docs/design/play-from-position.md). + PlayFrom, + /// Learn the opening up to this move (docs/design/opening-trainer.md). + Train, } /// Which comment of the game: after a move (`After(ROOT)`: the start of the game), or @@ -295,10 +306,43 @@ impl Row { 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()); + let dim = n + .dim_until + .is_some_and(|p| n.game.node(id).is_some_and(|nd| nd.ply() <= p)); + let text_right = + paint_move_cell(ui, cell, n.game, id, id == n.cursor, resp.hovered(), dim); if let Some(mark) = n.marks.and_then(|m| m.get(&id)) { paint_badge(ui, cell, mark); } + if let Some(&(count, shown)) = n.mistakes.and_then(|m| m.get(&id)) { + let color = if shown { + ui.visuals().warn_fg_color + } else { + ui.visuals().error_fg_color + }; + // A pill right after the move: its own, readable on the selected one. + let galley = ui.painter().layout_no_wrap( + format!("×{count}"), + FontId::proportional(12.0), + Color32::WHITE, + ); + let pill = egui::Rect::from_min_size( + egui::pos2( + text_right + 4.0, + cell.center().y - galley.size().y / 2.0 - 1.0, + ), + galley.size() + vec2(8.0, 2.0), + ); + ui.painter().rect_filled(pill, 7.0, color); + ui.painter() + .galley(pill.min + vec2(4.0, 1.0), galley, Color32::WHITE); + let tip = if shown { + crate::i18n::trf("Mistakes: {n}; the move was shown", &[("n", &count)]) + } else { + crate::i18n::trf("Mistakes on this move: {n}", &[("n", &count)]) + }; + resp.clone().on_hover_text(tip); + } handle_move_response(ui, &resp, n, id, out); } None => { @@ -372,6 +416,16 @@ fn handle_move_response( } } ui.separator(); + if ui + .add(egui::Button::new(tr("Paste a line from the clipboard")).shortcut_text("Ctrl+V")) + .on_hover_text(tr( + "Moves or a PGN game from the clipboard, as a variation from where they part from this game", + )) + .clicked() + { + out.context = Some((id, NotationCommand::Paste)); + ui.close(); + } if is_variation && ui.button(tr("Make main line")).clicked() { out.context = Some((id, NotationCommand::Promote)); ui.close(); @@ -380,6 +434,57 @@ fn handle_move_response( out.context = Some((id, NotationCommand::Delete)); ui.close(); } + ui.separator(); + // A finished position has nothing to play. + let over = n.game.position(id).and_then(|p| { + if p.is_checkmate() { + Some(tr("checkmate")) + } else if p.is_stalemate() { + Some(tr("stalemate")) + } else if p.is_insufficient_material() { + Some(tr("neither side can checkmate")) + } else { + None + } + }); + let play = ui + .add_enabled( + over.is_none(), + egui::Button::new(tr("Play on from here…")).shortcut_text("Ctrl+G"), + ) + .on_hover_text(tr("A game against Maia from this position")); + let play = match over { + Some(why) => play.on_disabled_hover_text(crate::i18n::trf( + "The game is over here: {why}", + &[("why", &why)], + )), + None => play, + }; + if play.clicked() { + out.context = Some((id, NotationCommand::PlayFrom)); + ui.close(); + } + // Learning the opening: the runs of this line so far on the right. + let runs = crate::train::runs_to(n.game, id); + let label = runs + .filter(|&r| r > 0) + .map(|r| crate::i18n::trf("runs: {n}", &[("n", &r)])) + .unwrap_or_default(); + let learn = ui + .add_enabled( + runs.is_some(), + egui::Button::new(tr("Learn the opening up to this move")).shortcut_text(label), + ) + .on_hover_text(tr( + "Replay from memory the moves of both sides from the start of the game up to this move", + )) + .on_disabled_hover_text(tr( + "The line has a null move (--): it cannot be played on the board", + )); + if learn.clicked() { + out.context = Some((id, NotationCommand::Train)); + ui.close(); + } }); let _ = ui; } @@ -447,7 +552,8 @@ fn paint_move_cell( id: NodeId, current: bool, hovered: bool, -) { + dim: bool, +) -> f32 { let visuals = ui.visuals(); if current { ui.painter() @@ -464,16 +570,20 @@ fn paint_move_cell( .unwrap_or((String::new(), None)); let text_color = if current { visuals.selection.stroke.color + } else if dim { + visuals.weak_text_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, - ); + ui.painter() + .text( + cell.left_center() + vec2(10.0, 0.0), + Align2::LEFT_CENTER, + format!("{san}{sym}"), + FontId::proportional(16.0), + text_color, + ) + .right() } /// Engine verdict at the right edge of a move cell: a filled pill, unlike the author's NAGs. diff --git a/apps/desktop/src/play.rs b/apps/desktop/src/play.rs index 1841f53..8374240 100644 --- a/apps/desktop/src/play.rs +++ b/apps/desktop/src/play.rs @@ -672,6 +672,9 @@ pub struct Session { pub resign_offer: Option, /// «Play to the end»: no more offers in this game. pub play_on: bool, + /// The last move of the game it goes on from (`ROOT`: a game from the start): the + /// moves up to it are not taken back and do not count as played. + pub floor: chess_core::NodeId, } /// What the play dialog starts. @@ -682,6 +685,31 @@ pub struct Start { pub user_elo: Option, pub user_name: String, pub clock: Option, + /// A game from a position of another game (docs/design/play-from-position.md). + pub from: Option>, +} + +/// Where a game against Maia starts when it goes on from a game: its start and the +/// moves to the chosen one (the history Maia and the repetitions need). +#[derive(Clone, Debug)] +pub struct StartFrom { + /// The FEN of the game's start (`None`: the standard position) — after the last + /// null move of the path, if there is one. + pub start_fen: Option, + /// The moves from that start to the chosen position. + pub moves: Vec, + /// The position played from. + pub position: Chess, + /// Its last move, for the board (from, to). + pub last: Option<(chess_core::shakmaty::Square, chess_core::shakmaty::Square)>, + /// «14...Ke7» — the move played from (SAN, as data); `None`: the game's start. + pub after: Option, + /// The same as shown («14…Ке7»). + pub after_shown: Option, + /// «Carlsen — Caruana, Wijk aan Zee 2024», when the game says so. + pub game: Option, + /// Null moves before the position were left out. + pub null_dropped: bool, } // ----- Maia resigns -------------------------------------------------------------------- @@ -818,6 +846,8 @@ pub struct Dialog { download: Option, /// «Download and play» was pressed: the game starts once Maia is there. play_after: bool, + /// The game goes on from a position of another game. + from: Option, focus: bool, } @@ -842,9 +872,21 @@ impl Dialog { download: None, play_after: false, focus: true, + from: None, } } + /// The dialog for a game from a position: the side to move plays (not remembered). + pub fn new_from(settings: &crate::settings::Settings, from: StartFrom) -> Dialog { + let mut d = Dialog::new(settings); + d.prefs.color = match from.position.turn() { + Color::White => ColorChoice::White, + Color::Black => ColorChoice::Black, + }; + d.from = Some(from); + d + } + fn rating(&self) -> Option { self.rating .trim() @@ -874,8 +916,11 @@ impl Dialog { .auto_shrink([false, true]) .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::VisibleWhenNeeded) .show(ui, |ui| { - // In a low window the choices matter more than the introduction. - if body_h >= 420.0 { + // A game from a position: that position, instead of the introduction. + if let Some(from) = &self.from { + position_block(ui, settings, from, self.prefs.color, body_h >= 420.0); + } else if body_h >= 420.0 { + // In a low window the choices matter more than the introduction. ui.label( RichText::new(tr( "Maia plays like a human of the chosen rating: it makes the moves people of that level make, mistakes included.", @@ -1129,13 +1174,19 @@ impl Dialog { }; settings.your_name = self.name.trim().to_owned(); settings.rating = rating; + // From a position the colour is the side to move's, not a habit. + let color = settings.play.color; settings.play = self.prefs.clone(); + if self.from.is_some() { + settings.play.color = color; + } out = Some(DialogOutcome::Play(Start { user, strength: self.prefs.strength, user_elo: rating, user_name: self.name.trim().to_owned(), clock: self.prefs.clock, + from: self.from.clone().map(Box::new), })); } if ui.add(egui::Button::new(tr("Cancel")).min_size(egui::vec2(0.0, 30.0))).clicked() { @@ -1150,6 +1201,103 @@ impl Dialog { } } +/// The position a game goes on from: a small board (turned to the colour chosen) and +/// where it comes from. `board`: room for the board (not in a low window). +fn position_block( + ui: &mut egui::Ui, + settings: &crate::settings::Settings, + from: &StartFrom, + color: ColorChoice, + board: bool, +) { + use egui::RichText; + let bottom = match color { + ColorChoice::White => Color::White, + ColorChoice::Black => Color::Black, + ColorChoice::Random => from.position.turn(), + }; + egui::Frame::new() + .inner_margin(egui::Margin::same(8)) + .corner_radius(4) + .stroke(egui::Stroke::new( + 1.0, + ui.visuals().widgets.noninteractive.bg_stroke.color, + )) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal_top(|ui| { + if board { + ui.allocate_ui(egui::vec2(112.0, 112.0), |ui| { + let view = crate::board::BoardView { + pos: &from.position, + orientation: bottom, + last_move: from.last, + arrows: &[], + circles: &[], + badge: None, + interactive: false, + show_coords: false, + theme: settings.board_theme.theme(), + pieces: settings.piece_set, + animation: 0.0, + premove: None, + auto_queen: false, + alert: None, + }; + let mut state = crate::board::BoardState::default(); + view.show(ui, &mut state); + }); + ui.add_space(12.0 - ui.spacing().item_spacing.x); + } + ui.vertical(|ui| { + let top = ui.cursor().top(); + let title = match &from.after_shown { + Some(m) => { + crate::i18n::trf("From the position after {move}", &[("move", m)]) + } + None => tr("From the game's starting position").to_owned(), + }; + ui.label(RichText::new(title).strong().size(15.0)); + if let Some(g) = &from.game { + // Two lines at most; the whole of it under the pointer. + let text = crate::i18n::trf("from the game {game}", &[("game", g)]); + let mut job = egui::text::LayoutJob::simple( + text.clone(), + egui::FontId::proportional(13.0), + ui.visuals().weak_text_color(), + ui.available_width(), + ); + job.wrap.max_rows = 2; + ui.add(egui::Label::new(job)).on_hover_text(text); + } + if from.null_dropped { + ui.label( + RichText::new(tr( + "The moves before the null move (--) are not carried over", + )) + .weak() + .size(13.0), + ); + } + // The side to move level with the bottom of the board. + let room = if board { + top + 112.0 - ui.cursor().top() - 17.0 + } else { + 4.0 + }; + ui.add_space(room.max(4.0)); + ui.label( + RichText::new(match from.position.turn() { + Color::White => tr("White to move"), + Color::Black => tr("Black to move"), + }) + .size(13.0), + ); + }); + }); + }); +} + fn trf_size() -> String { crate::i18n::trf( "Maia is downloaded once ({mb} MB, from huggingface.co, the authors' own file).", diff --git a/apps/desktop/src/train.rs b/apps/desktop/src/train.rs new file mode 100644 index 0000000..f94df20 --- /dev/null +++ b/apps/desktop/src/train.rs @@ -0,0 +1,387 @@ +//! Learning an opening: the user replays from memory the moves of both sides of a +//! line of a game, from its start to the chosen move (docs/design/opening-trainer.md, +//! docs/research/opening-trainer.md). +//! +//! Only the move of the line is right: another move — a move of a variation or one +//! transposing — is a mistake; it is shown for a moment and taken back. From the third +//! mistake on a move the user may ask to see it (the run is then marked «with a hint»). +//! The runs of each line are kept in `training.json`, by the line itself (its start +//! position and moves), so they survive edits of the game and are shared between games +//! with the same line. + +use std::path::PathBuf; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use chess_core::shakmaty::fen::Fen; +use chess_core::shakmaty::{CastlingMode, Chess, EnPassantMode, Move, Square}; +use chess_core::{Game, MoveKind, NodeId}; +use serde::{Deserialize, Serialize}; + +/// How long a wrong move stays on the board before it is taken back. +pub const WRONG_SHOWN: Duration = Duration::from_millis(400); + +/// From this mistake on one move, the user may ask to see it. +pub const HINT_AFTER: u32 = 3; + +/// The runs of a line remembered for its «recent» row. +const RECENT: usize = 10; + +/// What a training starts from: the line and how to name it. +#[derive(Clone, Debug)] +pub struct TrainStart { + /// The FEN of the game's start (`None`: the standard position). + pub start_fen: Option, + pub line: Vec, + /// «Carlsen — Caruana», when the game names its players. + pub game: Option, + /// «Wijk aan Zee 2024», when the game says so. + pub event: Option, + /// The last move of the line as shown («12…Rd8»). + pub up_to: String, + /// Its move number. + pub last_number: u32, + /// The board as the game showed it. + pub flipped: bool, +} + +impl TrainStart { + /// The line from the start of `game` to `at` (`None`: no move there, or a null + /// move on the way — it cannot be played on the board). + pub fn from_game(game: &Game, at: NodeId) -> Option { + let path = game.path(at); + let mut line = Vec::new(); + for &n in &path[1..] { + match game.game_move(n)?.kind { + MoveKind::Normal(m) => line.push(m), + MoveKind::Null => return None, + } + } + if line.is_empty() { + return None; + } + let (n, side) = game.move_number(at)?; + let san = &game.game_move(at)?.san; + let up_to = crate::san::show(&match side { + chess_core::shakmaty::Color::White => format!("{n}.{san}"), + chess_core::shakmaty::Color::Black => format!("{n}…{san}"), + }) + .into_owned(); + let name = |t: &str| { + game.tag(t) + .map(str::trim) + .filter(|v| !v.is_empty() && *v != "?") + }; + let players = match (name("White"), name("Black")) { + (None, None) => None, + (w, b) => Some(format!("{} — {}", w.unwrap_or("?"), b.unwrap_or("?"))), + }; + let year = name("Date") + .map(|d| d.chars().take(4).collect::()) + .filter(|y| y.len() == 4 && y.chars().all(|c| c.is_ascii_digit())); + let event = [name("Event").map(str::to_owned), year] + .into_iter() + .flatten() + .collect::>() + .join(" "); + Some(TrainStart { + start_fen: (!game.start().is_standard()).then(|| game.start().fen()), + line, + game: players, + event: (!event.is_empty()).then_some(event), + up_to, + last_number: n, + flipped: false, + }) + } + + /// The key of the line in the statistics. + pub fn key(&self) -> String { + let start = match self + .start_fen + .as_deref() + .and_then(|f| f.parse::().ok()) + { + Some(fen) => fen + .into_position::(CastlingMode::Standard) + .unwrap_or_default(), + None => Chess::default(), + }; + line_key(&start, &self.line) + } +} + +/// The key of a line: its start position (no counters) and its moves in UCI. +pub fn line_key(start: &Chess, line: &[Move]) -> String { + let fen = Fen::from_position(start, EnPassantMode::Legal).to_string(); + let pos: Vec<&str> = fen.split(' ').take(4).collect(); + let moves: Vec = line + .iter() + .map(|m| m.to_uci(CastlingMode::Standard).to_string()) + .collect(); + format!("{} | {}", pos.join(" "), moves.join(" ")) +} + +/// A wrong move shown on the board for a moment. +#[derive(Clone, Debug)] +pub struct Flash { + /// The position after it. + pub after: Chess, + pub from: Square, + pub to: Square, + pub until: Instant, +} + +/// A training in progress (or done). +pub struct Training { + pub start: TrainStart, + pub key: String, + /// Mistakes on each half-move of the line in this run. + pub mistakes: Vec, + /// The move was shown (a hint) on each half-move. + pub shown: Vec, + /// The hint is on the board now (the arrow of the right move). + pub hint: bool, + pub flash: Option, + /// The run is over: all the moves made. + pub done: bool, + /// The line's runs before this one. + pub before: LineStats, + /// …and after it, once it is done. + pub after: Option, +} + +impl Training { + pub fn new(start: TrainStart) -> Training { + let key = start.key(); + let n = start.line.len(); + Training { + before: stats(&key), + key, + mistakes: vec![0; n], + shown: vec![false; n], + hint: false, + flash: None, + done: false, + after: None, + start, + } + } + + /// The same line again from the start. + pub fn again(&mut self) { + let n = self.start.line.len(); + self.before = stats(&self.key); + self.mistakes = vec![0; n]; + self.shown = vec![false; n]; + self.hint = false; + self.flash = None; + self.done = false; + self.after = None; + } + + pub fn total(&self) -> u32 { + self.mistakes.iter().sum() + } + + pub fn hinted(&self) -> bool { + self.shown.iter().any(|&s| s) + } + + /// The run is over: it counts. + pub fn finish(&mut self) { + self.done = true; + self.hint = false; + self.after = Some(record(&self.key, self.total(), self.hinted())); + } +} + +/// What is known of the runs of a line. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct LineStats { + pub runs: u32, + /// Mistakes of the last run. + pub last: Option, + /// The fewest mistakes of a run without a hint. + pub best: Option, + /// Runs without mistakes (or hints) in a row, to the last one. + pub clean_streak: u32, + /// The last runs, oldest first: mistakes, a hint. + pub recent: Vec<(u32, bool)>, + /// The day of the last run (for repetition by a schedule later). + pub last_date: String, +} + +/// The runs by line, as in the file: an entry that does not read is left as it is. +static STATS: Mutex>> = Mutex::new(None); + +/// The file the tests write instead. +static FILE: Mutex> = Mutex::new(None); + +/// `/training.json` (`CP_TRAINING_FILE` elsewhere: development). +fn file() -> Option { + if let Some(p) = FILE.lock().ok().and_then(|f| f.clone()) { + return Some(p); + } + if let Some(p) = std::env::var_os("CP_TRAINING_FILE") { + return Some(PathBuf::from(p)); + } + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.data_local_dir().join("training.json")) +} + +fn with_stats(f: impl FnOnce(&mut serde_json::Map) -> R) -> R { + let mut guard = STATS.lock().unwrap_or_else(|e| e.into_inner()); + let map = guard.get_or_insert_with(load); + f(map) +} + +/// The file read; one that does not read as a whole is kept aside +/// (`training.json.unreadable`), not overwritten by the next run. +fn load() -> serde_json::Map { + let Some(path) = file() else { + return Default::default(); + }; + let Ok(bytes) = std::fs::read(&path) else { + return Default::default(); + }; + match serde_json::from_slice(&bytes) { + Ok(map) => map, + Err(e) => { + let aside = path.with_extension("json.unreadable"); + eprintln!( + "training: {} unreadable ({e}), kept as {}", + path.display(), + aside.display() + ); + let _ = std::fs::rename(&path, aside); + Default::default() + } + } +} + +/// The runs of the line `key` so far (an entry that does not read: none). +pub fn stats(key: &str) -> LineStats { + with_stats(|m| { + m.get(key) + .and_then(|v| serde_json::from_value(v.clone()).ok()) + .unwrap_or_default() + }) +} + +/// A run done: counted and written at once. +fn record(key: &str, mistakes: u32, hinted: bool) -> LineStats { + with_stats(|m| { + let mut s: LineStats = m + .get(key) + .and_then(|v| serde_json::from_value(v.clone()).ok()) + .unwrap_or_default(); + s.runs += 1; + s.last = Some(mistakes); + if !hinted { + s.best = Some(s.best.map_or(mistakes, |b| b.min(mistakes))); + } + s.clean_streak = if mistakes == 0 && !hinted { + s.clean_streak + 1 + } else { + 0 + }; + s.recent.push((mistakes, hinted)); + if s.recent.len() > RECENT { + s.recent.remove(0); + } + s.last_date = chrono::Local::now().format("%Y-%m-%d").to_string(); + if let Ok(v) = serde_json::to_value(&s) { + m.insert(key.to_owned(), v); + } + let out = s; + if let Some(path) = file() { + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + if let Ok(json) = serde_json::to_vec_pretty(m) + && let Err(e) = crate::settings::write_atomic(&path, &json) + { + eprintln!("training: save failed: {e}"); + } + } + out + }) +} + +/// The runs of the line from the start of `game` to `at`, for the move's menu +/// (`None`: no line there). +pub fn runs_to(game: &Game, at: NodeId) -> Option { + TrainStart::from_game(game, at).map(|t| stats(&t.key()).runs) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + #[test] + fn a_line_is_kept_by_its_moves_and_counted() { + let dir = std::env::temp_dir().join(format!("cp-train-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + *FILE.lock().unwrap() = Some(dir.join("training.json")); + let a = chess_core::parse_str("[White \"A\"]\n\n1. e4 c5 2. Nf3 d6 *").game; + let b = chess_core::parse_str("1. e4 c5 2. Nf3 d6 3. d4 (3. Bb5+) *").game; + let at = |g: &Game, k: usize| g.mainline()[k]; + let ta = TrainStart::from_game(&a, at(&a, 3)).unwrap(); + let tb = TrainStart::from_game(&b, at(&b, 3)).unwrap(); + // The same line in two games: one key. + assert_eq!(ta.key(), tb.key()); + assert_eq!(ta.game.as_deref(), Some("A — ?")); + let mut t = Training::new(ta); + t.mistakes[1] = 2; + t.finish(); + let s = stats(&t.key); + assert_eq!( + (s.runs, s.last, s.best, s.clean_streak), + (1, Some(2), Some(2), 0) + ); + t.again(); + t.shown[0] = true; + t.finish(); + let s = stats(&t.key); + // A hint: counted, not the best. + assert_eq!((s.runs, s.best), (2, Some(2))); + assert_eq!(s.recent, [(2, false), (0, true)]); + t.again(); + t.finish(); + let s = stats(&t.key); + assert_eq!((s.best, s.clean_streak), (Some(0), 1)); + // Written to the file. + let back: HashMap = + serde_json::from_slice(&std::fs::read(dir.join("training.json")).unwrap()).unwrap(); + assert_eq!(back[&t.key].runs, 3); + // An entry that does not read stays in the file as it is. + let mut raw: serde_json::Map = + serde_json::from_slice(&std::fs::read(dir.join("training.json")).unwrap()).unwrap(); + raw.insert("x".into(), serde_json::json!({"runs": "bad"})); + std::fs::write(dir.join("training.json"), serde_json::to_vec(&raw).unwrap()).unwrap(); + *STATS.lock().unwrap() = None; + t.again(); + t.finish(); + let raw: serde_json::Map = + serde_json::from_slice(&std::fs::read(dir.join("training.json")).unwrap()).unwrap(); + assert_eq!(raw["x"], serde_json::json!({"runs": "bad"})); + assert_eq!(stats(&t.key).runs, 4); + // A file that does not read is kept aside, not lost. + std::fs::write(dir.join("training.json"), b"{ broken").unwrap(); + *STATS.lock().unwrap() = None; + t.again(); + t.finish(); + assert_eq!( + std::fs::read(dir.join("training.json.unreadable")).unwrap(), + b"{ broken" + ); + assert_eq!(stats(&t.key).runs, 1); + // A null move on the way: nothing to train. + let n = chess_core::parse_str("1. e4 -- 2. d4 *").game; + assert!(TrainStart::from_game(&n, n.mainline()[2]).is_none()); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/chess-core/src/edit.rs b/crates/chess-core/src/edit.rs index 0d96f24..bb1ffdc 100644 --- a/crates/chess-core/src/edit.rs +++ b/crates/chess-core/src/edit.rs @@ -346,7 +346,7 @@ impl Game { /// Applies a new command (the Attach of a freshly pushed node is already /// linked by `push_child`, so it is only recorded). - fn record(&mut self, cmd: Command) { + pub(crate) fn record(&mut self, cmd: Command) { if !matches!(cmd, Command::Attach { .. }) { self.apply(&cmd); } diff --git a/crates/chess-core/src/lib.rs b/crates/chess-core/src/lib.rs index cb7b188..01d2f39 100644 --- a/crates/chess-core/src/lib.rs +++ b/crates/chess-core/src/lib.rs @@ -10,6 +10,7 @@ pub mod edit; pub mod encoding; pub mod game; pub mod nag; +pub mod paste; pub mod pgn; pub mod repair; pub mod start; diff --git a/crates/chess-core/src/paste.rs b/crates/chess-core/src/paste.rs new file mode 100644 index 0000000..ffb7215 --- /dev/null +++ b/crates/chess-core/src/paste.rs @@ -0,0 +1,809 @@ +//! Pasting moves or a PGN game from the clipboard into a game as a variation +//! (docs/research/paste-variation.md §4, docs/design/paste-variation.md). +//! +//! [`plan`] reads the text and finds where it fits without touching the game; +//! [`Game::apply_paste`] then grafts the new moves — with their comments, NAGs and +//! nested variations — as one undo step. +//! +//! What the clipboard may hold: +//! - a PGN game (tags, or numbers from move 1): it hangs where its moves part from +//! this game, along any branch; with no common start, where one of its positions +//! occurs here (another move order); with neither it does not fit; +//! - a fragment (`Nf3 d5`, `12...Rd8`, UCI `e2e4 e7e5`): after the selected move, +//! instead of it, or at the position of its move number on the current line. +//! +//! Nothing is inserted when any move of the line is impossible. + +use shakmaty::fen::Fen; +use shakmaty::san::SanPlus; +use shakmaty::uci::UciMove; +use shakmaty::{Chess, Color, EnPassantMode, Position}; + +use crate::edit::{Command, EditError}; +use crate::encoding::TextEncoding; +use crate::game::{Game, GameMove, MoveKind, NodeId, play_null}; +use crate::pgn::{parse_game_range, parse_str, scan_games}; + +/// Where and what to insert: the subtree of `source` from `from` hangs from `at`. +#[derive(Clone, Debug)] +pub struct PastePlan { + /// The node of this game the new moves follow. + pub at: NodeId, + source: Game, + from: NodeId, + /// The variations of the pasted game this one lacks, along the way: (where here, + /// the pasted move) — inserted too. + extra: Vec<(NodeId, NodeId)>, + /// `at` has no continuation: the moves continue the line instead of branching. + pub continuation: bool, + /// The moves of the new line (its main line): number, side, SAN. + pub line: Vec<(u32, Color, String)>, + /// The game reached this position by another move order: those moves + /// (`1.Nf3 c5 2.e4`), noted before the first move of the line. + pub transposition: Option, + /// «White – Black» of the pasted game, noted after the last move of the line. + pub source_ref: Option, + /// Games in the clipboard (the first one is pasted). + pub games: usize, +} + +/// Why nothing is pasted. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum PasteError { + /// The clipboard is empty or holds no moves. + NoMoves, + /// A fragment fits neither after the selected move nor instead of it (nor at + /// its move number). + DoesNotFit, + /// A move in the middle of the line is impossible. + Illegal { + number: u32, + side: Color, + san: String, + }, + /// The game shares no position with this one. + Unrelated, + /// All the moves are here already: the end of that line; `comments` — the + /// pasted moves had comments or symbols (not carried over). + AlreadyThere { at: NodeId, comments: bool }, +} + +/// Finds where `text` fits in `target` (the user stands on `cursor`). +pub fn plan(target: &Game, cursor: NodeId, text: &str) -> Result { + // «12…Rd8» as the program itself writes black's moves. + let text = text.trim().replace('…', "..."); + let text = text.as_str(); + if text.is_empty() { + return Err(PasteError::NoMoves); + } + if text.starts_with('[') { + // The games are only counted; the first one is read. + let never = std::sync::atomic::AtomicBool::new(false); + let entries = scan_games(text.as_bytes(), TextEncoding::Utf8, &mut |_| {}, &never) + .unwrap_or_default(); + let source = match entries.first() { + Some(e) => parse_game_range( + text.as_bytes(), + e.byte_range.clone(), + e.first_line, + TextEncoding::Utf8, + ), + None => parse_str(text), + }; + return whole_game(target, source, entries.len().max(1)); + } + let uci = uci_moves(text); + let number = leading_number(text); + // «1.e4 …» from the standard start: a game, with all its rules (a «1.d4» into a + // Sicilian is refused, not hung at the start). + if uci.is_none() && number == Some((1, Color::White)) && target.start().is_standard() { + return whole_game(target, parse_str(text), 1); + } + // A fragment: after the selected move, instead of it, at its move number. + let mut candidates = vec![cursor]; + if let Some(parent) = target.parent(cursor) { + candidates.push(parent); + } + if let Some(n) = number + && let Some(at) = by_number(target, cursor, n) + && !candidates.contains(&at) + { + candidates.push(at); + } + for at in candidates { + let Some(pos) = target.position(at) else { + continue; + }; + if number.is_some_and(|(n, side)| (pos.fullmoves().get(), pos.turn()) != (n, side)) { + continue; + } + let movetext = match &uci { + Some(moves) => match uci_to_san(pos, moves) { + Ok(san) => san, + Err(0) => continue, + Err(k) => return Err(illegal_at(pos, moves, k)), + }, + None => text.to_owned(), + }; + let fen = target.fen(at).unwrap_or_default(); + let source = parse_str(&format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n{movetext}\n")).game; + if source.main_child(NodeId::ROOT).is_none() { + continue; // its first move is impossible here + } + if let Some(e) = illegal_in_main_line(&source) { + return Err(e); + } + return from_node(target, at, &source, NodeId::ROOT, None, 1); + } + // Numbers or not, plain SAN may still be a game from the start. + if uci.is_none() && number.is_none() { + return match whole_game(target, parse_str(text), 1) { + Err(PasteError::Unrelated | PasteError::NoMoves) => Err(PasteError::DoesNotFit), + other => other, + }; + } + Err(PasteError::DoesNotFit) +} + +/// A whole game: where its moves part from this game; else where one of its +/// positions occurs here; else it does not fit. +fn whole_game( + target: &Game, + parsed: crate::pgn::ParsedGame, + games: usize, +) -> Result { + let source = parsed.game; + if source.main_child(NodeId::ROOT).is_none() { + return Err(PasteError::NoMoves); + } + if let Some(e) = illegal_in_main_line(&source) { + return Err(e); + } + let same_start = key(source.start().position()) == key(target.start().position()); + // An empty game takes it all. + if same_start && target.main_child(NodeId::ROOT).is_none() { + return from_node(target, NodeId::ROOT, &source, NodeId::ROOT, None, games); + } + // The moves in common, along any branch. + if same_start && walk(target, NodeId::ROOT, &source, NodeId::ROOT).matched > 0 { + return from_node(target, NodeId::ROOT, &source, NodeId::ROOT, None, games); + } + // Another move order: the first of its positions that occurs here. + let mut path = vec![NodeId::ROOT]; + path.extend(source.mainline()); + let targets: Vec = std::iter::once(NodeId::ROOT) + .chain(target.mainline()) + .chain(target.attached_nodes()) + .collect(); + for (k, &s) in path.iter().enumerate() { + if k == 0 && same_start { + continue; + } + let Some(sp) = source.position(s) else { + continue; + }; + let want = key(sp); + let Some(&t) = targets + .iter() + .find(|&&t| target.position(t).is_some_and(|tp| key(tp) == want)) + else { + continue; + }; + let note = (k > 0).then(|| line_text(&source, &path[1..=k])); + return from_node(target, t, &source, s, note, games); + } + Err(PasteError::Unrelated) +} + +/// The plan for the moves of `source` after `s`, matched along `target` from `t`. +fn from_node( + target: &Game, + t: NodeId, + source: &Game, + s: NodeId, + transposition: Option, + games: usize, +) -> Result { + let Walk { + last, + next, + mut extra, + .. + } = walk(target, t, source, s); + // The main line is all here: its variations this game lacks may still be new. + let (at, from) = match next { + Some(from) => (last, from), + None if !extra.is_empty() => extra.remove(0), + None => { + let comments = commented(source, s); + return Err(PasteError::AlreadyThere { at: last, comments }); + } + }; + let mut line = Vec::new(); + let mut cur = Some(from); + while let Some(c) = cur { + if let (Some(before), Some(mv)) = (source.position_before(c), source.game_move(c)) { + line.push((before.fullmoves().get(), before.turn(), mv.san.clone())); + } + cur = source.main_child(c); + } + let name = |tag: &str| { + source + .tag(tag) + .map(str::trim) + .filter(|v| !v.is_empty() && *v != "?") + }; + let source_ref = match (name("White"), name("Black")) { + (None, None) => None, + (w, b) => Some(format!("{} – {}", w.unwrap_or("?"), b.unwrap_or("?"))), + }; + Ok(PastePlan { + at, + source: source.clone(), + from, + extra, + continuation: target.children(at).is_empty(), + line, + transposition, + source_ref, + games, + }) +} + +/// What [`walk`] found. +struct Walk { + /// The last node in common. + last: NodeId, + /// The first move of the pasted main line that is not here. + next: Option, + /// How many moves matched. + matched: usize, + /// The pasted game's alternatives along the way that are not here: (where here, + /// the pasted move). + extra: Vec<(NodeId, NodeId)>, +} + +/// Follows the main line of `source` from `s` through `target` from `t` while the +/// moves are there (by any branch). +fn walk(target: &Game, mut t: NodeId, source: &Game, mut s: NodeId) -> Walk { + let child = |t: NodeId, kind: MoveKind| { + target + .children(t) + .iter() + .copied() + .find(|&c| target.game_move(c).is_some_and(|m| m.kind == kind)) + }; + let mut matched = 0; + let mut extra = Vec::new(); + while let Some(next) = source.main_child(s) { + // The pasted game's variations here: kept unless this game has the move. + for &alt in &source.children(s)[1..] { + if let Some(kind) = source.game_move(alt).map(|m| m.kind) + && child(t, kind).is_none() + { + extra.push((t, alt)); + } + } + let Some(kind) = source.game_move(next).map(|m| m.kind) else { + break; + }; + match child(t, kind) { + Some(c) => { + t = c; + s = next; + matched += 1; + } + None => { + return Walk { + last: t, + next: Some(next), + matched, + extra, + }; + } + } + } + Walk { + last: t, + next: None, + matched, + extra, + } +} + +/// The moves walked from `s` on had comments or symbols (lost when all are here). +fn commented(source: &Game, s: NodeId) -> bool { + let mut cur = source.main_child(s); + while let Some(c) = cur { + if let Some(n) = source.node(c) + && (!n.nags().is_empty() + || !n.comments_after().is_empty() + || !n.comments_before().is_empty()) + { + return true; + } + cur = source.main_child(c); + } + false +} + +/// An impossible move on the main line of a parsed game (its variations may keep +/// raw text: it is carried over as it is). +fn illegal_in_main_line(source: &Game) -> Option { + let mut main = vec![NodeId::ROOT]; + main.extend(source.mainline()); + let last = *main.last()?; + let node = source.node(last)?; + let raw = node.unparsed().first()?; + // The first move word, without a number glued to it («3.Qh8»). + let san = raw + .split_whitespace() + .find(|w| !is_number(w))? + .trim_start_matches(|c: char| c.is_ascii_digit() || c == '.' || c == '…') + .to_owned(); + let pos = source.position(last)?; + Some(PasteError::Illegal { + number: pos.fullmoves().get(), + side: pos.turn(), + san, + }) +} + +/// The position key: pieces, side to move, castling, en passant (no counters). +fn key(pos: &Chess) -> String { + Fen::from_position(pos, EnPassantMode::Legal) + .to_string() + .split(' ') + .take(4) + .collect::>() + .join(" ") +} + +/// `1.Nf3 c5 2.e4` for the given nodes of `game`. +fn line_text(game: &Game, nodes: &[NodeId]) -> String { + let mut out = String::new(); + for (i, &n) in nodes.iter().enumerate() { + let (Some(before), Some(mv)) = (game.position_before(n), game.game_move(n)) else { + continue; + }; + let num = before.fullmoves().get(); + if !out.is_empty() { + out.push(' '); + } + match before.turn() { + Color::White => out.push_str(&format!("{num}.{}", mv.san)), + Color::Black if i == 0 => out.push_str(&format!("{num}...{}", mv.san)), + Color::Black => out.push_str(&mv.san), + } + } + out +} + +/// The number of a move (`12.`, `12...`, `12…`), as a word of the text. +fn is_number(w: &str) -> bool { + let digits = w.trim_end_matches(['.', '…']); + !digits.is_empty() && digits.len() < w.len() && digits.chars().all(|c| c.is_ascii_digit()) +} + +/// `12.` → (12, White), `12...` / `12…` → (12, Black), when the text starts so. +fn leading_number(text: &str) -> Option<(u32, Color)> { + let first = text.split_whitespace().next()?; + let digits: String = first.chars().take_while(char::is_ascii_digit).collect(); + let rest = &first[digits.len()..]; + let n: u32 = digits.parse().ok()?; + if rest.starts_with("...") || rest.starts_with('…') { + Some((n, Color::Black)) + } else if rest.starts_with('.') { + Some((n, Color::White)) + } else { + None + } +} + +/// The words of a UCI line (`e2e4 e7e5 g1f3`, numbers allowed), if the text is one. +fn uci_moves(text: &str) -> Option> { + let words: Vec<&str> = text + .split_whitespace() + .filter(|w| !is_number(w) && !matches!(*w, "1-0" | "0-1" | "1/2-1/2" | "*")) + .collect(); + let is_uci = |w: &str| { + let b = w.as_bytes(); + (b.len() == 4 || b.len() == 5) + && (b'a'..=b'h').contains(&b[0]) + && (b'1'..=b'8').contains(&b[1]) + && (b'a'..=b'h').contains(&b[2]) + && (b'1'..=b'8').contains(&b[3]) + && (b.len() == 4 || b"qrbn".contains(&b[4])) + }; + (!words.is_empty() && words.iter().all(|w| is_uci(w))) + .then(|| words.iter().map(|w| (*w).to_owned()).collect()) +} + +/// UCI moves played from `pos` as SAN; `Err(k)`: the `k`-th move is impossible. +fn uci_to_san(pos: &Chess, moves: &[String]) -> Result { + let mut pos = pos.clone(); + let mut out = Vec::new(); + for (k, w) in moves.iter().enumerate() { + let m = w + .parse::() + .ok() + .and_then(|u| u.to_move(&pos).ok()) + .ok_or(k)?; + out.push(SanPlus::from_move_and_play_unchecked(&mut pos, m).to_string()); + } + Ok(out.join(" ")) +} + +/// The error for the `k`-th UCI move from `pos`. +fn illegal_at(pos: &Chess, moves: &[String], k: usize) -> PasteError { + let mut pos = pos.clone(); + for w in &moves[..k] { + if let Some(m) = w.parse::().ok().and_then(|u| u.to_move(&pos).ok()) { + pos.play_unchecked(m); + } + } + PasteError::Illegal { + number: pos.fullmoves().get(), + side: pos.turn(), + san: moves[k].clone(), + } +} + +/// The node of the current line (the path to `cursor`, then on by the main line) +/// where the move of number `n` is to be made. +fn by_number(target: &Game, cursor: NodeId, (n, side): (u32, Color)) -> Option { + let mut line = target.path(cursor); + let mut cur = cursor; + while let Some(next) = target.main_child(cur) { + line.push(next); + cur = next; + } + line.into_iter().find(|&id| { + target + .position(id) + .is_some_and(|p| (p.fullmoves().get(), p.turn()) == (n, side)) + }) +} + +impl Game { + /// Inserts what [`plan`] found: the new moves with their comments, symbols and + /// variations, the move-order note and the source, as one undo step. Returns the + /// first inserted node. + pub fn apply_paste(&mut self, plan: &PastePlan) -> Result { + let pos = self + .position(plan.at) + .ok_or(EditError::UnknownNode)? + .clone(); + // Every move is checked before the game changes. + check(&plan.source, plan.from, &pos)?; + for &(at, from) in &plan.extra { + let pos = self.position(at).ok_or(EditError::UnknownNode)?.clone(); + check(&plan.source, from, &pos)?; + } + self.edit_group(|g| g.paste_grafts(plan)) + } + + /// The grafts of [`Game::apply_paste`], checked already. + fn paste_grafts(&mut self, plan: &PastePlan) -> Result { + let first = self.graft(plan.at, &plan.source, plan.from)?; + if let Some(note) = &plan.transposition + && let Some(n) = self.node_mut(first) + { + n.comments_before.insert(0, note.clone()); + } + if let Some(r) = &plan.source_ref { + let end = self.line_end(first); + if let Some(n) = self.node_mut(end) { + n.comments_after.push(r.clone()); + } + } + let index = self.child_index(first).unwrap_or(0); + self.record(Command::Attach { + parent: plan.at, + child: first, + index, + }); + for &(at, from) in &plan.extra { + let id = self.graft(at, &plan.source, from)?; + let index = self.child_index(id).unwrap_or(0); + self.record(Command::Attach { + parent: at, + child: id, + index, + }); + } + Ok(first) + } + + /// Copies the subtree of `source` from `s` under `parent`, positions replayed + /// here (the counters may differ from the source's). + fn graft(&mut self, parent: NodeId, source: &Game, s: NodeId) -> Result { + let pos = self.position(parent).ok_or(EditError::UnknownNode)?.clone(); + let node = source.node(s).ok_or(EditError::UnknownNode)?; + let mv = node.game_move().ok_or(EditError::UnknownNode)?; + let (gm, after) = play(&pos, mv)?; + let id = self.push_child(parent, gm, after); + if let Some(n) = self.node_mut(id) { + n.nags = node.nags().to_vec(); + n.comments_before = node.comments_before().to_vec(); + n.comments_after = node.comments_after().to_vec(); + n.unparsed = node.unparsed().to_vec(); + } + for &c in source.children(s) { + self.graft(id, source, c)?; + } + Ok(id) + } +} + +/// The move `mv` from `pos`: the node's move and the position after it. +fn play(pos: &Chess, mv: &GameMove) -> Result<(GameMove, Chess), EditError> { + match mv.kind { + MoveKind::Normal(m) => { + if !pos.is_legal(m) { + return Err(EditError::IllegalMove(mv.san.clone())); + } + let mut after = pos.clone(); + let san = SanPlus::from_move_and_play_unchecked(&mut after, m).to_string(); + Ok((GameMove { kind: mv.kind, san }, after)) + } + MoveKind::Null => { + let after = play_null(pos).map_err(|_| EditError::IllegalMove("--".into()))?; + Ok(( + GameMove { + kind: MoveKind::Null, + san: "--".into(), + }, + after, + )) + } + } +} + +/// Every move of the subtree of `source` from `s` can be made from `pos`. +fn check(source: &Game, s: NodeId, pos: &Chess) -> Result<(), EditError> { + let mut stack = vec![(s, pos.clone())]; + while let Some((id, pos)) = stack.pop() { + let mv = source.game_move(id).ok_or(EditError::UnknownNode)?; + let (_, after) = play(&pos, mv)?; + for &c in source.children(id) { + stack.push((c, after.clone())); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn game(pgn: &str) -> Game { + parse_str(pgn).game + } + + /// The node reached by the SAN moves from the root (along any branch). + fn at(g: &Game, sans: &[&str]) -> NodeId { + let mut cur = NodeId::ROOT; + for s in sans { + cur = *g + .children(cur) + .iter() + .find(|&&c| g.game_move(c).is_some_and(|m| m.san == *s)) + .unwrap_or_else(|| panic!("no {s}")); + } + cur + } + + fn sans(p: &PastePlan) -> Vec<&str> { + p.line.iter().map(|(_, _, s)| s.as_str()).collect() + } + + const SICILIAN: &str = "1. e4 c5 2. Nf3 d6 3. d4 *"; + + #[test] + fn a_game_hangs_where_it_parts_and_undoes_whole() { + let mut g = game(SICILIAN); + let before = g.canonical_tree(); + let cursor = at(&g, &["e4", "c5", "Nf3", "d6", "d4"]); + let p = plan(&g, cursor, "1.e4 c5 2.Nf3 Nc6 3.d4").unwrap(); + assert_eq!(p.at, at(&g, &["e4", "c5", "Nf3"])); + assert_eq!(sans(&p), ["Nc6", "d4"]); + assert!(!p.continuation); + let first = g.apply_paste(&p).unwrap(); + assert_eq!(g.game_move(first).unwrap().san, "Nc6"); + // The main line is the same; the variation is the last child. + assert_eq!(g.mainline().len(), 5); + assert_eq!(g.children(p.at).last(), Some(&first)); + g.undo(); + assert_eq!(g.canonical_tree(), before); + } + + #[test] + fn an_unrelated_game_is_refused() { + let g = game(SICILIAN); + let cursor = at(&g, &["e4", "c5"]); + assert_eq!( + plan(&g, cursor, "1.d4 d5 2.c4").unwrap_err(), + PasteError::Unrelated + ); + assert_eq!( + plan(&g, cursor, "[White \"A\"]\n[Black \"B\"]\n\n1.d4 d5 2.c4 *").unwrap_err(), + PasteError::Unrelated + ); + } + + #[test] + fn another_move_order_is_found_and_noted() { + let g = game(SICILIAN); + let cursor = at(&g, &["e4", "c5", "Nf3"]); + // All there by another order. + assert!(matches!( + plan(&g, cursor, "1.Nf3 c5 2.e4 d6 3.d4").unwrap_err(), + PasteError::AlreadyThere { .. } + )); + let p = plan(&g, cursor, "1.Nf3 c5 2.e4 Nc6").unwrap(); + assert_eq!(p.at, at(&g, &["e4", "c5", "Nf3"])); + assert_eq!(sans(&p), ["Nc6"]); + assert_eq!(p.transposition.as_deref(), Some("1.Nf3 c5 2.e4")); + } + + #[test] + fn fragments_after_instead_of_or_by_number() { + let g = game("1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nf6 5. f3 Bf5 6. Ng3 *"); + let bf5 = at( + &g, + &[ + "e4", "c6", "d4", "d5", "Nc3", "dxe4", "Nxe4", "Nf6", "f3", "Bf5", + ], + ); + // Instead of the selected move. + let p = plan(&g, bf5, "5...Nxe4 6.fxe4").unwrap(); + assert_eq!(p.at, g.parent(bf5).unwrap()); + assert_eq!(sans(&p), ["Nxe4", "fxe4"]); + // After it. + let p = plan(&g, bf5, "6.Qd3 e6").unwrap(); + assert_eq!(p.at, bf5); + // Without numbers. + let p = plan(&g, bf5, "Qd3 e6").unwrap(); + assert_eq!(p.at, bf5); + // By the number on the current line. + let e4 = at(&g, &["e4"]); + let p = plan(&g, e4, "4...e5").unwrap(); + assert_eq!( + p.at, + at(&g, &["e4", "c6", "d4", "d5", "Nc3", "dxe4", "Nxe4"]) + ); + // Nowhere. + assert_eq!(plan(&g, bf5, "Ke3").unwrap_err(), PasteError::DoesNotFit); + } + + #[test] + fn uci_lines_and_impossible_moves() { + let g = Game::new(); + let p = plan(&g, NodeId::ROOT, "e2e4 e7e5 g1f3").unwrap(); + assert_eq!(sans(&p), ["e4", "e5", "Nf3"]); + assert!(p.continuation); + assert_eq!( + plan(&g, NodeId::ROOT, "e2e4 e7e5 e1e3").unwrap_err(), + PasteError::Illegal { + number: 2, + side: Color::White, + san: "e1e3".into() + } + ); + let s = game(SICILIAN); + assert_eq!( + plan(&s, NodeId::ROOT, "1.e4 c5 2.Nf3 Nc6 3.Qh8").unwrap_err(), + PasteError::Illegal { + number: 3, + side: Color::White, + san: "Qh8".into() + } + ); + } + + #[test] + fn comments_variations_and_the_source_come_along() { + let mut g = game(SICILIAN); + let text = "[White \"Mellado Trivino,J\"]\n[Black \"Garcia Albarracin,F\"]\n[Result \"0-1\"]\n\n\ + 1.e4 c5 2.Nf3 Nc6 {Old.} 3.d4 $1 (3.Bb5 g6) cxd4 0-1"; + let p = plan(&g, NodeId::ROOT, text).unwrap(); + assert_eq!( + p.source_ref.as_deref(), + Some("Mellado Trivino,J – Garcia Albarracin,F") + ); + let first = g.apply_paste(&p).unwrap(); + let after = g.to_pgn(); + assert!(after.contains("{Old.}"), "{after}"); + assert!(after.contains("Bb5"), "{after}"); + assert_eq!( + g.node(g.line_end(first)).unwrap().comments_after(), + ["Mellado Trivino,J – Garcia Albarracin,F"] + ); + assert_eq!( + g.node(at(&g, &["e4", "c5", "Nf3", "Nc6", "d4"])) + .unwrap() + .nags() + .len(), + 1 + ); + // Written and read again: the same tree. + let again = game(&after); + assert_eq!(again.canonical_tree(), g.canonical_tree()); + assert!(g.is_attached(first)); + } + + #[test] + fn the_pasted_games_variations_come_along() { + let mut g = game(SICILIAN); + let before = g.canonical_tree(); + // An alternative at the parting point and one on a move in common. + let text = + "[White \"A\"]\n[Black \"B\"]\n\n1.e4 c5 (1...e5 2.Nf3) 2.Nf3 Nc6 (2...e6 3.d4) 3.d4 *"; + let p = plan(&g, NodeId::ROOT, text).unwrap(); + g.apply_paste(&p).unwrap(); + let nf3 = at(&g, &["e4", "c5", "Nf3"]); + let kids = |g: &Game, id| -> Vec { + g.children(id) + .iter() + .map(|&c| g.game_move(c).unwrap().san.clone()) + .collect() + }; + assert_eq!(kids(&g, nf3), ["d6", "Nc6", "e6"]); + assert_eq!(kids(&g, at(&g, &["e4"])), ["c5", "e5"]); + // One undo step for all of it. + g.undo(); + assert_eq!(g.canonical_tree(), before); + // Only a variation is new: it is pasted, not «already there». + let p = plan(&g, NodeId::ROOT, "1.e4 c5 (1...e6) 2.Nf3 d6 3.d4").unwrap(); + assert_eq!(p.at, at(&g, &["e4"])); + assert_eq!(sans(&p), ["e6"]); + } + + #[test] + fn black_numbers_with_an_ellipsis_character() { + let g = game(SICILIAN); + let p = plan(&g, at(&g, &["e4"]), "1…e5 2.Nf3").unwrap(); + assert_eq!(sans(&p), ["e5", "Nf3"]); + } + + #[test] + fn the_same_game_or_line_is_already_there() { + let g = game(SICILIAN); + match plan(&g, NodeId::ROOT, SICILIAN).unwrap_err() { + PasteError::AlreadyThere { at: end, comments } => { + assert_eq!(end, *g.mainline().last().unwrap()); + assert!(!comments); + } + e => panic!("{e:?}"), + } + assert!(matches!( + plan(&g, NodeId::ROOT, "1.e4 c5 {Sicilian}").unwrap_err(), + PasteError::AlreadyThere { comments: true, .. } + )); + assert_eq!( + plan(&g, NodeId::ROOT, " ").unwrap_err(), + PasteError::NoMoves + ); + } + + #[test] + fn a_game_from_a_position_with_fullmove_zero() { + let fen = "4k3/8/8/8/8/8/4P3/4K3 w - - 0 0"; + let mut g = game(&format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n1. e4 Kd7 *")); + let e4 = at(&g, &["e4"]); + let p = plan(&g, e4, "1...Ke7").unwrap(); + assert_eq!(p.at, e4); + g.apply_paste(&p).unwrap(); + assert_eq!(g.children(e4).len(), 2); + } + + #[test] + fn several_games_paste_the_first() { + let g = game(SICILIAN); + let text = "[White \"A\"]\n\n1.e4 c5 2.Nf3 Nc6 *\n\n[White \"B\"]\n\n1.e4 e5 *\n"; + let p = plan(&g, NodeId::ROOT, text).unwrap(); + assert_eq!(p.games, 2); + assert_eq!(sans(&p), ["Nc6"]); + } +} diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index 51f9dab..7888076 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -51,7 +51,7 @@ XDG_CONFIG_HOME=/tmp/cfg CP_OPEN=11 CP_PLY=3 CP_ANALYZE=1 ./target/debug/chesspe ``` `CP_OPEN` — индекс партии (с 0) в первой базе списка, `CP_PLY` — шагов по основной линии, -`CP_ONLINE=<ник>` (или `<ник Lichess>,<ник Chess.com>`) — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу скачать). `CP_UPDATE_CHECK=<адрес>` — спрашивать о выпуске этот сайт вместо chess.vrubel.xyz/api/update (локальный, чтобы проверить счёт установок). `CP_UPDATE_SOURCE=<папка>` — брать «последний выпуск» из `latest.json` и файлов этой папки вместо GitHub, `CP_UPDATE_KIND=deb|rpm|arch|aur|flatpak|appimage|tarball|windows|mac` — считать установку такой, `CP_UPDATE_OPEN=1` — открыть окно обновления (`=start` — сразу начать), `CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about`, `=translation` — сразу эту вкладку), `CP_TRANSLATE_SETUP=1` — окно «Как переводить?» (`=key` — с выбранным ключом API), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска базы с этими ходами (SAN), `CP_SORT=date` — база по дате (новые сверху), `CP_PANE=hidden` — база без правой панели (`=drawer` — фильтры поверх таблицы в узком окне), `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» базы при запуске, `CP_SEARCH="текст"` — быстрый поиск базы при запуске, `CP_KEYS="ArrowDown Shift+ArrowUp Ctrl+Z Escape"` — нажать эти клавиши (имена egui, по одной раз в полсекунды со второй секунды; модификаторы `Shift+`, `Ctrl+`), `CP_OWN=new|chooser|data|save|delete|newin` (`newin` — «+ Партия» первой базы) — открыть диалог своих баз через 1,5 с: новая база, «Добавить в базу» (для открытой партии, иначе для записи `CP_OPEN` первой базы), данные партии, Ctrl+S, удаление записи `CP_OPEN` первой базы; `CP_PASTE="<текст PGN>"` — перед `CP_OWN` открыть эту партию как вставленную (без базы), `CP_COMMENT=текст` — комментарий к ходу после `CP_PLY` (партия считается изменённой), `CP_COMMENT_EDIT=1` — открыть редактор комментария на текущем ходе, `CP_SHAPE=Ge2e4,Rd5` — нарисовать стрелки/круги на доске у текущего хода (как правой кнопкой), `CP_TYPE=текст` — напечатать текст в поле с фокусом через 2,5 с (после `CP_KEYS`, которые начинаются со 2-й секунды, если их мало), `CP_SETTINGS=interface` — вкладка «Интерфейс», `CP_PLAY=white|black[,5+3|none][,1500]` — сразу начать партию с Maia (`CP_PLAY=dialog` — открыть диалог «Игра с компьютером»), `CP_MAIA=путь/maia3-5m.pt` — веса Maia из этого файла вместо скачанных, `CP_PLAY_AUTO=1` — за пользователя тоже ходит Maia, быстро (партия до конца без мыши), `CP_PREMOVE=e7e5` — в начале партии поставить этот предход (виден подсветкой, играется сразу после ответа Maia, если легален), `CP_LOG_FRAMES=1` — писать в `chesspenguin.log` отладочные сообщения egui_wgpu о каждом кадре (пропущенный как «occluded» кадр виден только там); предупреждения библиотек (wgpu, winit) пишутся туда всегда, одинаковые — раз в минуту со счётчиком, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_PANEL_CHECK=1` — сообщать в stderr о боковой панели, чьё содержимое шире её места (egui тогда задвигает панель под соседнюю); в отладочной сборке egui ещё и подсвечивает красным, что расширяет родителя (`docs/design/narrow-windows.md`). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). +`CP_ONLINE=<ник>` (или `<ник Lichess>,<ник Chess.com>`) — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу скачать). `CP_UPDATE_CHECK=<адрес>` — спрашивать о выпуске этот сайт вместо chess.vrubel.xyz/api/update (локальный, чтобы проверить счёт установок). `CP_UPDATE_SOURCE=<папка>` — брать «последний выпуск» из `latest.json` и файлов этой папки вместо GitHub, `CP_UPDATE_KIND=deb|rpm|arch|aur|flatpak|appimage|tarball|windows|mac` — считать установку такой, `CP_UPDATE_OPEN=1` — открыть окно обновления (`=start` — сразу начать), `CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about`, `=translation` — сразу эту вкладку), `CP_TRANSLATE_SETUP=1` — окно «Как переводить?» (`=key` — с выбранным ключом API), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска базы с этими ходами (SAN), `CP_SORT=date` — база по дате (новые сверху), `CP_PANE=hidden` — база без правой панели (`=drawer` — фильтры поверх таблицы в узком окне), `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» базы при запуске, `CP_SEARCH="текст"` — быстрый поиск базы при запуске, `CP_KEYS="ArrowDown Shift+ArrowUp Ctrl+Z Escape"` — нажать эти клавиши (имена egui, по одной раз в полсекунды со второй секунды; модификаторы `Shift+`, `Ctrl+`), `CP_OWN=new|chooser|data|save|delete|newin` (`newin` — «+ Партия» первой базы) — открыть диалог своих баз через 1,5 с: новая база, «Добавить в базу» (для открытой партии, иначе для записи `CP_OPEN` первой базы), данные партии, Ctrl+S, удаление записи `CP_OPEN` первой базы; `CP_PASTE="<текст PGN>"` — перед `CP_OWN` открыть эту партию как вставленную (без базы), `CP_COMMENT=текст` — комментарий к ходу после `CP_PLY` (партия считается изменённой), `CP_COMMENT_EDIT=1` — открыть редактор комментария на текущем ходе, `CP_SHAPE=Ge2e4,Rd5` — нарисовать стрелки/круги на доске у текущего хода (как правой кнопкой), `CP_TYPE=текст` — напечатать текст в поле с фокусом через 2,5 с (после `CP_KEYS`, которые начинаются со 2-й секунды, если их мало), `CP_SETTINGS=interface` — вкладка «Интерфейс», `CP_PLAY=white|black[,5+3|none][,1500]` — сразу начать партию с Maia (`CP_PLAY=dialog` — открыть диалог «Игра с компьютером»), `CP_MAIA=путь/maia3-5m.pt` — веса Maia из этого файла вместо скачанных, `CP_PLAY_AUTO=1` — за пользователя тоже ходит Maia, быстро (партия до конца без мыши), `CP_PREMOVE=e7e5` — в начале партии поставить этот предход (виден подсветкой, играется сразу после ответа Maia, если легален), `CP_PASTE_LINE="<текст>"` — после `CP_OPEN`/`CP_PLY` вставить текст как вариант, как Ctrl+V (`docs/design/paste-variation.md`), `CP_PLAY_FROM=dialog|white|black[,сила]` — «Играть отсюда…» с хода `CP_PLY`: диалог или сразу партия, `CP_TRAIN=1` — «Учить дебют до этого хода» с хода `CP_PLY`, `CP_TRAIN_MOVES="e2e4 e7e5"` — ходы тренировки как с доски (UCI; неверный — ошибка), `CP_TRAIN_KEEP=1` — последний неверный ход хука остаётся показанным, `CP_TRAINING_FILE=путь` — статистика тренировок в этом файле вместо `training.json`, `CP_LOG_FRAMES=1` — писать в `chesspenguin.log` отладочные сообщения egui_wgpu о каждом кадре (пропущенный как «occluded» кадр виден только там); предупреждения библиотек (wgpu, winit) пишутся туда всегда, одинаковые — раз в минуту со счётчиком, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_PANEL_CHECK=1` — сообщать в stderr о боковой панели, чьё содержимое шире её места (egui тогда задвигает панель под соседнюю); в отладочной сборке egui ещё и подсвечивает красным, что расширяет родителя (`docs/design/narrow-windows.md`). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). ## Языки