From 29ded2f55f0c4fd12be0fb43947086d2af5b9f5b Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Thu, 22 Oct 2026 19:57:53 +0300 Subject: [PATCH] =?UTF-8?q?Desktop:=20=E2=86=91=20to=20the=20end,=20?= =?UTF-8?q?=E2=86=93=20to=20the=20start,=20Escape=20leaves=20the=20game?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Variations move to Shift+↑/↓. Escape cancels a preview or a picked-up piece first, then returns to the previous game or the library; a window, menu or dialog open over the game (this frame or the last) keeps the key. CP_KEYS presses keys for manual checks. Also drops an empty database of a local site run committed by mistake. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 3 ++ CHANGELOG.md | 8 ++++ README.md | 2 +- apps/desktop/src/app.rs | 62 ++++++++++++++++++++++++++++++- apps/desktop/src/board.rs | 5 +++ apps/desktop/src/engine_offer.rs | 5 ++- apps/desktop/src/game_view.rs | 30 ++++++++++++--- apps/desktop/src/i18n.rs | 16 ++++++++ data-dev/d.sqlite | Bin 20480 -> 0 bytes docs/dev/desktop.md | 2 +- 10 files changed, 123 insertions(+), 10 deletions(-) delete mode 100644 data-dev/d.sqlite diff --git a/.gitignore b/.gitignore index 9942163..d878c7d 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,6 @@ # Third-party reference screenshots (kept locally, not published) /designExample/ + +# A local run of the website from the repository root (website/README.md runs it from server/). +/data-dev/ diff --git a/CHANGELOG.md b/CHANGELOG.md index dcf6ad6..a5b532d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). +## [Unreleased] + +- Keys in a game: ↑ goes to the end, ↓ to the start (as End and Home); variations are + switched with Shift+↑/↓. Escape first closes what is open (a preview of an engine line, + a picked-up piece); then it goes back to the game this one was opened from, or to the + library. A window, menu or dialog over the game keeps Escape for itself, and a game with + unsaved changes still asks first. + ## [0.10.0] — 2026-10-22 - **ChessPenguin for Android, alpha** (12 and newer): add databases of the same formats (PGN, ChessBase diff --git a/README.md b/README.md index db66895..64e1ec5 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ cargo run --release -p chesspenguin -- examples/classics.pgn | Where | Keys | | --- | --- | | Library | ↑/↓ select · Enter open · Ctrl+O add PGN · Ctrl+N new game · Ctrl+F search | -| Game | ←/→ move · ↑/↓ switch variation · Home/End · F flip · L engine · Shift+A game analysis · Esc leave preview | +| Game | ←/→ move · ↑ end · ↓ start (also End/Home) · Shift+↑/↓ switch variation · F flip · L engine · Shift+A game analysis · Esc leave a preview, then back to the previous game or the library | | Editing | Ctrl+Z / Ctrl+Y undo/redo · Ctrl+Shift+C copy PGN · Ctrl+S save as · Ctrl+W back to library | ## Project layout diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index ad285d2..ce49e6d 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -25,6 +25,24 @@ enum Async { EngineChecked(Result<(PathBuf, String), String>), } +/// The id of the toast: a passing message, never in the way of the keyboard. +pub const TOAST: &str = "toast"; + +/// Something is open over the screen — a window, a menu, a dialog — in this frame or the +/// last one: Escape is meant for it (it closes itself), not for leaving the screen. +pub fn overlay_open(ctx: &egui::Context) -> bool { + let passive = [ + egui::Id::new(TOAST), + egui::Id::new(crate::engine_offer::DOWNLOAD_INDICATOR), + ]; + ctx.memory(|m| m.areas().visible_layer_ids()) + .iter() + .any(|l| { + matches!(l.order, egui::Order::Middle | egui::Order::Foreground) + && !passive.contains(&l.id) + }) +} + #[derive(Clone, Copy, PartialEq)] enum CloseIntent { BackToLibrary, @@ -80,7 +98,9 @@ pub struct App { /// Dev-only startup automation for screenshots/manual QA (see docs/dev/desktop.md): /// `CP_OPEN=` opens a game from the first database, `CP_PLY=` steps /// along the main line, `CP_ANALYZE=1` starts the engine, `CP_SETTINGS=1` opens settings (`=board`, `=about`: that tab), -/// `CP_REVIEW=1` starts the whole-game analysis (`=dialog` only opens its dialog). +/// `CP_REVIEW=1` starts the whole-game analysis (`=dialog` only opens its dialog), +/// `CP_KEYS="ArrowDown Shift+ArrowUp Escape"` presses these keys, one every half second +/// from the second second. #[derive(Default)] struct DebugStartup { open: Option, @@ -92,6 +112,8 @@ struct DebugStartup { screenshot_delay: f64, screenshot_requested: bool, open_settings: bool, + keys: std::collections::VecDeque<(Modifiers, Key)>, + next_key: f64, } impl DebugStartup { @@ -108,6 +130,18 @@ impl DebugStartup { .unwrap_or(4.0), screenshot_requested: false, open_settings: false, + keys: std::env::var("CP_KEYS") + .unwrap_or_default() + .split_whitespace() + .filter_map(|k| { + let (shift, name) = match k.strip_prefix("Shift+") { + Some(name) => (Modifiers::SHIFT, name), + None => (Modifiers::NONE, k), + }; + Key::from_name(name).map(|key| (shift, key)) + }) + .collect(), + next_key: 2.0, } } } @@ -217,6 +251,29 @@ impl App { self } + fn debug_keys(&mut self, ctx: &egui::Context) { + if self.debug.keys.is_empty() { + return; + } + let now = ctx.input(|i| i.time); + if now >= self.debug.next_key + && let Some((modifiers, key)) = self.debug.keys.pop_front() + { + self.debug.next_key = now + 0.5; + ctx.input_mut(|i| { + i.modifiers = modifiers; + i.events.push(egui::Event::Key { + key, + physical_key: None, + pressed: true, + repeat: false, + modifiers, + }); + }); + } + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + } + fn debug_screenshot(&mut self, ctx: &egui::Context) { if self.debug.open_settings && ctx.input(|i| i.time) > 1.5 { self.debug.open_settings = false; @@ -781,6 +838,7 @@ impl eframe::App for App { } self.offer_events(&ctx); self.debug_step(&ctx); + self.debug_keys(&ctx); self.debug_screenshot(&ctx); self.analysis.poll(); @@ -1064,7 +1122,7 @@ impl eframe::App for App { if now > *until { self.toast = None; } else { - egui::Area::new(egui::Id::new("toast")) + egui::Area::new(egui::Id::new(TOAST)) .anchor(egui::Align2::CENTER_BOTTOM, egui::vec2(0.0, -24.0)) .order(egui::Order::Foreground) .show(&ctx, |ui| { diff --git a/apps/desktop/src/board.rs b/apps/desktop/src/board.rs index cded68c..45ba1db 100644 --- a/apps/desktop/src/board.rs +++ b/apps/desktop/src/board.rs @@ -43,6 +43,11 @@ impl BoardState { self.drag = None; self.promotion = None; } + + /// A piece is selected or dragged, or a promotion is being chosen. + pub fn is_busy(&self) -> bool { + self.selected.is_some() || self.drag.is_some() || self.promotion.is_some() + } } /// Pieces moving from one position to the next, as on Lichess (chessground): each piece diff --git a/apps/desktop/src/engine_offer.rs b/apps/desktop/src/engine_offer.rs index 69b5724..7f732f6 100644 --- a/apps/desktop/src/engine_offer.rs +++ b/apps/desktop/src/engine_offer.rs @@ -11,6 +11,9 @@ use crate::engine_download::{self, Download, Failure, Stage}; use crate::i18n::{tr, trf}; use crate::settings::Settings; +/// The id of the download indicator in the corner (it is never in the way of Escape). +pub const DOWNLOAD_INDICATOR: &str = "download_indicator"; + /// What the user wanted to do when the engine turned out to be missing. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Pending { @@ -399,7 +402,7 @@ impl EngineOffer { Some(_) => "⬇ Stockfish…".to_string(), None => tr("⚠ Stockfish wasn't downloaded").to_string(), }; - egui::Area::new(egui::Id::new("download_indicator")) + egui::Area::new(egui::Id::new(DOWNLOAD_INDICATOR)) .anchor(egui::Align2::RIGHT_BOTTOM, vec2(-12.0, -12.0)) .order(egui::Order::Foreground) .show(ctx, |ui| { diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 4756e9b..ff71e8d 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -448,7 +448,11 @@ impl GameView { ui.horizontal(|ui| { if ui .button(tr("⬅ Library")) - .on_hover_text(tr("Back to the game list (Ctrl+W)")) + .on_hover_text(if self.previous.is_some() { + tr("Back to the game list (Ctrl+W)") + } else { + tr("Back to the game list (Esc, Ctrl+W)") + }) .clicked() { actions.push(GameAction::Back); @@ -456,7 +460,7 @@ impl GameView { if let Some(t) = &self.previous && ui .button(trf("⬅ Back to {game}", &[("game", t)])) - .on_hover_text(tr("The game this one was opened from, as you left it")) + .on_hover_text(tr("The game this one was opened from, as you left it (Esc)")) .clicked() { actions.push(GameAction::ReturnToPrevious); @@ -1403,12 +1407,18 @@ impl GameView { if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::A)) { cmds.push("review"); } + if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::ArrowUp)) { + cmds.push("prev_var"); + } + if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::ArrowDown)) { + cmds.push("next_var"); + } if i.modifiers.is_none() { for (key, cmd) in [ (Key::ArrowLeft, "back1"), (Key::ArrowRight, "fwd1"), - (Key::ArrowUp, "prev_var"), - (Key::ArrowDown, "next_var"), + (Key::ArrowUp, "end"), + (Key::ArrowDown, "home"), (Key::Home, "home"), (Key::End, "end"), (Key::F, "flip"), @@ -1469,11 +1479,21 @@ impl GameView { self.review.dialog_open = true; } } + // Escape cancels what is going on first (a preview of an engine line, a + // piece picked up); then it leaves the game: to the game this one was + // opened from, or to the library. A window, menu or dialog open over the + // game takes the key itself. "esc" => { if self.preview.is_some() { self.preview = None; - } else { + } else if self.board.is_busy() { self.board.clear(); + } else if !crate::app::overlay_open(ui.ctx()) { + actions.push(if self.previous.is_some() { + GameAction::ReturnToPrevious + } else { + GameAction::Back + }); } } _ => {} diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 2983f0c..c298f50 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -3401,6 +3401,14 @@ const ROWS: &[[&str; 6]] = &[ "La partida desde la que se abrió esta, tal como la dejaste", "La partita da cui è stata aperta questa, come l'hai lasciata", ], + [ + "The game this one was opened from, as you left it (Esc)", + "Партия, из которой открыта эта, — в том виде, как вы её оставили (Esc)", + "La partie d'où celle-ci a été ouverte, telle que vous l'avez laissée (Esc)", + "Die Partie, aus der diese geöffnet wurde, so wie Sie sie verlassen haben (Esc)", + "La partida desde la que se abrió esta, tal como la dejaste (Esc)", + "La partita da cui è stata aperta questa, come l'hai lasciata (Esc)", + ], [ "⬅ Back to {game}", "⬅ К партии {game}", @@ -4841,6 +4849,14 @@ const ROWS: &[[&str; 6]] = &[ "Volver a la lista de partidas (Ctrl+W)", "Torna all'elenco delle partite (Ctrl+W)", ], + [ + "Back to the game list (Esc, Ctrl+W)", + "Вернуться к списку партий (Esc, Ctrl+W)", + "Retour à la liste des parties (Esc, Ctrl+W)", + "Zurück zur Partienliste (Esc, Ctrl+W)", + "Volver a la lista de partidas (Esc, Ctrl+W)", + "Torna all'elenco delle partite (Esc, Ctrl+W)", + ], [ "PGN compatibility notes", "Замечания по совместимости PGN", diff --git a/data-dev/d.sqlite b/data-dev/d.sqlite deleted file mode 100644 index 9b6eee029f07e017edc19d02cd8a6332b11df33f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 20480 zcmeI%(Q4XI7zgl}+Lg9AdROR;-_2-+xX}rP-ObrJWSMR@Ld!13sU9^<6G@J`U2o96 zz}{dlu-Dk*>2lkaTm0COgM7Rr|K?KTRYP5S{OxC<@Jq|@9%;Krh41@6_PeW!aU22=fB*y_009VW zR^UrLw{uu5=DxlY?0Up|-rOB|tQRB$z1B9Xwn=vNg=JE5m`?U6{cw8JXxipWvrTW> zjn~!o6}>XA47ErEWSf^ZHCuA)SeB9QP%cx)t{K#>*QipdJX24djF<@jeakdZi)P#p z9M8S8h6Mo^cUE-0sVn?XQH`>~aJ6!kjf)mlPS4KDr^H5+AuB&sSK;$Pyok)}?>b`H zRy||H+`-?cTg=#Z{6NsP@67}5Q&>G^1FrV)d7t~fd^!?N!!CLZJ=wzRlNfSZ)H-s~ ziPFcQnG-m|TQo7~gX8v8Dmpjo)sAJ;@o+k3?y*5r7FCq2{DZ?s#avgO!as&>XAYkS z??sS|x0gw3G|$b;Xy&+tTFu*iIuSwX^JFWE<;{~QmPwCfkXK@v9A0}Yhv9YYhU2=nycj5f%UmG-@9SEr z5Pr!XZ1$TLvqJy^5P$##AOHafKmY;|fB*y_aK8e3VSC*F-!C${LjVF0fB*y_009U< z00Izz00cHHfZzW&{03lp2tWV=5P$##AOHafKmY;|fWR6A@caK7kTC@WAOHafKmY;| QfB*y_009U` (или `<ник Lichess>,<ник Chess.com>`) — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу скачать). `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` — большая база без правой панели, `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров большой базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» большой базы ChessBase при запуске, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). +`CP_ONLINE=<ник>` (или `<ник Lichess>,<ник Chess.com>`) — открыть окно онлайн-партий и найти ник (`CP_ONLINE_DOWNLOAD=1` — сразу скачать). `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` — большая база без правой панели, `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров большой базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» большой базы ChessBase при запуске, `CP_KEYS="ArrowDown Shift+ArrowUp Escape"` — нажать эти клавиши (имена egui, по одной раз в полсекунды со второй секунды), `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). ## Языки