terminal.rs huge changes

This commit is contained in:
filipriec
2025-03-21 12:05:18 +01:00
parent d3f6296d67
commit 5edc286854
12 changed files with 247 additions and 207 deletions

View File

@@ -1,174 +1,11 @@
// src/client/terminal.rs
use crossterm::event::{self, Event};
use crossterm::{
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen},
};
use crossterm::cursor::{SetCursorStyle, EnableBlinking};
use ratatui::{backend::CrosstermBackend, Terminal};
use std::io::{self, stdout, Write};
use tonic::transport::Channel;
use ratatui::backend::Backend;
// src/tui/terminal.rs
// Import the correct clients and proto messages from their respective modules
use common::proto::multieko2::adresar::adresar_client::AdresarClient;
use common::proto::multieko2::adresar::{AdresarResponse, PostAdresarRequest, PutAdresarRequest};
use common::proto::multieko2::common::{CountResponse, PositionRequest, Empty};
use common::proto::multieko2::table_structure::table_structure_service_client::TableStructureServiceClient;
use common::proto::multieko2::table_structure::TableStructureResponse;
pub mod core;
pub mod grpc_client;
pub mod commands;
pub mod events;
pub struct AppTerminal {
terminal: Terminal<CrosstermBackend<io::Stdout>>,
adresar_client: AdresarClient<Channel>,
table_structure_client: TableStructureServiceClient<Channel>,
}
impl Drop for AppTerminal {
fn drop(&mut self) {
let _ = self.cleanup(); // Best-effort cleanup during drop
}
}
impl AppTerminal {
pub fn set_cursor_style(
&mut self,
style: SetCursorStyle,
) -> Result<(), Box<dyn std::error::Error>> {
execute!(
self.terminal.backend_mut(),
style,
EnableBlinking,
)?;
Ok(())
}
pub async fn new() -> Result<Self, Box<dyn std::error::Error>> {
enable_raw_mode()?;
let mut stdout = stdout();
execute!(
stdout,
EnterAlternateScreen,
SetCursorStyle::SteadyBlock
)?;
let backend = CrosstermBackend::new(stdout);
let terminal = Terminal::new(backend)?;
// Initialize both gRPC clients
let adresar_client = AdresarClient::connect("http://[::1]:50051").await?;
let table_structure_client = TableStructureServiceClient::connect("http://[::1]:50051").await?;
Ok(Self { terminal, adresar_client, table_structure_client })
}
pub fn draw<F>(&mut self, f: F) -> Result<(), Box<dyn std::error::Error>>
where
F: FnOnce(&mut ratatui::Frame),
{
self.terminal.draw(f)?;
Ok(())
}
pub fn read_event(&self) -> Result<Event, Box<dyn std::error::Error>> {
Ok(event::read()?)
}
pub fn cleanup(&mut self) -> Result<(), Box<dyn std::error::Error>> {
// Get a separate stdout handle for cleanup operations
let mut stdout = stdout();
// Step 1: Show cursor first (most important for user experience)
execute!(stdout, crossterm::cursor::Show)?;
// Step 2: Reset cursor style to default
execute!(stdout, crossterm::cursor::SetCursorStyle::DefaultUserShape)?;
// Step 3: Leave alternate screen mode
execute!(stdout, crossterm::terminal::LeaveAlternateScreen)?;
// Step 4: Disable raw mode
disable_raw_mode()?;
// Step 5: Flush all pending changes to ensure they're applied
stdout.flush()?;
// Step 6: Final reset - clear screen and move cursor to home position
// This ensures terminal is in a known good state
execute!(
stdout,
crossterm::terminal::Clear(crossterm::terminal::ClearType::All),
crossterm::cursor::MoveTo(0, 0)
)?;
Ok(())
}
pub async fn handle_command(
&mut self,
action: &str,
is_saved: &mut bool,
) -> Result<(bool, String), Box<dyn std::error::Error>> {
match action {
"quit" => {
if *is_saved {
self.cleanup()?;
Ok((true, "Exiting.".to_string()))
} else {
Ok((false, "No changes saved. Use :q! to force quit.".to_string()))
}
}
"force_quit" => {
self.cleanup()?;
Ok((true, "Force exiting without saving.".to_string()))
}
"save_and_quit" => {
*is_saved = true;
self.cleanup()?;
Ok((true, "State saved. Exiting.".to_string()))
}
_ => Ok((false, format!("Action not recognized: {}", action))),
}
}
// Adresar service methods use adresar_client
pub async fn get_adresar_count(&mut self) -> Result<u64, Box<dyn std::error::Error>> {
let request = tonic::Request::new(Empty::default());
let response: CountResponse = self.adresar_client.get_adresar_count(request).await?.into_inner();
Ok(response.count as u64)
}
pub async fn get_adresar_by_position(&mut self, position: u64) -> Result<AdresarResponse, Box<dyn std::error::Error>> {
let request = tonic::Request::new(PositionRequest { position: position as i64 });
let response: AdresarResponse = self.adresar_client.get_adresar_by_position(request).await?.into_inner();
Ok(response)
}
pub async fn post_adresar(
&mut self,
request: PostAdresarRequest,
) -> Result<tonic::Response<AdresarResponse>, Box<dyn std::error::Error>> {
let request = tonic::Request::new(request);
let response = self.adresar_client.post_adresar(request).await?;
Ok(response)
}
pub async fn put_adresar(
&mut self,
request: PutAdresarRequest,
) -> Result<tonic::Response<AdresarResponse>, Box<dyn std::error::Error>> {
let request = tonic::Request::new(request);
let response = self.adresar_client.put_adresar(request).await?;
Ok(response)
}
// Table structure method uses table_structure_client
pub async fn get_table_structure(
&mut self,
) -> Result<TableStructureResponse, Box<dyn std::error::Error>> {
let request = tonic::Request::new(Empty::default());
let response = self.table_structure_client
.get_adresar_table_structure(request)
.await?;
Ok(response.into_inner())
}
}
pub use core::TerminalCore;
pub use grpc_client::GrpcClient;
pub use commands::CommandHandler;
pub use events::EventHandler;

