small improvements + players cmd + cleanup

This commit is contained in:
Luuk van Oijen 2023-11-23 16:03:31 +01:00
parent f0a5fa48b8
commit 39028ba4d7
4 changed files with 60 additions and 14 deletions

View File

@ -125,6 +125,16 @@ async fn server_main(user_config: Arc<config::Config>, mut cmd_rx: mpsc::Receive
server.close().await; server.close().await;
break 'server; break 'server;
}, },
"players" => {
let mut pl = "Players:\n".to_string();
for (i, (id, player)) in status.player_list.iter().enumerate() {
pl.push_str(&format!("\t[{: >2}] - {player}", id));
if i + 1 < status.player_list.len() {
pl.push('\n');
}
}
info!("{}", pl);
},
_ => info!("Unknown command!"), _ => info!("Unknown command!"),
} }
} else { } else {

View File

@ -24,17 +24,17 @@ use super::car::*;
use super::packet::*; use super::packet::*;
lazy_static! { lazy_static! {
pub static ref TAKEN_PLAYER_IDS: Mutex<[bool;256]> = Mutex::new([false; 256]); pub static ref TAKEN_PLAYER_IDS: Mutex<Vec<u8>> = Mutex::new(Vec::new());
pub static ref CLIENT_MOD_PROGRESS: Mutex<HashMap<u8, isize>> = Mutex::new(HashMap::new()); pub static ref CLIENT_MOD_PROGRESS: Mutex<HashMap<u8, isize>> = Mutex::new(HashMap::new());
} }
// TODO: Return a proper error? // TODO: Return a proper error?
async fn claim_id() -> Result<u8, ()> { async fn claim_id() -> Result<u8, ()> {
let mut lock = TAKEN_PLAYER_IDS.lock().await; let mut lock = TAKEN_PLAYER_IDS.lock().await;
for index in 0..255 { for index in 0..=255 {
if !lock[index] { if !lock.contains(&index) {
lock[index] = true; lock.push(index);
return Ok(index as u8); return Ok(index);
} }
} }
// requires more then 255 players on the server to error // requires more then 255 players on the server to error
@ -43,7 +43,7 @@ async fn claim_id() -> Result<u8, ()> {
async fn free_id(id: u8) { async fn free_id(id: u8) {
let mut lock = TAKEN_PLAYER_IDS.lock().await; let mut lock = TAKEN_PLAYER_IDS.lock().await;
lock[id as usize] = false; *lock = lock.drain(..).filter(|i| *i != id).collect::<Vec<u8>>();
} }
#[derive(PartialEq)] #[derive(PartialEq)]

View File

@ -288,7 +288,6 @@ impl Server {
} }
if set.is_empty() == false { if set.is_empty() == false {
info!("what!");
// Because join_next() is cancel safe, we can simply cancel it after N duration // Because join_next() is cancel safe, we can simply cancel it after N duration
// so at worst this client acceptance loop blocks for N duration // so at worst this client acceptance loop blocks for N duration
tokio::select! { tokio::select! {

View File

@ -21,7 +21,7 @@ pub async fn tui_main(config: Arc<Config>, cmd_tx: mpsc::Sender<Vec<String>>) {
let mut tui = Tui::new().expect("Failed to initialize tui!"); let mut tui = Tui::new().expect("Failed to initialize tui!");
'app: loop { 'app: loop {
if tui.update().await.expect("Failed to run tui.update!") { if tui.update(&cmd_tx).await.expect("Failed to run tui.update!") {
cmd_tx.send(vec!["exit".to_string()]).await.unwrap(); cmd_tx.send(vec!["exit".to_string()]).await.unwrap();
break 'app; break 'app;
} }
@ -34,6 +34,8 @@ struct Tui {
log_buffer: VecDeque<(Level, String)>, log_buffer: VecDeque<(Level, String)>,
history_scroll: usize,
input_history: Vec<String>,
input: String, input: String,
} }
@ -57,6 +59,8 @@ impl Tui {
log_buffer: VecDeque::new(), log_buffer: VecDeque::new(),
history_scroll: 0,
input_history: Vec::new(),
input: String::new(), input: String::new(),
}) })
} }
@ -67,7 +71,7 @@ impl Tui {
Ok(()) Ok(())
} }
async fn update(&mut self) -> Result<bool> { async fn update(&mut self, cmd_tx: &mpsc::Sender<Vec<String>>) -> Result<bool> {
for (level, msg) in crate::logger::drain_log_buffer().await { for (level, msg) in crate::logger::drain_log_buffer().await {
self.log_buffer.push_front((level, msg)); self.log_buffer.push_front((level, msg));
if self.log_buffer.len() > 100 { if self.log_buffer.len() > 100 {
@ -77,9 +81,42 @@ impl Tui {
if event::poll(std::time::Duration::from_millis(16))? { if event::poll(std::time::Duration::from_millis(16))? {
if let event::Event::Key(key) = event::read()? { if let event::Event::Key(key) = event::read()? {
if key.kind == KeyEventKind::Press && key.code == KeyCode::Char('q') { if key.kind == KeyEventKind::Press {
match key.code {
KeyCode::Char(c) => {
self.input.push(c);
self.history_scroll = 0;
},
KeyCode::Backspace => { self.input.pop(); },
KeyCode::Enter => {
if self.input.is_empty() == false {
let args = self.input.split(" ").map(|s| s.to_string()).collect::<Vec<String>>();
if let Err(e) = cmd_tx.send(args.clone()).await {
error!("Error occured sending a command to the server! {e}");
return Ok(true); return Ok(true);
} }
self.input_history.insert(0, self.input.clone());
self.input = String::new();
if args.get(0) == Some(&"exit".to_string()) {
return Ok(true);
}
}
},
KeyCode::Up => {
if self.history_scroll < self.input_history.len() {
self.history_scroll += 1;
self.input = self.input_history[self.history_scroll - 1].clone();
}
},
KeyCode::Down => {
if self.history_scroll > 1 {
self.history_scroll -= 1;
self.input = self.input_history[self.history_scroll - 1].clone();
}
},
_ => {},
}
}
} }
} }
@ -125,17 +162,17 @@ impl Tui {
lines.reverse(); lines.reverse();
frame.render_widget( frame.render_widget(
// Paragraph::new("[INFO] info!!!\n[DEBUG] debug!!!!").block(Block::new().borders(Borders::ALL)), // Paragraph::new("[INFO] info!!!\n[DEBUG] debug!!!!").block(Block::new().borders(Borders::ALL)),
Paragraph::new(Text::from(lines)).block(Block::new().borders(Borders::ALL)), Paragraph::new(Text::from(lines)).block(Block::new().borders(Borders::ALL).title("Log")),
horiz_layout[0], horiz_layout[0],
); );
frame.render_widget( frame.render_widget(
Paragraph::new("0 - luuk-bepis\n1 - lion guy\n2 - the_racc").block(Block::new().borders(Borders::ALL)), Paragraph::new("0 - luuk-bepis\n1 - lion guy\n2 - the_racc").block(Block::new().borders(Borders::ALL).title("Player List")),
horiz_layout[1], horiz_layout[1],
); );
frame.render_widget( frame.render_widget(
Paragraph::new(format!(" > {}", self.input)).block(Block::new().borders(Borders::ALL)), Paragraph::new(format!(" > {}", self.input)).block(Block::new().borders(Borders::ALL).title("Input")),
vert_layout[1], vert_layout[1],
); );
})?; })?;