User comments: an editor in the notation, symbols, arrows on the board
Some checks are pending
CI / macos-build (push) Waiting to run
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run

Enter on a move (the move's menu, a double click on a comment, the ☰ menu) opens
the editor where the comment stands: after any move, in a variation too (the
flow is cut at the move), or at the start of the game; Enter — done, Esc —
cancel, Shift+Enter — a paragraph; another move writes the draft; one edit —
one undo step. Symbols of the move (! ? !! ?? !? ?!, Ctrl+1…6) and of the
position in the editor and in the menu. The right mouse button draws arrows
and circles on the board ([%cal]/[%csl] of the current move; colours by
modifiers). Existing comments are edited and deleted; their commands and
untouched bytes are kept. chess_core: with_text, with_shapes, shapes,
Game::set_comments_before. Dev hooks CP_COMMENT_EDIT, CP_TYPE, CP_SHAPE.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-25 02:35:54 +03:00
parent 9967d6b759
commit dc7d9f88b3
15 changed files with 1592 additions and 71 deletions

View file

@ -242,6 +242,8 @@ struct DebugStartup {
own: Option<String>,
keys: std::collections::VecDeque<(Modifiers, Key)>,
next_key: f64,
/// `CP_TYPE=<text>`: typed into the field that has the keyboard, 2.5 s after start.
typed: Option<String>,
}
impl DebugStartup {
@ -281,6 +283,7 @@ impl DebugStartup {
})
.collect(),
next_key: 2.0,
typed: std::env::var("CP_TYPE").ok(),
}
}
}
@ -397,10 +400,15 @@ impl App {
}
fn debug_keys(&mut self, ctx: &egui::Context) {
let now = ctx.input(|i| i.time);
if now >= 2.5
&& let Some(text) = self.debug.typed.take()
{
ctx.input_mut(|i| i.events.push(egui::Event::Text(text)));
}
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()
{
@ -504,6 +512,12 @@ impl App {
if let Ok(text) = std::env::var("CP_COMMENT") {
g.debug_comment(&text);
}
if let Ok(spec) = std::env::var("CP_SHAPE") {
g.debug_shapes(&spec);
}
if std::env::var_os("CP_COMMENT_EDIT").is_some() {
g.debug_comment_edit();
}
if std::env::var("CP_ENGINE_PANEL").is_ok() {
g.debug_open_engine_settings();
}
@ -1664,6 +1678,10 @@ impl App {
}
fn request_close(&mut self, ctx: &egui::Context, intent: CloseIntent) {
// A comment being written goes into the game first.
if let Some(g) = self.game.as_mut() {
g.commit_editor();
}
if self.game.as_ref().is_some_and(|g| g.game.is_modified()) {
self.confirm_close = Some(intent);
} else {

View file

@ -23,11 +23,24 @@ pub struct Badge {
}
/// Interaction state that lives across frames (per board instance).
/// A shape the user drew with the right mouse button (docs/design/user-comments.md
/// §10): an arrow, or a circle on one square. The colour is the modifier held when the
/// button was released: none green, Shift red, Alt blue, Shift+Alt yellow (Lichess).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Drawn {
Arrow(chess_core::ShapeColor, Square, Square),
Circle(chess_core::ShapeColor, Square),
}
#[derive(Default)]
pub struct BoardState {
selected: Option<Square>,
drag: Option<Square>,
promotion: Option<(Square, Square)>,
/// The square the right button went down on: a shape is being drawn.
shape_from: Option<Square>,
/// A shape drawn this frame, for the game to take (`take_shape`).
shape: Option<Drawn>,
/// The position drawn last: a different one next frame is animated from it.
shown: Option<Board>,
anim: Option<Anim>,
@ -44,6 +57,11 @@ impl BoardState {
self.promotion = None;
}
/// The shape the user has just drawn, once.
pub fn take_shape(&mut self) -> Option<Drawn> {
self.shape.take()
}
/// 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()
@ -182,8 +200,32 @@ impl BoardView<'_> {
_ => state.selected = self.own_piece(sq).then_some(sq),
}
}
// The right button draws: a drag — an arrow, a click — a circle on the square.
// Pressing it also drops a picked-up piece, as before.
if response.drag_started_by(egui::PointerButton::Secondary) {
let origin = ui.input(|i| i.pointer.press_origin()).or(pointer);
state.shape_from = origin.and_then(|p| geo.square_at(p));
state.selected = None;
state.drag = None;
}
if response.drag_stopped_by(egui::PointerButton::Secondary) {
let to = ui
.input(|i| i.pointer.latest_pos())
.and_then(|p| geo.square_at(p));
let color = shape_color_for(ui.input(|i| i.modifiers));
if let Some(from) = state.shape_from.take() {
state.shape = Some(match to {
Some(to) if to != from => Drawn::Arrow(color, from, to),
_ => Drawn::Circle(color, from),
});
}
}
if response.secondary_clicked() {
state.clear();
if let Some(sq) = pointer.and_then(|p| geo.square_at(p)) {
let color = shape_color_for(ui.input(|i| i.modifiers));
state.shape = Some(Drawn::Circle(color, sq));
}
}
}
@ -305,6 +347,35 @@ impl BoardView<'_> {
for a in self.arrows {
draw_arrow(&painter, &geo, a);
}
if let Some(from) = state.shape_from
&& response.dragged_by(egui::PointerButton::Secondary)
{
let color = shape_color_for(ui.input(|i| i.modifiers));
let c = shape_preview_color(color);
match ui
.input(|i| i.pointer.latest_pos())
.and_then(|p| geo.square_at(p))
{
Some(to) if to != from => draw_arrow(
&painter,
&geo,
&Arrow {
from,
to,
color: c,
weight: 0.9,
},
),
_ => {
let r = geo.square_rect(from);
painter.circle_stroke(
r.center(),
sq_size * 0.46,
Stroke::new(sq_size * 0.07, c),
);
}
}
}
if let Some(b) = self.badge {
let r = geo.square_rect(b.square);
let radius = sq_size * 0.19;
@ -509,6 +580,27 @@ impl Geometry {
}
}
/// The colour of a shape from the modifiers held (as on Lichess).
fn shape_color_for(m: egui::Modifiers) -> chess_core::ShapeColor {
match (m.shift, m.alt) {
(false, false) => chess_core::ShapeColor::Green,
(true, false) => chess_core::ShapeColor::Red,
(false, true) => chess_core::ShapeColor::Blue,
(true, true) => chess_core::ShapeColor::Yellow,
}
}
/// How a shape being drawn looks (the game draws the finished ones).
pub fn shape_preview_color(c: chess_core::ShapeColor) -> Color32 {
match c {
chess_core::ShapeColor::Red => Color32::from_rgba_unmultiplied(136, 32, 32, 170),
chess_core::ShapeColor::Green => Color32::from_rgba_unmultiplied(21, 120, 27, 170),
chess_core::ShapeColor::Blue => Color32::from_rgba_unmultiplied(0, 48, 136, 170),
chess_core::ShapeColor::Yellow => Color32::from_rgba_unmultiplied(230, 143, 0, 170),
chess_core::ShapeColor::Other(_) => Color32::from_rgba_unmultiplied(120, 120, 120, 170),
}
}
fn draw_arrow(painter: &egui::Painter, geo: &Geometry, a: &Arrow) {
let from = geo.center(a.from);
let to = geo.center(a.to);

View file

@ -6,15 +6,17 @@ use std::path::PathBuf;
use chess_core::shakmaty::{Chess, Color, Move, Position, Square};
use chess_core::{
Annotation, CommentPart, Diagnostic, Game, GameResult, MoveKind, NodeId, Severity, ShapeColor,
parse_comment,
Annotation, CommentPart, Diagnostic, Game, GameResult, MoveKind, Nag, NodeId, Severity,
ShapeColor, parse_comment,
};
use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText, Sense, Ui, vec2};
use crate::analysis::{self, Analysis, PvLine, Status};
use crate::assets::Sound;
use crate::board::{self, Arrow, BoardState, BoardView};
use crate::notation::{Notation, NotationCommand};
use crate::notation::{
CommentEditor, EditorOutcome, MOVE_NAGS, Notation, NotationCommand, Slot, toggle_nag,
};
use crate::review::{DialogAction, ReportAction, Review};
use crate::settings::Settings;
@ -58,6 +60,8 @@ pub struct GameView {
flipped: bool,
preview: Option<Preview>,
scroll_to_cursor: bool,
/// The comment being written (user-comments.md).
editor: Option<CommentEditor>,
show_diagnostics: bool,
engine_settings_open: bool,
review: Review,
@ -133,6 +137,7 @@ impl GameView {
flipped,
preview: None,
scroll_to_cursor: true,
editor: None,
show_diagnostics: false,
engine_settings_open: false,
review,
@ -249,6 +254,8 @@ impl GameView {
fn goto(&mut self, id: NodeId) {
if id != self.cursor {
// Leaving the move writes the comment being written (user-comments.md §4).
self.commit_editor();
self.cursor = id;
self.board.clear();
self.scroll_to_cursor = true;
@ -256,6 +263,272 @@ impl GameView {
self.preview = None;
}
// ----- comments (docs/design/user-comments.md) ------------------------------------
/// «4.Ba4» / «4…Nf6» as the editor's title names the move.
fn move_name(&self, id: NodeId) -> String {
let Some((num, color)) = self.game.move_number(id) else {
return String::new();
};
let san = self
.game
.game_move(id)
.map(|m| m.san.as_str())
.unwrap_or("?");
let san = crate::san::show(san);
match color {
Color::White => format!("{num}.{san}"),
Color::Black => format!("{num}…{san}"),
}
}
/// Opens the editor on this comment (the one open before is written first). The
/// move becomes the current one.
fn open_editor(&mut self, slot: Slot) {
if self.preview.is_some() {
return;
}
if self.editor.as_ref().is_some_and(|e| e.slot == slot) {
if let Some(e) = self.editor.as_mut() {
e.focus = true;
}
return;
}
self.commit_editor();
let id = slot.node();
let Some(node) = self.game.node(id) else {
return;
};
let (original, nags, title, short) = match slot {
Slot::After(NodeId::ROOT) => (
node.comments_after().to_vec(),
Vec::new(),
tr("Comment at the start of the game").to_owned(),
tr("At the start").to_owned(),
),
Slot::After(_) => (
node.comments_after().to_vec(),
node.nags().to_vec(),
trf("Comment after {move}", &[("move", &self.move_name(id))]),
trf("After {move}", &[("move", &self.move_name(id))]),
),
Slot::Before(_) => (
node.comments_before().to_vec(),
Vec::new(),
trf("Comment before {move}", &[("move", &self.move_name(id))]),
trf("Before {move}", &[("move", &self.move_name(id))]),
),
};
let text = chess_core::comment_display_text(&original);
let translated = self
.translation
.shown()
.and_then(|m| m.get(&text))
.is_some_and(|m| matches!(m, crate::translate_ui::Mark::Translated(_)));
if matches!(slot, Slot::After(_)) && id != NodeId::ROOT {
self.goto(id);
}
self.editor = Some(CommentEditor {
slot,
initial: text.clone(),
text,
initial_nags: nags.clone(),
nags,
title,
short_title: short,
translated,
focus: true,
scroll: true,
field_id: None,
});
}
/// Writes the comment being written into the game (one undo step) and closes the
/// editor; nothing written when nothing changed. Also for the program: before the
/// game is left or saved.
pub fn commit_editor(&mut self) {
let Some(ed) = self.editor.take() else { return };
if !ed.changed() {
return;
}
let id = ed.slot.node();
let Some(node) = self.game.node(id) else {
return;
};
match ed.slot {
Slot::After(_) => {
let original = node.comments_after().to_vec();
let comments = if ed.text_changed() {
chess_core::with_text(&original, &ed.text)
} else {
original
};
let _ = self.game.annotate(id, ed.nags, comments);
}
Slot::Before(_) => {
let original = node.comments_before().to_vec();
let _ = self
.game
.set_comments_before(id, chess_core::with_text(&original, &ed.text));
}
}
self.scroll_to_cursor = true;
}
fn cancel_editor(&mut self) {
self.editor = None;
self.scroll_to_cursor = true;
}
/// The editor's text field has the keyboard.
fn editor_focused(&self, ui: &Ui) -> bool {
self.editor
.as_ref()
.and_then(|e| e.field_id)
.is_some_and(|id| ui.ctx().memory(|m| m.focused() == Some(id)))
}
/// The keys of the editor, taken before the text field sees them: Enter — done,
/// Shift+Enter — a paragraph, Esc — cancel, Ctrl+S / Ctrl+W — done and then the
/// action, Ctrl+1…6 — the move's symbol in the draft.
fn editor_keys(&mut self, ui: &Ui, actions: &mut Vec<GameAction>) {
if !self.editor_focused(ui) {
return;
}
let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k);
let (done, paragraph, cancel, save, back, nag) = ui.input_mut(|i| {
let done =
i.consume_key(Modifiers::NONE, Key::Enter) || i.consume_shortcut(&ctrl(Key::Enter));
let paragraph = i.consume_key(Modifiers::SHIFT, Key::Enter);
let cancel = i.consume_key(Modifiers::NONE, Key::Escape);
let save = i.consume_shortcut(&ctrl(Key::S));
let back = i.consume_shortcut(&ctrl(Key::W));
let nag = [
Key::Num1,
Key::Num2,
Key::Num3,
Key::Num4,
Key::Num5,
Key::Num6,
]
.into_iter()
.zip(MOVE_NAGS)
.find(|(k, _)| i.consume_shortcut(&ctrl(*k)))
.map(|(_, (nag, _, _))| nag);
(done, paragraph, cancel, save, back, nag)
});
if let Some(nag) = nag
&& let Some(ed) = self.editor.as_mut()
{
ed.nags = toggle_nag(&ed.nags, nag);
}
if paragraph && let Some(ed) = self.editor.as_mut() {
// A blank line at the cursor.
let Some(field) = ed.field_id else { return };
let mut state = egui::TextEdit::load_state(ui.ctx(), field).unwrap_or_default();
let at = state
.cursor
.char_range()
.map_or(ed.text.chars().count(), |r| r.primary.index.into());
let byte = ed
.text
.char_indices()
.nth(at)
.map_or(ed.text.len(), |(b, _)| b);
ed.text.insert_str(byte, "\n\n");
state
.cursor
.set_char_range(Some(egui::text::CCursorRange::one(
egui::text::CCursor::new(at + 2),
)));
state.store(ui.ctx(), field);
}
if cancel {
self.cancel_editor();
} else if done || save || back {
self.commit_editor();
if save {
actions.push(GameAction::Save);
}
if back {
actions.push(GameAction::Back);
}
}
}
/// A symbol put on or taken off a move at once (the menu, Ctrl+1…6): one undo step.
fn toggle_nag_on(&mut self, id: NodeId, nag: Nag) {
if id == NodeId::ROOT {
return;
}
let Some(node) = self.game.node(id) else {
return;
};
let nags = toggle_nag(node.nags(), nag);
let comments = node.comments_after().to_vec();
let _ = self.game.annotate(id, nags, comments);
}
/// Deletes a comment (its board commands and clocks stay); undoable.
fn delete_comment(&mut self, slot: Slot, actions: &mut Vec<GameAction>) {
if self.editor.as_ref().is_some_and(|e| e.slot == slot) {
self.editor = None;
}
let id = slot.node();
let Some(node) = self.game.node(id) else {
return;
};
let done = match slot {
Slot::After(_) => {
let comments = chess_core::with_text(node.comments_after(), "");
self.game.annotate(id, node.nags().to_vec(), comments)
}
Slot::Before(_) => {
let comments = chess_core::with_text(node.comments_before(), "");
self.game.set_comments_before(id, comments)
}
};
if done.is_ok() {
actions.push(GameAction::Toast(
tr("Comment deleted (Ctrl+Z to undo)").to_owned(),
));
}
}
/// An arrow or a circle drawn on the board goes into the comment of the current move
/// (`[%cal]`, `[%csl]`); the same shape again takes it off, another colour replaces it.
fn apply_shape(&mut self, drawn: board::Drawn) {
let id = self.cursor;
let Some(node) = self.game.node(id) else {
return;
};
let (mut arrows, mut squares) = chess_core::shapes(node.comments_after());
match drawn {
board::Drawn::Arrow(color, from, to) => {
let same = arrows.iter().position(|(_, a, b)| *a == from && *b == to);
match same {
Some(i) if arrows[i].0 == color => {
arrows.remove(i);
}
Some(i) => arrows[i].0 = color,
None => arrows.push((color, from, to)),
}
}
board::Drawn::Circle(color, sq) => {
let same = squares.iter().position(|(_, s)| *s == sq);
match same {
Some(i) if squares[i].0 == color => {
squares.remove(i);
}
Some(i) => squares[i].0 = color,
None => squares.push((color, sq)),
}
}
}
let comments = chess_core::with_shapes(node.comments_after(), &arrows, &squares);
let _ = self.game.annotate(id, node.nags().to_vec(), comments);
}
/// Assessment of the move that led to the current position, for the board: the
/// engine's judgement when the game analysis is shown, otherwise the author's
/// `!`/`?` symbol.
@ -326,6 +599,7 @@ impl GameView {
self.review.note_live_speed(analysis.nps, e.threads);
}
if input_enabled && !self.review.dialog_open {
self.editor_keys(ui, &mut actions);
self.keyboard(ui, &mut actions);
}
@ -909,6 +1183,11 @@ impl GameView {
if let Some(m) = view.show(ui, &mut self.board) {
self.play_move(m, actions);
}
if let Some(drawn) = self.board.take_shape()
&& self.preview.is_none()
{
self.apply_shape(drawn);
}
});
});
if show_graph {
@ -1030,11 +1309,26 @@ impl GameView {
.as_ref()
.map(|p| (p.base, p.san.as_slice(), p.shown)),
translations: self.translation.shown(),
editor: self.editor.as_mut(),
}
.show(ui);
if let Some(id) = resp.clicked {
self.goto(id);
}
match resp.editor {
Some(EditorOutcome::Done) => self.commit_editor(),
Some(EditorOutcome::Cancel) => self.cancel_editor(),
None => {}
}
if let Some(slot) = resp.edit {
self.open_editor(slot);
}
if let Some(slot) = resp.delete {
self.delete_comment(slot, actions);
}
if let Some((id, nag)) = resp.nag {
self.toggle_nag_on(id, nag);
}
if let Some((id, shown)) = resp.best
&& let Some(mark) = self.review.analysis.marks.get(&id)
&& let Some(root) = self.game.position(mark.base)
@ -1379,15 +1673,23 @@ impl GameView {
{
self.flipped = !self.flipped;
}
// Not while a comment is being written: it would undo what stands under it.
let no_editor = self.editor.is_none();
if ui
.add_enabled(self.game.can_undo(), egui::Button::new(big("↩")))
.add_enabled(
self.game.can_undo() && no_editor,
egui::Button::new(big("↩")),
)
.on_hover_text(tr("Undo move/edit (Ctrl+Z)"))
.clicked()
{
self.undo();
}
if ui
.add_enabled(self.game.can_redo(), egui::Button::new(big("↪")))
.add_enabled(
self.game.can_redo() && no_editor,
egui::Button::new(big("↪")),
)
.on_hover_text(tr("Redo move/edit (Ctrl+Y)"))
.clicked()
{
@ -1410,6 +1712,15 @@ impl GameView {
actions.push(GameAction::AddToDatabase);
ui.close();
}
let comment = if self.cursor == NodeId::ROOT {
tr("Comment at the start of the game… (Enter)")
} else {
tr("Comment on the move… (Enter)")
};
if ui.button(comment).clicked() {
self.open_editor(Slot::After(self.cursor));
ui.close();
}
ui.separator();
if ui.button(tr("Copy PGN")).clicked() {
actions.push(self.copy_pgn());
@ -1584,6 +1895,37 @@ impl GameView {
}
}
/// Dev hook (`CP_SHAPE=Ge2e4,Rd5`): shapes drawn on the board at the current move.
pub fn debug_shapes(&mut self, spec: &str) {
for item in spec.split(',').map(str::trim).filter(|s| !s.is_empty()) {
let parsed = chess_core::parse_comment(&if item.len() > 3 {
format!("[%cal {item}]")
} else {
format!("[%csl {item}]")
});
for p in parsed {
match p {
CommentPart::Annotation(Annotation::Arrows(list)) => {
for (c, a, b) in list {
self.apply_shape(board::Drawn::Arrow(c, a, b));
}
}
CommentPart::Annotation(Annotation::Squares(list)) => {
for (c, sq) in list {
self.apply_shape(board::Drawn::Circle(c, sq));
}
}
_ => {}
}
}
}
}
/// 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));
}
/// Dev hook (`CP_COMMENT`): a comment after the current move.
pub fn debug_comment(&mut self, text: &str) {
let nags = self
@ -1643,6 +1985,7 @@ impl GameView {
}
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());
let mut cmds = Vec::new();
ui.input_mut(|i| {
if i.consume_shortcut(&ctrl_shift(Key::Z)) || i.consume_shortcut(&ctrl(Key::Y)) {
@ -1681,6 +2024,18 @@ impl GameView {
if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::ArrowUp)) {
cmds.push("prev_var");
}
for (key, cmd) in [
(Key::Num1, "nag1"),
(Key::Num2, "nag2"),
(Key::Num3, "nag3"),
(Key::Num4, "nag4"),
(Key::Num5, "nag5"),
(Key::Num6, "nag6"),
] {
if i.consume_shortcut(&ctrl(key)) {
cmds.push(cmd);
}
}
if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::ArrowDown)) {
cmds.push("next_var");
}
@ -1700,12 +2055,28 @@ impl GameView {
cmds.push(cmd);
}
}
// Taken: the Enter that closed a dialog this frame must not open the editor.
if i.key_pressed(Key::Enter) && !overlay {
i.consume_key(Modifiers::NONE, Key::Enter);
cmds.push("comment");
}
}
});
for cmd in cmds {
match cmd {
"undo" => self.undo(),
"redo" => self.redo(),
"undo" if self.editor.is_none() => self.undo(),
"redo" if self.editor.is_none() => self.redo(),
"comment" => {
if self.preview.is_none() {
self.open_editor(Slot::After(self.cursor));
}
}
"nag1" | "nag2" | "nag3" | "nag4" | "nag5" | "nag6" => {
if self.preview.is_none() {
let k: u8 = cmd[3..].parse().unwrap_or(1);
self.toggle_nag_on(self.cursor, Nag(k));
}
}
"copy" => actions.push(self.copy_pgn()),
"save" => actions.push(GameAction::Save),
"add_to_db" => actions.push(GameAction::AddToDatabase),

View file

@ -9857,6 +9857,348 @@ const ROWS: &[[&str; 9]] = &[
"“+ O‘yin” bo‘sh taxtani ochadi; Ctrl+S o‘yinni shu yerga qo‘shadi. Yoki istalgan o‘yinni oching va “Bazaga qo‘shish…” ni tanlang (Ctrl+Shift+S)",
"«+ Партия» бос тақтаны ашады; Ctrl+S партияны осында қосады. Немесе кез келген партияны ашып, «Базаға қосу…» таңдаңыз (Ctrl+Shift+S)",
],
// --- user comments ---
[
"Comment at the start of the game",
"Комментарий в начале партии",
"Commentaire au début de la partie",
"Kommentar zu Beginn der Partie",
"Comentario al inicio de la partida",
"Commento all’inizio della partita",
"Comentário no início da partida",
"Partiya boshidagi izoh",
"Партия басындағы түсініктеме",
],
[
"At the start",
"В начале партии",
"Au début de la partie",
"Zu Beginn der Partie",
"Al inicio de la partida",
"All’inizio della partita",
"No início da partida",
"Partiya boshida",
"Партия басында",
],
[
"Comment after {move}",
"Комментарий после {move}",
"Commentaire après {move}",
"Kommentar nach {move}",
"Comentario después de {move}",
"Commento dopo {move}",
"Comentário depois de {move}",
"{move} yurishidan keyingi izoh",
"{move} жүрісінен кейінгі түсініктеме",
],
[
"After {move}",
"После {move}",
"Après {move}",
"Nach {move}",
"Después de {move}",
"Dopo {move}",
"Depois de {move}",
"{move} yurishidan keyin",
"{move} жүрісінен кейін",
],
[
"Comment before {move}",
"Комментарий перед {move}",
"Commentaire avant {move}",
"Kommentar vor {move}",
"Comentario antes de {move}",
"Commento prima di {move}",
"Comentário antes de {move}",
"{move} yurishidan oldingi izoh",
"{move} жүрісінің алдындағы түсініктеме",
],
[
"Before {move}",
"Перед {move}",
"Avant {move}",
"Vor {move}",
"Antes de {move}",
"Prima di {move}",
"Antes de {move}",
"{move} yurishidan oldin",
"{move} жүрісінің алдында",
],
[
"Comment deleted (Ctrl+Z to undo)",
"Комментарий удалён (Ctrl+Z — вернуть)",
"Commentaire supprimé (Ctrl+Z pour annuler)",
"Kommentar gelöscht (Ctrl+Z zum Rückgängigmachen)",
"Comentario eliminado (Ctrl+Z para deshacer)",
"Commento eliminato (Ctrl+Z per annullare)",
"Comentário excluído (Ctrl+Z para desfazer)",
"Izoh o‘chirildi (bekor qilish: Ctrl+Z)",
"Түсініктеме жойылды (болдырмау — Ctrl+Z)",
],
[
"Comment at the start of the game… (Enter)",
"Комментарий в начале партии… (Enter)",
"Commentaire au début de la partie… (Enter)",
"Kommentar zu Beginn der Partie… (Enter)",
"Comentario al inicio de la partida… (Enter)",
"Commento all’inizio della partita… (Enter)",
"Comentário no início da partida… (Enter)",
"Partiya boshidagi izoh… (Enter)",
"Партия басындағы түсініктеме… (Enter)",
],
[
"Comment on the move… (Enter)",
"Комментарий к ходу… (Enter)",
"Commentaire sur le coup… (Enter)",
"Kommentar zum Zug… (Enter)",
"Comentario a la jugada… (Enter)",
"Commento alla mossa… (Enter)",
"Comentário ao lance… (Enter)",
"Yurishga izoh… (Enter)",
"Жүріске түсініктеме… (Enter)",
],
[
"Edit comment…",
"Изменить комментарий…",
"Modifier le commentaire…",
"Kommentar bearbeiten…",
"Editar comentario…",
"Modifica commento…",
"Editar comentário…",
"Izohni tahrirlash…",
"Түсініктемені өзгерту…",
],
[
"Comment…",
"Комментарий…",
"Commentaire…",
"Kommentar…",
"Comentario…",
"Commento…",
"Comentário…",
"Izoh…",
"Түсініктеме…",
],
[
"Delete comment",
"Удалить комментарий",
"Supprimer le commentaire",
"Kommentar löschen",
"Eliminar comentario",
"Elimina commento",
"Excluir comentário",
"Izohni o‘chirish",
"Түсініктемені жою",
],
[
"Comment at the start of the game…",
"Комментарий в начале партии…",
"Commentaire au début de la partie…",
"Kommentar zu Beginn der Partie…",
"Comentario al inicio de la partida…",
"Commento all’inizio della partita…",
"Comentário no início da partida…",
"Partiya boshidagi izoh…",
"Партия басындағы түсініктеме…",
],
[
"Cancel (Esc)",
"Отмена (Esc)",
"Annuler (Esc)",
"Abbrechen (Esc)",
"Cancelar (Esc)",
"Annulla (Esc)",
"Cancelar (Esc)",
"Bekor qilish (Esc)",
"Бас тарту (Esc)",
],
[
"Done (Enter)",
"Готово (Enter)",
"Terminé (Enter)",
"Fertig (Enter)",
"Listo (Enter)",
"Fatto (Enter)",
"Concluído (Enter)",
"Tayyor (Enter)",
"Дайын (Enter)",
],
[
"Position assessment",
"Оценка позиции",
"Évaluation de la position",
"Stellungsbewertung",
"Valoración de la posición",
"Valutazione della posizione",
"Avaliação da posição",
"Pozitsiya bahosi",
"Позицияны бағалау",
],
[
"Your comment…",
"Ваш комментарий…",
"Votre commentaire…",
"Ihr Kommentar…",
"Su comentario…",
"Il tuo commento…",
"Seu comentário…",
"Izohingiz…",
"Сіздің түсініктемеңіз…",
],
[
"Enter — done · Esc — cancel · Shift+Enter — new paragraph",
"Enter — готово · Esc — отмена · Shift+Enter — новый абзац",
"Enter — terminer · Esc — annuler · Shift+Enter — nouveau paragraphe",
"Enter — fertig · Esc — abbrechen · Shift+Enter — neuer Absatz",
"Enter — listo · Esc — cancelar · Shift+Enter — nuevo párrafo",
"Enter — fatto · Esc — annulla · Shift+Enter — nuovo paragrafo",
"Enter — concluir · Esc — cancelar · Shift+Enter — novo parágrafo",
"Enter — tayyor · Esc — bekor qilish · Shift+Enter — yangi xatboshi",
"Enter — дайын · Esc — бас тарту · Shift+Enter — жаңа абзац",
],
[
"⇄ You are editing the original; its translation will be dropped",
"⇄ Правится оригинал; перевод этого комментария пропадёт",
"⇄ Vous modifiez l’original ; sa traduction sera supprimée",
"⇄ Sie bearbeiten das Original; seine Übersetzung wird verworfen",
"⇄ Está editando el original; su traducción se descartará",
"⇄ Stai modificando l’originale; la sua traduzione verrà scartata",
"⇄ Você está editando o original; sua tradução será descartada",
"⇄ Siz aslini tahrirlayapsiz; uning tarjimasi o‘chiriladi",
"⇄ Сіз түпнұсқаны өңдеп жатырсыз; оның аудармасы жойылады",
],
[
"Good move",
"Хороший ход",
"Bon coup",
"Guter Zug",
"Buena jugada",
"Buona mossa",
"Bom lance",
"Yaxshi yurish",
"Жақсы жүріс",
],
[
"Brilliant move",
"Отличный ход",
"Coup brillant",
"Brillanter Zug",
"Jugada brillante",
"Mossa brillante",
"Lance brilhante",
"Ajoyib yurish",
"Тамаша жүріс",
],
[
"Interesting move",
"Интересный ход",
"Coup intéressant",
"Interessanter Zug",
"Jugada interesante",
"Mossa interessante",
"Lance interessante",
"Qiziqarli yurish",
"Қызықты жүріс",
],
[
"Dubious move",
"Сомнительный ход",
"Coup douteux",
"Zweifelhafter Zug",
"Jugada dudosa",
"Mossa dubbia",
"Lance duvidoso",
"Shubhali yurish",
"Күмәнді жүріс",
],
[
"Equal position",
"Равенство",
"Position égale",
"Ausgeglichene Stellung",
"Posición igualada",
"Posizione pari",
"Posição igual",
"Teng pozitsiya",
"Тең позиция",
],
[
"Unclear position",
"Неясно",
"Position peu claire",
"Unklare Stellung",
"Posición poco clara",
"Posizione poco chiara",
"Posição pouco clara",
"Noaniq pozitsiya",
"Анық емес позиция",
],
[
"White is slightly better",
"У белых чуть лучше",
"Les Blancs sont légèrement mieux",
"Weiß steht etwas besser",
"Las blancas están ligeramente mejor",
"Il Bianco sta leggermente meglio",
"As brancas estão ligeiramente melhor",
"Oqlar biroz yaxshiroq",
"Ақтардың жағдайы сәл жақсы",
],
[
"Black is slightly better",
"У чёрных чуть лучше",
"Les Noirs sont légèrement mieux",
"Schwarz steht etwas besser",
"Las negras están ligeramente mejor",
"Il Nero sta leggermente meglio",
"As pretas estão ligeiramente melhor",
"Qoralar biroz yaxshiroq",
"Қаралардың жағдайы сәл жақсы",
],
[
"White is better",
"У белых перевес",
"Les Blancs sont mieux",
"Weiß steht besser",
"Las blancas están mejor",
"Il Bianco sta meglio",
"As brancas estão melhor",
"Oqlar yaxshiroq",
"Ақтардың жағдайы жақсы",
],
[
"Black is better",
"У чёрных перевес",
"Les Noirs sont mieux",
"Schwarz steht besser",
"Las negras están mejor",
"Il Nero sta meglio",
"As pretas estão melhor",
"Qoralar yaxshiroq",
"Қаралардың жағдайы жақсы",
],
[
"White is winning",
"Белые выигрывают",
"Les Blancs gagnent",
"Weiß steht auf Gewinn",
"Las blancas ganan",
"Il Bianco vince",
"As brancas estão ganhando",
"Oqlar yutmoqda",
"Ақтар ұтып жатыр",
],
[
"Black is winning",
"Чёрные выигрывают",
"Les Noirs gagnent",
"Schwarz steht auf Gewinn",
"Las negras ganan",
"Il Nero vince",
"As pretas estão ganhando",
"Qoralar yutmoqda",
"Қаралар ұтып жатыр",
],
];
#[cfg(test)]

View file

@ -20,6 +20,8 @@ pub struct Notation<'a> {
pub preview: Option<(NodeId, &'a [String], usize)>,
/// Translated comments by their original text (none: the original is shown).
pub translations: Option<&'a HashMap<String, Translated>>,
/// The comment being written, drawn where the comment stands (user-comments.md §3).
pub editor: Option<&'a mut CommentEditor>,
}
/// Result of a frame of the notation panel.
@ -29,6 +31,14 @@ pub struct NotationResponse {
pub context: Option<(NodeId, NotationCommand)>,
/// A move of the better line of this marked move was clicked: (marked node, moves to show).
pub best: Option<(NodeId, usize)>,
/// Open the editor for this comment (a double click, the menu).
pub edit: Option<Slot>,
/// Delete this comment (the menu).
pub delete: Option<Slot>,
/// Put or take off this symbol on this move (the menu), at once.
pub nag: Option<(NodeId, Nag)>,
/// The editor's «Done» or «Cancel».
pub editor: Option<EditorOutcome>,
}
#[derive(Clone, Copy, Debug)]
@ -37,6 +47,121 @@ pub enum NotationCommand {
Delete,
}
/// Which comment of the game: after a move (`After(ROOT)`: the start of the game), or
/// before a move (an introduction to a line, only an existing one).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Slot {
After(NodeId),
Before(NodeId),
}
impl Slot {
pub fn node(self) -> NodeId {
match self {
Slot::After(id) | Slot::Before(id) => id,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EditorOutcome {
Done,
Cancel,
}
/// A comment being written: its draft text and symbols (user-comments.md §3.4).
pub struct CommentEditor {
pub slot: Slot,
pub text: String,
/// The text as the editor opened (unchanged: the comment's bytes stay).
pub initial: String,
/// The draft symbols of the move (all of them; the two groups are toggled).
pub nags: Vec<Nag>,
pub initial_nags: Vec<Nag>,
/// «Comment after 4…Nf6», and its short form for a narrow panel.
pub title: String,
pub short_title: String,
/// A translation of this comment was on the screen: the original is edited.
pub translated: bool,
/// Put the keyboard into the field (on opening, on Enter from the game).
pub focus: bool,
/// Scroll the editor into view (on opening).
pub scroll: bool,
/// The text field's id, to know whether it has the keyboard.
pub field_id: Option<egui::Id>,
}
impl CommentEditor {
/// Something to write: the text or the symbols changed.
pub fn changed(&self) -> bool {
self.text.trim() != self.initial.trim() || self.nags != self.initial_nags
}
pub fn text_changed(&self) -> bool {
self.text.trim() != self.initial.trim()
}
}
/// The six symbols of a move and the eight of a position, as the editor and the move's
/// menu offer them (user-comments.md §3.4): (NAG, symbol, name).
pub const MOVE_NAGS: [(Nag, &str, &str); 6] = [
(Nag(1), "!", "Good move"),
(Nag(2), "?", "Mistake"),
(Nag(3), "!!", "Brilliant move"),
(Nag(4), "??", "Blunder"),
(Nag(5), "!?", "Interesting move"),
(Nag(6), "?!", "Dubious move"),
];
pub const POSITION_NAGS: [(Nag, &str, &str); 8] = [
(Nag(10), "=", "Equal position"),
(Nag(13), "∞", "Unclear position"),
(Nag(14), "⩲", "White is slightly better"),
(Nag(15), "⩱", "Black is slightly better"),
(Nag(16), "±", "White is better"),
(Nag(17), "∓", "Black is better"),
(Nag(18), "+−", "White is winning"),
(Nag(19), "−+", "Black is winning"),
];
fn is_position_nag(n: Nag) -> bool {
(10..=19).contains(&n.0)
}
/// `nag` put on or taken off `nags`: one symbol of its group (move or position) at a
/// time; the same symbol again takes it off; the other symbols stay.
pub fn toggle_nag(nags: &[Nag], nag: Nag) -> Vec<Nag> {
let same_group = |n: &Nag| {
if nag.is_move_assessment() {
n.is_move_assessment()
} else {
is_position_nag(*n)
}
};
let had = nags
.iter()
.any(|n| *n == nag || (n.0 >= 10 && n.0 <= 12 && nag.0 == 10));
let mut out: Vec<Nag> = nags.iter().copied().filter(|n| !same_group(n)).collect();
if !had {
out.push(nag);
out.sort();
}
out
}
/// The symbol of a group that is on: `=` for $10–$12.
fn group_current(nags: &[Nag], position: bool) -> Option<Nag> {
nags.iter()
.copied()
.find(|n| {
if position {
is_position_nag(*n)
} else {
n.is_move_assessment()
}
})
.map(|n| if (10..=12).contains(&n.0) { Nag(10) } else { n })
}
const ROW_H: f32 = 26.0;
const NUM_W: f32 = 38.0;
/// A move's cell is no wider than this: in a wide panel (the notation under the board)
@ -46,16 +171,26 @@ const CELL_MAX: f32 = 160.0;
const MARK_LINE_MOVES: usize = 6;
impl Notation<'_> {
pub fn show(self, ui: &mut Ui) -> NotationResponse {
pub fn show(mut self, ui: &mut Ui) -> NotationResponse {
let mut out = NotationResponse::default();
let mut editor = self.editor.take();
let game = self.game;
let editing = editor.as_ref().map(|e| e.slot);
let root_comments = comment_text(
game.node(NodeId::ROOT)
.map(|n| n.comments_after())
.unwrap_or(&[]),
);
if !root_comments.is_empty() {
comment_block(ui, &self, &root_comments);
if editing == Some(Slot::After(NodeId::ROOT)) {
editor_block(ui, &mut editor, &mut out);
} else if !root_comments.is_empty() {
comment_block(
ui,
&self,
&root_comments,
Slot::After(NodeId::ROOT),
&mut out,
);
}
let mut row = Row::default();
@ -63,9 +198,12 @@ impl Notation<'_> {
while let Some(child) = game.main_child(node) {
let Some(n) = game.node(child) else { break };
let before = comment_text(n.comments_before());
if !before.is_empty() {
if editing == Some(Slot::Before(child)) {
row.flush(ui, &self, &mut out);
comment_block(ui, &self, &before);
editor_block(ui, &mut editor, &mut out);
} else if !before.is_empty() {
row.flush(ui, &self, &mut out);
comment_block(ui, &self, &before, Slot::Before(child), &mut out);
}
let (num, color) = game.move_number(child).unwrap_or((0, Color::White));
if color == Color::White {
@ -81,21 +219,27 @@ impl Notation<'_> {
let after = comment_text(n.comments_after());
let vars = game.variations(node);
let mark = self.marks.and_then(|m| m.get(&child));
let interrupted =
!after.is_empty() || !vars.is_empty() || !n.unparsed().is_empty() || mark.is_some();
let editing_after = editing == Some(Slot::After(child));
let interrupted = editing_after
|| !after.is_empty()
|| !vars.is_empty()
|| !n.unparsed().is_empty()
|| mark.is_some();
if interrupted || color == Color::Black {
row.flush(ui, &self, &mut out);
if let Some(mark) = mark {
mark_block(ui, &self, child, mark, &mut out);
}
if !after.is_empty() {
comment_block(ui, &self, &after);
if editing_after {
editor_block(ui, &mut editor, &mut out);
} else if !after.is_empty() {
comment_block(ui, &self, &after, Slot::After(child), &mut out);
}
for u in n.unparsed() {
unparsed_block(ui, u);
}
for &v in vars {
variation_block(ui, &self, v, &mut out);
variation_block(ui, &self, v, &mut editor, &mut out);
}
}
node = child;
@ -182,7 +326,45 @@ fn handle_move_response(
resp.scroll_to_me(Some(egui::Align::Center));
}
let is_variation = n.game.child_index(id).is_some_and(|i| i > 0) || !n.game.is_mainline(id);
// The menu is about the move it opens on: the move becomes the current one.
if resp.secondary_clicked() && id != n.cursor {
out.clicked = Some(id);
}
resp.context_menu(|ui| {
let node = n.game.node(id);
let has_comment = node.is_some_and(|nd| !comment_text(nd.comments_after()).is_empty());
let label = if has_comment {
tr("Edit comment…")
} else {
tr("Comment…")
};
if ui
.add(egui::Button::new(label).shortcut_text("Enter"))
.clicked()
{
out.edit = Some(Slot::After(id));
ui.close();
}
if has_comment && ui.button(tr("Delete comment")).clicked() {
out.delete = Some(Slot::After(id));
ui.close();
}
// The symbols act at once and keep the menu open: «?» off, «?!» on.
let nags = node.map(|nd| nd.nags().to_vec()).unwrap_or_default();
symbol_row(ui, &nags, &MOVE_NAGS, true, &mut |nag| {
out.nag = Some((id, nag))
});
symbol_row(ui, &nags, &POSITION_NAGS, false, &mut |nag| {
out.nag = Some((id, nag))
});
if n.game.main_child(NodeId::ROOT) == Some(id) {
ui.separator();
if ui.button(tr("Comment at the start of the game…")).clicked() {
out.edit = Some(Slot::After(NodeId::ROOT));
ui.close();
}
}
ui.separator();
if is_variation && ui.button(tr("Make main line")).clicked() {
out.context = Some((id, NotationCommand::Promote));
ui.close();
@ -195,6 +377,44 @@ fn handle_move_response(
let _ = ui;
}
/// A row of symbol toggles: the one on is pressed; `on` gets the symbol clicked.
fn symbol_row(
ui: &mut Ui,
nags: &[Nag],
set: &[(Nag, &str, &'static str)],
moves: bool,
on: &mut dyn FnMut(Nag),
) {
let current = group_current(nags, !moves);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 2.0;
for (nag, sym, name) in set {
let mut text = RichText::new(*sym).size(15.0);
if moves && let Some(c) = assessment_color(*nag) {
text = text.color(c);
}
let r = ui
.add_sized(
[28.0, 24.0],
egui::Button::selectable(current == Some(*nag), text),
)
.on_hover_text(symbol_hint(*nag, name));
if r.clicked() {
on(*nag);
}
}
});
}
/// «Good move (Ctrl+1)».
fn symbol_hint(nag: Nag, name: &'static str) -> String {
if nag.is_move_assessment() {
format!("{} (Ctrl+{})", tr(name), nag.0)
} else {
tr(name).to_owned()
}
}
fn paint_move_cell(
ui: &Ui,
cell: egui::Rect,
@ -457,7 +677,7 @@ fn mark_info(
/// Room kept on the right of a comment for its translation mark.
const MARK_ROOM: f32 = 18.0;
fn comment_block(ui: &mut Ui, n: &Notation, text: &str) {
fn comment_block(ui: &mut Ui, n: &Notation, text: &str, slot: Slot, out: &mut NotationResponse) {
let (shown, mark) = translated(n, text);
let mut frame = block_frame(ui);
if mark.is_some() {
@ -468,16 +688,190 @@ fn comment_block(ui: &mut Ui, n: &Notation, text: &str) {
bottom: 6,
});
}
let hovered = ui.rect_contains_pointer(ui.available_rect_before_wrap());
let r = frame.show(ui, |ui| {
ui.set_width(ui.available_width());
ui.label(RichText::new(shown).color(comment_color(ui)).size(14.5));
let resp = ui.add(
egui::Label::new(RichText::new(shown).color(comment_color(ui)).size(14.5))
.sense(Sense::click()),
);
comment_response(&resp, slot, out);
});
let _ = hovered;
if let Some(m) = mark {
let at = r.response.rect.right_top() + vec2(-8.0, 7.0);
translation_mark(ui, at, m, text);
}
}
/// A double click opens the comment for editing; the right button offers that and
/// deleting (user-comments.md §5.2).
fn comment_response(resp: &egui::Response, slot: Slot, out: &mut NotationResponse) {
if resp.hovered() {
resp.ctx.set_cursor_icon(egui::CursorIcon::Text);
}
if resp.double_clicked() {
out.edit = Some(slot);
}
resp.context_menu(|ui| {
if ui.button(tr("Edit comment…")).clicked() {
out.edit = Some(slot);
ui.close();
}
if ui.button(tr("Delete comment")).clicked() {
out.delete = Some(slot);
ui.close();
}
});
}
/// The comment editor on the spot of its comment (user-comments.md §3.4).
fn editor_block(ui: &mut Ui, editor: &mut Option<&mut CommentEditor>, out: &mut NotationResponse) {
let Some(ed) = editor.as_deref_mut() else {
return;
};
let focused = ed
.field_id
.is_some_and(|id| ui.ctx().memory(|m| m.focused() == Some(id)));
let sel = ui.visuals().selection;
let stroke = if focused {
Stroke::new(1.5, sel.stroke.color)
} else {
Stroke::new(1.0, ui.visuals().weak_text_color())
};
let width = ui.available_width();
let narrow = width < 360.0;
let r = egui::Frame::new()
.fill(ui.visuals().extreme_bg_color)
.inner_margin(egui::Margin::symmetric(10, 6))
.stroke(stroke)
.show(ui, |ui| {
ui.set_width(ui.available_width());
// The title and the buttons.
ui.horizontal(|ui| {
let buttons = if narrow { 2.0 * 30.0 } else { 150.0 };
let room = ui.available_width() - buttons;
let title = if narrow
|| crate::game_view::text_width(ui, &ed.title, egui::TextStyle::Body) > room
{
&ed.short_title
} else {
&ed.title
};
ui.add(egui::Label::new(RichText::new(title).strong()).truncate());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if narrow {
if ui.button("×").on_hover_text(tr("Cancel (Esc)")).clicked() {
out.editor = Some(EditorOutcome::Cancel);
}
if crate::widgets::primary(ui, "✔")
.on_hover_text(tr("Done (Enter)"))
.clicked()
{
out.editor = Some(EditorOutcome::Done);
}
} else {
if ui.button(tr("Cancel")).on_hover_text("Esc").clicked() {
out.editor = Some(EditorOutcome::Cancel);
}
if crate::widgets::primary(ui, tr("Done"))
.on_hover_text("Enter")
.clicked()
{
out.editor = Some(EditorOutcome::Done);
}
}
});
});
// The symbols: the move's six, then the position's eight (a «±▾» menu when
// they do not fit on the line). Not for the start of the game.
if ed.slot != Slot::After(NodeId::ROOT) && !matches!(ed.slot, Slot::Before(_)) {
let both = 14.0 * 30.0 + 24.0 <= ui.available_width();
ui.horizontal(|ui| {
let mut toggled = None;
symbol_row(ui, &ed.nags, &MOVE_NAGS, true, &mut |nag| {
toggled = Some(nag)
});
if both {
ui.separator();
symbol_row(ui, &ed.nags, &POSITION_NAGS, false, &mut |nag| {
toggled = Some(nag)
});
} else {
let current = group_current(&ed.nags, true)
.and_then(|n| n.symbol())
.unwrap_or("±");
ui.menu_button(format!("{current}▾"), |ui| {
symbol_row(ui, &ed.nags, &POSITION_NAGS[..4], false, &mut |nag| {
toggled = Some(nag)
});
symbol_row(ui, &ed.nags, &POSITION_NAGS[4..], false, &mut |nag| {
toggled = Some(nag)
});
})
.response
.on_hover_text(tr("Position assessment"));
}
if let Some(nag) = toggled {
ed.nags = toggle_nag(&ed.nags, nag);
}
});
}
// The text: 2 to 12 lines, then it scrolls inside.
let color = comment_color(ui);
let row_h = ui.fonts_mut(|f| f.row_height(&FontId::proportional(14.5)));
let resp = egui::ScrollArea::vertical()
.id_salt("comment_editor_scroll")
.max_height(12.0 * row_h + 8.0)
.auto_shrink([false, true])
.show(ui, |ui| {
ui.add(
egui::TextEdit::multiline(&mut ed.text)
.id_salt("comment_editor")
.desired_rows(2)
.desired_width(f32::INFINITY)
.font(FontId::proportional(14.5))
.text_color(color)
.hint_text(tr("Your comment…")),
)
})
.inner;
ed.field_id = Some(resp.id);
if std::mem::take(&mut ed.focus) {
resp.request_focus();
// The cursor at the end: one adds to a comment more often than replaces it.
if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), resp.id) {
let end = egui::text::CCursor::new(ed.text.chars().count());
state
.cursor
.set_char_range(Some(egui::text::CCursorRange::one(end)));
state.store(ui.ctx(), resp.id);
}
}
if !narrow {
ui.label(
RichText::new(tr(
"Enter — done · Esc — cancel · Shift+Enter — new paragraph",
))
.weak()
.small(),
);
}
if ed.translated {
ui.label(
RichText::new(tr(
"⇄ You are editing the original; its translation will be dropped",
))
.weak()
.small(),
);
}
});
if std::mem::take(&mut ed.scroll) {
r.response.scroll_to_me(None);
}
}
fn unparsed_block(ui: &mut Ui, text: &str) {
block_frame(ui).show(ui, |ui| {
ui.set_width(ui.available_width());
@ -498,18 +892,125 @@ fn comment_color(ui: &Ui) -> Color32 {
}
}
fn variation_block(ui: &mut Ui, n: &Notation, start: NodeId, out: &mut NotationResponse) {
/// One piece of a variation's flowing text.
enum Token {
Move {
id: NodeId,
label: String,
color: Option<Color32>,
},
Comment {
slot: Slot,
text: String,
},
Unparsed(String),
Open,
Close,
}
fn variation_block(
ui: &mut Ui,
n: &Notation,
start: NodeId,
editor: &mut Option<&mut CommentEditor>,
out: &mut NotationResponse,
) {
let mut tokens = Vec::new();
line_tokens(n, start, &mut tokens);
let editing = editor.as_ref().map(|e| e.slot);
// The flow is cut where the editor stands: after the move for «after», before it
// for «before»; a comment being edited is replaced by the editor.
let cut = editing.and_then(|slot| {
tokens
.iter()
.position(|t| matches!(t, Token::Comment { slot: s, .. } if *s == slot))
.map(|i| (i, true))
.or_else(|| match slot {
Slot::After(id) => tokens
.iter()
.position(|t| matches!(t, Token::Move { id: m, .. } if *m == id))
.map(|i| (i + 1, false)),
Slot::Before(id) => tokens
.iter()
.position(|t| matches!(t, Token::Move { id: m, .. } if *m == id))
.map(|i| (i, false)),
})
});
block_frame(ui).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(3.0, 2.0);
inline_line(ui, n, start, out);
});
match cut {
None => flow(ui, n, &tokens, out),
Some((at, replaces)) => {
flow(ui, n, &tokens[..at], out);
editor_block(ui, editor, out);
let rest = if replaces { at + 1 } else { at };
flow(ui, n, &tokens[rest..], out);
}
}
});
}
/// Renders a line starting at `first` (a variation move) as flowing text.
fn inline_line(ui: &mut Ui, n: &Notation, first: NodeId, out: &mut NotationResponse) {
/// Lays out tokens as flowing text.
fn flow(ui: &mut Ui, n: &Notation, tokens: &[Token], out: &mut NotationResponse) {
if tokens.is_empty() {
return;
}
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(3.0, 2.0);
for t in tokens {
match t {
Token::Move { id, label, color } => {
let current = *id == n.cursor;
let mut text = RichText::new(label).size(15.0);
if let Some(c) = color
&& !current
{
text = text.color(*c);
}
// Same strong highlight as the main-line table, so the current move is
// visible inside text.
let button = if current {
let sel = ui.visuals().selection;
egui::Button::new(text.color(sel.stroke.color).strong())
.fill(sel.bg_fill)
.stroke(egui::Stroke::new(1.0, sel.stroke.color))
} else {
egui::Button::new(text).frame_when_inactive(false)
};
let resp = ui.add(button);
handle_move_response(ui, &resp, n, *id, out);
}
Token::Comment { slot, text } => {
let (shown, mark) = translated(n, text);
let resp = ui.add(
egui::Label::new(RichText::new(shown).color(comment_color(ui)).size(14.5))
.sense(Sense::click()),
);
comment_response(&resp, *slot, out);
if let Some(m) = mark {
inline_mark(ui, m, text);
}
}
Token::Unparsed(u) => {
ui.label(
RichText::new(u)
.monospace()
.color(ui.visuals().warn_fg_color),
);
}
Token::Open => {
ui.label(RichText::new("(").weak());
}
Token::Close => {
ui.label(RichText::new(")").weak());
}
}
}
});
}
/// The tokens of a line starting at `first` (a variation move), nested lines inside.
fn line_tokens(n: &Notation, first: NodeId, tokens: &mut Vec<Token>) {
let game = n.game;
let mut node = first;
let mut need_number = true;
@ -517,11 +1018,10 @@ fn inline_line(ui: &mut Ui, n: &Notation, first: NodeId, out: &mut NotationRespo
let Some(nd) = game.node(node) else { return };
let before = comment_text(nd.comments_before());
if !before.is_empty() {
let (shown, mark) = translated(n, &before);
ui.label(RichText::new(shown).color(comment_color(ui)).size(14.5));
if let Some(m) = mark {
inline_mark(ui, m, &before);
}
tokens.push(Token::Comment {
slot: Slot::Before(node),
text: before,
});
need_number = true;
}
let (num, color) = game.move_number(node).unwrap_or((0, Color::White));
@ -534,40 +1034,21 @@ fn inline_line(ui: &mut Ui, n: &Notation, first: NodeId, out: &mut NotationRespo
(Color::Black, false) => format!("{san}{sym}"),
};
need_number = false;
let current = node == n.cursor;
let mut text = RichText::new(label).size(15.0);
if let Some(c) = sym_color
&& !current
{
text = text.color(c);
}
// Same strong highlight as the main-line table, so the current move is visible inside text.
let button = if current {
let sel = ui.visuals().selection;
egui::Button::new(text.color(sel.stroke.color).strong())
.fill(sel.bg_fill)
.stroke(egui::Stroke::new(1.0, sel.stroke.color))
} else {
egui::Button::new(text).frame_when_inactive(false)
};
let resp = ui.add(button);
handle_move_response(ui, &resp, n, node, out);
tokens.push(Token::Move {
id: node,
label,
color: sym_color,
});
let after = comment_text(nd.comments_after());
if !after.is_empty() {
let (shown, mark) = translated(n, &after);
ui.label(RichText::new(shown).color(comment_color(ui)).size(14.5));
if let Some(m) = mark {
inline_mark(ui, m, &after);
}
tokens.push(Token::Comment {
slot: Slot::After(node),
text: after,
});
need_number = true;
}
for u in nd.unparsed() {
ui.label(
RichText::new(u)
.monospace()
.color(ui.visuals().warn_fg_color),
);
tokens.push(Token::Unparsed(u.clone()));
}
// Alternatives to this move are printed right after it (PGN order),
// except for the line's own first move whose siblings belong to the outer level.
@ -575,9 +1056,9 @@ fn inline_line(ui: &mut Ui, n: &Notation, first: NodeId, out: &mut NotationRespo
&& let Some(parent) = game.parent(node)
{
for &v in game.variations(parent) {
ui.label(RichText::new("(").weak());
inline_line(ui, n, v, out);
ui.label(RichText::new(")").weak());
tokens.push(Token::Open);
line_tokens(n, v, tokens);
tokens.push(Token::Close);
need_number = true;
}
}