View File

@@ -0,0 +1,48 @@
// src/tui/terminal/commands.rs
use crate::tui::terminal::core::TerminalCore;
use crate::tui::terminal::grpc_client::GrpcClient;
pub struct CommandHandler {
grpc_client: GrpcClient,
is_saved: bool,
}
impl CommandHandler {
pub fn new(grpc_client: GrpcClient) -> Self {
Self { grpc_client, is_saved: false }
}
pub async fn handle_command(
&mut self,
action: &str,
terminal: &mut TerminalCore
) -> Result<(bool, String), Box<dyn std::error::Error>> {
match action {
"quit" => self.handle_quit(terminal).await,
"force_quit" => self.handle_force_quit(terminal).await,
"save_and_quit" => self.handle_save_quit(terminal).await,
_ => Ok((false, format!("Unknown command: {}", action))),
}
}
async fn handle_quit(&self, terminal: &mut TerminalCore) -> Result<(bool, String), Box<dyn std::error::Error>> {
if self.is_saved {
terminal.cleanup()?;
Ok((true, "Exiting.".into()))
} else {
Ok((false, "No changes saved. Use :q! to force quit.".into()))
}
}
async fn handle_force_quit(&self, terminal: &mut TerminalCore) -> Result<(bool, String), Box<dyn std::error::Error>> {
terminal.cleanup()?;
Ok((true, "Force exiting without saving.".into()))
}
async fn handle_save_quit(&mut self, terminal: &mut TerminalCore) -> Result<(bool, String), Box<dyn std::error::Error>> {
self.is_saved = true;
terminal.cleanup()?;
Ok((true, "State saved. Exiting.".into()))
}
}

View File

