diff --git a/rust/src/ui/cli.rs b/rust/src/ui/cli.rs index 595b283..5c770e7 100644 --- a/rust/src/ui/cli.rs +++ b/rust/src/ui/cli.rs @@ -1,3 +1,7 @@ +use std::collections::HashMap; +use std::ops::DerefMut; +use std::rc::Rc; + use godot::classes::{RichTextLabel, ScrollContainer}; use godot::prelude::*; @@ -32,6 +36,7 @@ struct CommandLinePanel { pub scroll_container: Option>, scroll_next_update: bool, + commands: HashMap>>, base: Base, } @@ -39,11 +44,15 @@ struct CommandLinePanel { #[godot_api] impl IPanel for CommandLinePanel { fn init(base: Base) -> Self { + let mut commands: HashMap>> = HashMap::new(); + commands.insert("help".to_owned(), Rc::new(Box::new(HelpCommand))); + CommandLinePanel { input_field: None, text_field: None, scroll_container: None, scroll_next_update: false, + commands, base, } } @@ -61,19 +70,19 @@ impl IPanel for CommandLinePanel { if text.contains("\n") { let parts = text.split("\n"); let first = parts.get(0).unwrap(); - self.handle_command(first.to_string()); + self.input_command(first.to_string()); } } } } impl CommandLinePanel { - pub fn handle_command(&mut self, command: String) { + pub fn input_command(&mut self, command: String) { self.publish_message(format!("> {}", command), CliColor::Command); if let Some(input) = &mut self.input_field { input.clear(); } - self.publish_message("Command registered!".to_owned(), CliColor::Regular); + self.handle_command(&command); self.scroll_next_update = true; } @@ -87,4 +96,39 @@ impl CommandLinePanel { field.append_text("[/color]"); } } + + fn handle_command(&mut self, text: &String) { + let mut command_and_params = text.split(" ").into_iter(); + let command = command_and_params.next().clone().unwrap_or(""); + let params = command_and_params.collect::>(); + if let Some(command) = self.commands.get(command) { + command.clone().execute(self, ¶ms); + } else { + self.publish_message(format!("Unknown command: {}", command), CliColor::Regular); + } + } +} + +trait Command { + fn execute(&self, cli: &mut CommandLinePanel, params: &[&str]); + fn help(&self) -> &str; +} + +#[derive(Clone)] +struct HelpCommand; +impl Command for HelpCommand { + fn execute(&self, cli: &mut CommandLinePanel, params: &[&str]) { + let mut keys = cli.commands.keys().cloned().collect::>(); + keys.sort(); + for key in keys { + cli.publish_message( + format!("\t- {}: {}", key, cli.commands.get(&key).unwrap().help()), + CliColor::Regular, + ); + } + } + + fn help(&self) -> &str { + "Shows this message" + } }