From d251b54fe40f6f8f95261b4df65bced2fb728c63 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 1 Nov 2026 19:00:04 +0100 Subject: v4.0.6: move the prompt editor and key mapping out of the core --- src/bin/client/repl.rs | 37 +++++++-- src/client/core.rs | 208 ++----------------------------------------------- src/client/input.rs | 183 +++++++++++++++++++++++++++++++++++++++++++ src/client/mod.rs | 1 + 4 files changed, 221 insertions(+), 208 deletions(-) create mode 100644 src/client/input.rs (limited to 'src') diff --git a/src/bin/client/repl.rs b/src/bin/client/repl.rs index c13fc58..bc4238d 100644 --- a/src/bin/client/repl.rs +++ b/src/bin/client/repl.rs @@ -13,7 +13,8 @@ use crossterm::{ use sha2::{Digest, Sha256}; -use zagan_bet::client::core::{ClientCore, Effect, InteractiveCommand, Key}; +use zagan_bet::client::core::{ClientCore, Effect, InteractiveCommand}; +use zagan_bet::client::input::{game_input, GameInput, Input, Key, Editor}; use zagan_bet::client::database; use zagan_bet::client::ui::{ display_width, format_pong, host_lines, input_cursor_column, lines_to_move_up, @@ -30,6 +31,7 @@ pub struct ClientState { pub addr: Option, pub default_port: u16, core: ClientCore, + editor: Editor, cleanup_done: Arc>, /// Number of visual terminal lines currently occupied by the game board. game_lines: usize, @@ -59,6 +61,7 @@ impl ClientState { addr, default_port, core: ClientCore::new(), + editor: Editor::new(), cleanup_done: Arc::new(Mutex::new(false)), game_lines: 0, prompt_text: String::new(), @@ -112,9 +115,29 @@ impl ClientState { Event::Key(key) => { if key.kind == KeyEventKind::Press { if let Some(key) = map_key(key) { - let effects = self.core.handle_key(key); + let effects = if self.core.is_in_game() { + match game_input( + self.core.current_game_type().unwrap_or(""), + key, + ) { + GameInput::Quit => vec![Effect::Quit], + GameInput::Command(command) => { + self.core.command(command) + } + GameInput::None => Vec::new(), + } + } else { + match self.editor.handle(key) { + Input::Quit => vec![Effect::Quit], + Input::Submit(line) => self.core.submit_line(&line), + Input::Print(lines) => vec![Effect::Print(lines)], + Input::Prompt | Input::None => Vec::new(), + } + }; quit = self.apply_effects(effects); - self.apply_prompt(); + if !quit { + self.apply_prompt(); + } } } } @@ -222,7 +245,6 @@ impl ClientState { } } Effect::ClearRegion => self.clear_region(), - Effect::SetPrompt { text, cursor_col } => self.draw_prompt(&text, cursor_col), Effect::SendLine(line) => { let is_ping = line == "PING"; let started = Instant::now(); @@ -293,9 +315,12 @@ impl ClientState { } fn apply_prompt(&mut self) { - if let Some(prompt) = self.core.prompt_effect() { - let _ = self.apply_effects(vec![prompt]); + if self.core.is_in_game() { + return; } + let text = self.editor.input().to_string(); + let column = self.editor.cursor_column(); + self.draw_prompt(&text, column); } /// Leave the command currently on the prompt line visible in the diff --git a/src/client/core.rs b/src/client/core.rs index 98f109f..280eb77 100644 --- a/src/client/core.rs +++ b/src/client/core.rs @@ -3,32 +3,15 @@ use crate::client::games::response::{ parse_blackjack_response, parse_crash_response, parse_history_response, parse_roulette_response, parse_spin_response, }; -use crate::client::games::roulette::Direction; use crate::client::view::{ BlackjackView, Command, CrashView, HistoryView, LobbyView, RouletteView, SlotsView, View, }; -use crate::client::ui::{ - command_names, completion_lines, display_width, help_lines, history_lines, - input_cursor_column, parse_bet_arg, record_history, -}; +use crate::client::ui::{help_lines, history_lines, parse_bet_arg}; use crate::crash::{CrashState, multiplier_at}; use crate::history::{PlayRecord, MAX_HISTORY}; use crate::roulette::{BetTarget, Bets}; use std::time::{Duration, Instant}; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Key { - Char(char), - Enter, - Backspace, - Up, - Down, - Left, - Right, - Tab, - Esc, - CtrlC, -} #[derive(Debug, Clone, PartialEq, Eq)] pub enum InteractiveCommand { @@ -50,8 +33,6 @@ pub enum Effect { AnimateRoulette { winning: u8, view: View }, /// Remove the game board region. ClearRegion, - /// Redraw the command prompt. `text` is the input without the `> ` prefix. - SetPrompt { text: String, cursor_col: u16 }, /// Send one protocol line and feed the reply to `handle_reply`. SendLine(String), /// Delegate an interactive prompt flow to the terminal adapter. @@ -91,9 +72,6 @@ enum Screen { } pub struct ClientCore { - input: String, - history: Vec, - history_index: usize, game: GameManager, connected: bool, logged_in: Option, @@ -114,9 +92,6 @@ pub struct ClientCore { impl ClientCore { pub fn new() -> Self { Self { - input: String::new(), - history: Vec::new(), - history_index: 0, game: GameManager::new(), connected: false, logged_in: None, @@ -184,40 +159,6 @@ impl ClientCore { self.board_effects() } - pub fn prompt_effect(&self) -> Option { - if self.is_in_game() { - return None; - } - Some(Effect::SetPrompt { - text: self.input.clone(), - cursor_col: input_cursor_column(2, display_width(&self.input)), - }) - } - - pub fn handle_key(&mut self, key: Key) -> Vec { - if self.game.is_in_game() { - return self.handle_game_key(key); - } - - match key { - Key::CtrlC => vec![Effect::Quit], - Key::Enter => self.submit(), - Key::Backspace => { - self.input.pop(); - self.prompt_effects() - } - Key::Char(c) => { - self.input.push(c); - self.prompt_effects() - } - Key::Up => self.history_previous(), - Key::Down => self.history_next(), - Key::Left | Key::Right => Vec::new(), - Key::Tab => self.complete(), - Key::Esc => Vec::new(), - } - } - pub fn handle_reply(&mut self, reply: &str) -> Vec { match self.pending.take() { Some(Pending::Spin) => match parse_spin_response(reply) { @@ -370,31 +311,6 @@ impl ClientCore { } } - fn handle_game_key(&mut self, key: Key) -> Vec { - let game_type = self - .game - .get_current_state() - .map(|state| state.game_type.as_str()); - if game_type == Some("roulette") { - return self.handle_roulette_key(key); - } - if game_type == Some("blackjack") { - return self.handle_blackjack_key(key); - } - if game_type == Some("crash") { - return self.handle_crash_key(key); - } - - match key { - Key::CtrlC => vec![Effect::Quit], - Key::Esc | Key::Char('q') => self.command(Command::Leave), - Key::Char(' ') => self.command(Command::Spin), - Key::Char('+') | Key::Char('=') => self.command(Command::AdjustBet(10)), - Key::Char('-') => self.command(Command::AdjustBet(-10)), - _ => Vec::new(), - } - } - fn spin(&mut self) -> Vec { let Some(request) = self.game.spin_request() else { return Vec::new(); @@ -409,23 +325,6 @@ impl ClientCore { effects } - fn handle_roulette_key(&mut self, key: Key) -> Vec { - match key { - Key::CtrlC => vec![Effect::Quit], - Key::Up => self.command(Command::MoveCursor(Direction::Up)), - Key::Down => self.command(Command::MoveCursor(Direction::Down)), - Key::Left => self.command(Command::MoveCursor(Direction::Left)), - Key::Right => self.command(Command::MoveCursor(Direction::Right)), - Key::Enter => self.command(Command::PlaceBet), - Key::Char(' ') => self.command(Command::Spin), - Key::Char('c') => self.command(Command::ClearBets), - Key::Char('+') | Key::Char('=') => self.command(Command::AdjustChip(10)), - Key::Char('-') => self.command(Command::AdjustChip(-10)), - Key::Char('q') => self.command(Command::Leave), - _ => Vec::new(), - } - } - /// Apply a semantic command. Both frontends drive the core through this. pub fn command(&mut self, command: Command) -> Vec { let game = self.current_game_type().map(str::to_string); @@ -523,7 +422,7 @@ impl ClientCore { } } - fn current_game_type(&self) -> Option<&str> { + pub fn current_game_type(&self) -> Option<&str> { self.game .get_current_state() .map(|state| state.game_type.as_str()) @@ -628,36 +527,6 @@ impl ClientCore { effects } - fn handle_blackjack_key(&mut self, key: Key) -> Vec { - let status = self - .game - .get_current_state() - .and_then(|state| state.data.get("status")) - .cloned() - .unwrap_or_else(|| "ready".to_string()); - let hand = self.game.blackjack_state(); - let player = hand.as_ref().is_some_and(|hand| hand.phase == "player"); - let can_double = hand.as_ref().is_some_and(|hand| { - hand.phase == "player" && hand.actions.iter().any(|action| action == "double") - }); - - match key { - Key::CtrlC => vec![Effect::Quit], - Key::Char('q') => self.command(Command::Leave), - Key::Char(' ') => self.command(Command::Deal), - Key::Char('h') if player => self.command(Command::Hit), - Key::Char('s') if player => self.command(Command::Stand), - Key::Char('d') if can_double => self.command(Command::Double), - Key::Char('+') | Key::Char('=') if matches!(status.as_str(), "ready" | "done") => { - self.command(Command::AdjustBet(10)) - } - Key::Char('-') if matches!(status.as_str(), "ready" | "done") => { - self.command(Command::AdjustBet(-10)) - } - _ => Vec::new(), - } - } - fn start_blackjack(&mut self) -> Vec { let status = self .game @@ -768,25 +637,6 @@ impl ClientCore { self.board_effects() } - fn handle_crash_key(&mut self, key: Key) -> Vec { - let status = self.game.crash_status(); - let running = status == "running"; - - match key { - Key::CtrlC => vec![Effect::Quit], - Key::Char('q') => self.command(Command::Leave), - Key::Char(' ') if !running && self.pending.is_none() => self.command(Command::Start), - Key::Char('c') if running && self.pending.is_none() => { - self.command(Command::CashOut) - } - Key::Char('+') | Key::Char('=') if !running => { - self.command(Command::AdjustBet(10)) - } - Key::Char('-') if !running => self.command(Command::AdjustBet(-10)), - _ => Vec::new(), - } - } - fn start_crash(&mut self) -> Vec { let status = self.game.crash_status(); if !matches!(status.as_str(), "ready" | "cashed" | "crashed" | "forfeit") { @@ -822,16 +672,14 @@ impl ClientCore { vec![Effect::SendLine(format!("CRASH_CASHOUT {session}"))] } - fn submit(&mut self) -> Vec { - let line = self.input.trim().to_string(); - self.input.clear(); + /// Run one command line. The interactive frontend owns the buffer and the + /// history; the core only sees the finished line. + pub fn submit_line(&mut self, line: &str) -> Vec { + let line = line.trim().to_string(); if line.is_empty() { return Vec::new(); } - record_history(&mut self.history, &line); - self.history_index = self.history.len(); - let parts: Vec<&str> = line.splitn(3, ' ').collect(); match parts[0] { "play" => self.cmd_play(&parts), @@ -1047,47 +895,6 @@ impl ClientCore { effects } - fn history_previous(&mut self) -> Vec { - if self.history_index == 0 { - return Vec::new(); - } - self.history_index -= 1; - self.input = self.history[self.history_index].clone(); - self.prompt_effects() - } - - fn history_next(&mut self) -> Vec { - if self.history_index >= self.history.len() { - return Vec::new(); - } - self.history_index += 1; - self.input = if self.history_index == self.history.len() { - String::new() - } else { - self.history[self.history_index].clone() - }; - self.prompt_effects() - } - - fn complete(&mut self) -> Vec { - let prefix = self.input.trim(); - let matches: Vec<&'static str> = command_names() - .into_iter() - .filter(|command| command.starts_with(prefix)) - .collect(); - - let mut effects = Vec::new(); - if matches.len() == 1 { - self.input = matches[0].to_string(); - } else if matches.len() > 1 { - effects.push(Effect::Print(completion_lines(&matches, 76))); - } - if let Some(prompt) = self.prompt_effect() { - effects.push(prompt); - } - effects - } - /// Snapshot of the current screen for a frontend to draw. pub fn view(&self) -> Option { if let Some(state) = self.game.get_current_state() { @@ -1126,9 +933,6 @@ impl ClientCore { self.view().map(Effect::Render).into_iter().collect() } - fn prompt_effects(&self) -> Vec { - self.prompt_effect().into_iter().collect() - } } fn auth_result(reply: &str) -> Result<(), String> { diff --git a/src/client/input.rs b/src/client/input.rs new file mode 100644 index 0000000..0c9d99d --- /dev/null +++ b/src/client/input.rs @@ -0,0 +1,183 @@ +//! Terminal input for the adapter: the command-line editor and key mapping. +//! +//! `ClientCore` knows nothing about keys or the prompt; this module turns +//! keystrokes into `Command`s or a submitted line. + +use crate::client::games::roulette::Direction; +use crate::client::ui::{ + command_names, completion_lines, display_width, input_cursor_column, record_history, +}; +use crate::client::view::Command; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Key { + Char(char), + Enter, + Backspace, + Up, + Down, + Left, + Right, + Tab, + Esc, + CtrlC, +} + +/// What the prompt wants the adapter to do after a key. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Input { + /// Nothing changed. + None, + /// Redraw the prompt. + Prompt, + /// Run this command line. + Submit(String), + /// Print lines above the prompt. + Print(Vec), + Quit, +} + +/// What a key means inside a running game. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum GameInput { + None, + Quit, + Command(Command), +} + +/// The prompt buffer, its history and its cursor. +pub struct Editor { + input: String, + history: Vec, + history_index: usize, +} + +impl Default for Editor { + fn default() -> Self { + Self::new() + } +} + +impl Editor { + pub fn new() -> Self { + Self { + input: String::new(), + history: Vec::new(), + history_index: 0, + } + } + + pub fn input(&self) -> &str { + &self.input + } + + pub fn clear(&mut self) { + self.input.clear(); + } + + /// Column of the cursor after the `> ` prompt. + pub fn cursor_column(&self) -> u16 { + input_cursor_column(2, display_width(&self.input)) + } + + pub fn handle(&mut self, key: Key) -> Input { + match key { + Key::CtrlC => Input::Quit, + Key::Enter => { + let line = self.input.trim().to_string(); + if line.is_empty() { + return Input::None; + } + record_history(&mut self.history, &line); + self.history_index = self.history.len(); + self.input.clear(); + Input::Submit(line) + } + Key::Backspace => { + self.input.pop(); + Input::Prompt + } + Key::Char(c) => { + self.input.push(c); + Input::Prompt + } + Key::Up => { + if self.history_index > 0 { + self.history_index -= 1; + self.input = self.history[self.history_index].clone(); + } + Input::Prompt + } + Key::Down => { + if self.history_index < self.history.len() { + self.history_index += 1; + self.input = if self.history_index == self.history.len() { + String::new() + } else { + self.history[self.history_index].clone() + }; + } + Input::Prompt + } + Key::Tab => { + let prefix = self.input.trim(); + let matches: Vec<&'static str> = command_names() + .into_iter() + .filter(|command| command.starts_with(prefix)) + .collect(); + match matches.len() { + 1 => { + self.input = matches[0].to_string(); + Input::Prompt + } + 0 => Input::None, + _ => Input::Print(completion_lines(&matches, 76)), + } + } + // Esc, Left and Right do nothing on the prompt line. + Key::Esc | Key::Left | Key::Right => Input::None, + } + } +} + +/// Map a key to a command inside `game`. +/// +/// Invalid combinations simply produce a command the core ignores (for +/// example `h` when it is not the player's turn), so this stays stateless. +pub fn game_input(game: &str, key: Key) -> GameInput { + match key { + Key::CtrlC => GameInput::Quit, + Key::Char('q') => GameInput::Command(Command::Leave), + Key::Char('+') | Key::Char('=') => GameInput::Command(Command::AdjustBet(10)), + Key::Char('-') => GameInput::Command(Command::AdjustBet(-10)), + _ => match game { + "roulette" => match key { + Key::Up => GameInput::Command(Command::MoveCursor(Direction::Up)), + Key::Down => GameInput::Command(Command::MoveCursor(Direction::Down)), + Key::Left => GameInput::Command(Command::MoveCursor(Direction::Left)), + Key::Right => GameInput::Command(Command::MoveCursor(Direction::Right)), + Key::Enter => GameInput::Command(Command::PlaceBet), + Key::Char(' ') => GameInput::Command(Command::Spin), + Key::Char('c') => GameInput::Command(Command::ClearBets), + _ => GameInput::None, + }, + "blackjack" => match key { + Key::Char(' ') => GameInput::Command(Command::Deal), + Key::Char('h') => GameInput::Command(Command::Hit), + Key::Char('s') => GameInput::Command(Command::Stand), + Key::Char('d') => GameInput::Command(Command::Double), + _ => GameInput::None, + }, + "crash" => match key { + Key::Char(' ') => GameInput::Command(Command::Start), + Key::Char('c') => GameInput::Command(Command::CashOut), + _ => GameInput::None, + }, + _ => match key { + Key::Char(' ') => GameInput::Command(Command::Spin), + Key::Esc => GameInput::Command(Command::Leave), + _ => GameInput::None, + }, + }, + } +} diff --git a/src/client/mod.rs b/src/client/mod.rs index 456faa0..1d79d97 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -1,6 +1,7 @@ pub mod core; pub mod database; pub mod games; +pub mod input; pub mod paths; pub mod transport; pub mod tui; -- cgit v1.2.3