@@ -0,0 +1,65 @@
// src/tui/terminal/core.rs
use crossterm::{
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
cursor::{SetCursorStyle, EnableBlinking, Show, MoveTo},
event::Event,
};
use ratatui::{backend::CrosstermBackend, Terminal};
use std::io::{self, stdout, Write};
pub struct TerminalCore {
terminal: Terminal<CrosstermBackend<io::Stdout>>,
}
impl TerminalCore {
pub fn new() -> Result<Self, Box<dyn std::error::Error>> {
enable_raw_mode()?;
let mut stdout = stdout();
execute!(
stdout,
EnterAlternateScreen,
SetCursorStyle::SteadyBlock,
EnableBlinking
)?;
let backend = CrosstermBackend::new(stdout);
let terminal = Terminal::new(backend)?;
Ok(Self { terminal })
}
pub fn draw<F>(&mut self, f: F) -> Result<(), Box<dyn std::error::Error>>
where
F: FnOnce(&mut ratatui::Frame),
{
self.terminal.draw(f)?;
Ok(())
}
pub fn cleanup(&mut self) -> Result<(), Box<dyn std::error::Error>> {
let mut stdout = stdout();
execute!(stdout, Show)?;
execute!(stdout, SetCursorStyle::DefaultUserShape)?;
execute!(stdout, LeaveAlternateScreen)?;
disable_raw_mode()?;
stdout.flush()?;
execute!(
stdout,
crossterm::terminal::Clear(crossterm::terminal::ClearType::All),
MoveTo(0, 0)
)?;
Ok(())
}
pub fn set_cursor_style(
&mut self,
style: SetCursorStyle,
) -> Result<(), Box<dyn std::error::Error>> {
execute!(
self.terminal.backend_mut(),
style,
EnableBlinking,
)?;
Ok(())
}
}

View File

@@ -0,0 +1,15 @@
// src/tui/terminal/events.rs
use crossterm::event::{self, Event};
pub struct EventHandler;
impl EventHandler {
pub fn new() -> Self {
Self
}
pub fn read_event(&self) -> Result<Event, Box<dyn std::error::Error>> {
Ok(event::read()?)
}
}

View File

@@ -0,0 +1,51 @@
// src/tui/terminal/grpc_client.rs
use tonic::transport::Channel;
use common::proto::multieko2::adresar::adresar_client::AdresarClient;
use common::proto::multieko2::adresar::{AdresarResponse, PostAdresarRequest, PutAdresarRequest};
use common::proto::multieko2::common::{CountResponse, PositionRequest, Empty};
use common::proto::multieko2::table_structure::table_structure_service_client::TableStructureServiceClient;
use common::proto::multieko2::table_structure::TableStructureResponse;
pub struct GrpcClient {
adresar_client: AdresarClient<Channel>,
table_structure_client: TableStructureServiceClient<Channel>,
}
impl GrpcClient {
pub async fn new() -> Result<Self, Box<dyn std::error::Error>> {
let adresar_client = AdresarClient::connect("http://[::1]:50051").await?;
let table_structure_client = TableStructureServiceClient::connect("http://[::1]:50051").await?;
Ok(Self { adresar_client, table_structure_client })
}
pub async fn get_adresar_count(&mut self) -> Result<u64, Box<dyn std::error::Error>> {
let request = tonic::Request::new(Empty::default());
let response: CountResponse = self.adresar_client.get_adresar_count(request).await?.into_inner();
Ok(response.count as u64)
}
pub async fn get_adresar_by_position(&mut self, position: u64) -> Result<AdresarResponse, Box<dyn std::error::Error>> {
let request = tonic::Request::new(PositionRequest { position: position as i64 });
let response: AdresarResponse = self.adresar_client.get_adresar_by_position(request).await?.into_inner();
Ok(response)
}
pub async fn post_adresar(&mut self, request: PostAdresarRequest) -> Result<tonic::Response<AdresarResponse>, Box<dyn std::error::Error>> {
let request = tonic::Request::new(request);
let response = self.adresar_client.post_adresar(request).await?;
Ok(response)
}
pub async fn put_adresar(&mut self, request: PutAdresarRequest) -> Result<tonic::Response<AdresarResponse>, Box<dyn std::error::Error>> {
let request = tonic::Request::new(request);
let response = self.adresar_client.put_adresar(request).await?;
Ok(response)
}
pub async fn get_table_structure(&mut self) -> Result<TableStructureResponse, Box<dyn std::error::Error>> {
let request = tonic::Request::new(Empty::default());
let response = self.table_structure_client.get_adresar_table_structure(request).await?;
Ok(response.into_inner())
}
}