Add commands

This commit is contained in:
Sofia 2026-07-15 20:30:22 +03:00
parent fbb24ddd17
commit eba728f194

View File

@ -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<Gd<ScrollContainer>>,
scroll_next_update: bool,
commands: HashMap<String, Rc<Box<dyn Command>>>,
base: Base<Panel>,
}
@ -39,11 +44,15 @@ struct CommandLinePanel {
#[godot_api]
impl IPanel for CommandLinePanel {
fn init(base: Base<Panel>) -> Self {
let mut commands: HashMap<String, Rc<Box<dyn Command>>> = 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::<Vec<_>>();
if let Some(command) = self.commands.get(command) {
command.clone().execute(self, &params);
} 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::<Vec<_>>();
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"
}
}