code cleanup

This commit is contained in:
filipriec
2025-05-31 23:02:09 +02:00
parent ea88c2686d
commit 6e2fc5349b
5 changed files with 316 additions and 214 deletions

View File

@@ -1,4 +1,4 @@
// src/ui/handlers/ui.rs
// client/src/ui/handlers/ui.rs
use crate::config::binds::config::Config;
use crate::config::colors::themes::Theme;
@@ -23,16 +23,14 @@ use crate::tui::terminal::{EventReader, TerminalCore};
use crate::ui::handlers::render::render_ui;
use crate::tui::functions::common::login::LoginResult;
use crate::tui::functions::common::register::RegisterResult;
// Removed: use crate::tui::functions::common::add_table::handle_save_table_action;
// Removed: use crate::functions::modes::navigation::add_table_nav::SaveTableResultSender;
use crate::ui::handlers::context::DialogPurpose; // UiContext removed if not used directly
use crate::ui::handlers::context::DialogPurpose;
use crate::tui::functions::common::login;
use crate::tui::functions::common::register;
use std::time::Instant;
use anyhow::{Context, Result};
use crossterm::cursor::SetCursorStyle;
use crossterm::event as crossterm_event;
use tracing::{error, info, warn}; // Added warn
use tracing::{error, info, warn};
use tokio::sync::mpsc;
@@ -43,14 +41,14 @@ pub async fn run_ui() -> Result<()> {
let mut grpc_client = GrpcClient::new().await?;
let mut command_handler = CommandHandler::new();
// --- Channel for Login Results ---
let (login_result_sender, mut login_result_receiver) =
mpsc::channel::<LoginResult>(1);
let (register_result_sender, mut register_result_receiver) =
mpsc::channel::<RegisterResult>(1);
let (save_table_result_sender, mut save_table_result_receiver) =
mpsc::channel::<Result<String>>(1);
let (save_logic_result_sender, _save_logic_result_receiver) = // Prefixed and removed mut
let (save_logic_result_sender, _save_logic_result_receiver) =
mpsc::channel::<Result<String>>(1);
let mut event_handler = EventHandler::new(
@@ -69,7 +67,7 @@ pub async fn run_ui() -> Result<()> {
let mut buffer_state = BufferState::default();
let mut app_state = AppState::new().context("Failed to create initial app state")?;
// --- DATA: Load auth data from file at startup ---
let mut auto_logged_in = false;
match load_auth_data() {
Ok(Some(stored_data)) => {
@@ -87,7 +85,7 @@ pub async fn run_ui() -> Result<()> {
error!("Failed to load auth data: {}", e);
}
}
// --- END DATA ---
let column_names =
UiService::initialize_app_state(&mut grpc_client, &mut app_state)
@@ -108,7 +106,7 @@ pub async fn run_ui() -> Result<()> {
let mut needs_redraw = true;
loop {
// --- Synchronize UI View from Active Buffer ---
if let Some(active_view) = buffer_state.get_active_view() {
app_state.ui.show_intro = false;
app_state.ui.show_login = false;
@@ -155,12 +153,12 @@ pub async fn run_ui() -> Result<()> {
AppView::Scratch => {}
}
}
// --- End Synchronization ---
// --- Handle Pending Table Structure Fetches ---
if let Some((profile_name, table_name)) = app_state.pending_table_structure_fetch.take() {
if app_state.ui.show_add_logic {
// Ensure admin_state.add_logic_state matches the pending fetch
if admin_state.add_logic_state.profile_name == profile_name &&
admin_state.add_logic_state.selected_table_name.as_deref() == Some(table_name.as_str()) {
@@ -168,7 +166,7 @@ pub async fn run_ui() -> Result<()> {
let fetch_message = UiService::initialize_add_logic_table_data(
&mut grpc_client,
&mut admin_state.add_logic_state,
&app_state.profile_tree, // Pass the profile tree
&app_state.profile_tree,
).await.unwrap_or_else(|e| {
error!("Error initializing add_logic_table_data: {}", e);
format!("Error fetching table structure: {}", e)
@@ -196,7 +194,7 @@ pub async fn run_ui() -> Result<()> {
}
}
// --- 3. Draw UI ---
if needs_redraw {
terminal.draw(|f| {
render_ui(
@@ -215,7 +213,7 @@ pub async fn run_ui() -> Result<()> {
event_handler.command_mode,
&event_handler.command_message,
&event_handler.navigation_state,
// General app state
app_state.total_count,
app_state.current_position,
&app_state.current_dir,
@@ -226,7 +224,7 @@ pub async fn run_ui() -> Result<()> {
needs_redraw = false;
}
// --- Handle Pending Column Autocomplete for Table Selection ---
if let Some(table_name) = admin_state.add_logic_state.script_editor_awaiting_column_autocomplete.clone() {
if app_state.ui.show_add_logic {
let profile_name = admin_state.add_logic_state.profile_name.clone();
@@ -249,7 +247,7 @@ pub async fn run_ui() -> Result<()> {
}
}
// --- Cursor Visibility Logic ---
let current_mode = ModeManager::derive_mode(&app_state, &event_handler, &admin_state);
match current_mode {
AppMode::Edit => { terminal.show_cursor()?; }
@@ -265,7 +263,7 @@ pub async fn run_ui() -> Result<()> {
}
AppMode::Command => { terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?; terminal.show_cursor().context("Failed to show cursor in Command mode")?; }
}
// --- End Cursor Visibility Logic ---
let total_count = app_state.total_count;
let mut current_position = app_state.current_position;
@@ -274,7 +272,7 @@ pub async fn run_ui() -> Result<()> {
needs_redraw = true;
}
// --- 1. Handle Terminal Events ---
let mut event_outcome_result = Ok(EventOutcome::Ok(String::new()));
let mut event_processed = false;
if crossterm_event::poll(std::time::Duration::from_millis(1))? {
@@ -304,32 +302,32 @@ pub async fn run_ui() -> Result<()> {
}
app_state.current_position = current_position;
// --- Check for Login Results from Channel ---
match login_result_receiver.try_recv() {
Ok(result) => {
if login::handle_login_result(result, &mut app_state, &mut auth_state, &mut login_state) {
needs_redraw = true;
}
}
Err(mpsc::error::TryRecvError::Empty) => { /* No message waiting */ }
Err(mpsc::error::TryRecvError::Empty) => {}
Err(mpsc::error::TryRecvError::Disconnected) => {
error!("Login result channel disconnected unexpectedly.");
}
}
// --- Check for Register Results from Channel ---
match register_result_receiver.try_recv() {
Ok(result) => {
if register::handle_registration_result(result, &mut app_state, &mut register_state) {
needs_redraw = true;
}
}
Err(mpsc::error::TryRecvError::Empty) => { /* No message waiting */ }
Err(mpsc::error::TryRecvError::Empty) => {}
Err(mpsc::error::TryRecvError::Disconnected) => {
error!("Register result channel disconnected unexpectedly.");
}
}
// --- Check for Save Table Results ---
match save_table_result_receiver.try_recv() {
Ok(result) => {
app_state.hide_dialog();
@@ -355,13 +353,11 @@ pub async fn run_ui() -> Result<()> {
}
}
// --- Centralized Consequence Handling ---
let mut should_exit = false;
match event_outcome_result {
Ok(outcome) => match outcome {
EventOutcome::Ok(_message) => {
// Message is often set directly in event_handler.command_message
}
EventOutcome::Ok(_message) => {}
EventOutcome::Exit(message) => {
event_handler.command_message = message;
should_exit = true;
@@ -380,19 +376,17 @@ pub async fn run_ui() -> Result<()> {
format!("Error handling save outcome: {}", e);
}
}
EventOutcome::ButtonSelected { context: _, index: _ } => {
// Handled within event_handler or specific navigation modules
}
EventOutcome::ButtonSelected { context: _, index: _ } => {}
},
Err(e) => {
event_handler.command_message = format!("Error: {}", e);
}
}
// --- End Consequence Handling ---
// --- Position Change Handling ---
let position_changed = app_state.current_position != position_before_event;
let current_total_count = app_state.total_count; // Use current total_count
let current_total_count = app_state.total_count;
let mut position_logic_needs_redraw = false;
if app_state.ui.show_form {
@@ -430,13 +424,13 @@ pub async fn run_ui() -> Result<()> {
if !load_message.starts_with("Loaded entry") || event_handler.command_message.is_empty() {
event_handler.command_message = load_message;
}
} else { // current_position is 0 or invalid
} else {
app_state.current_position = 1.min(current_total_count + 1);
if app_state.current_position > current_total_count { // Handles empty db case
if app_state.current_position > current_total_count {
form_state.reset_to_empty();
form_state.current_field = 0;
}
// If db is not empty, this will trigger load in next iteration if position changed to 1
}
} else if !position_changed && !event_handler.is_edit_mode {
let current_input = form_state.get_current_input();
@@ -460,18 +454,18 @@ pub async fn run_ui() -> Result<()> {
if position_logic_needs_redraw {
needs_redraw = true;
}
// --- End Position Change Handling ---
if should_exit {
return Ok(());
}
// --- FPS Calculation ---
let now = Instant::now();
let frame_duration = now.duration_since(last_frame_time);
last_frame_time = now;
if frame_duration.as_secs_f64() > 1e-6 { // Avoid division by zero
if frame_duration.as_secs_f64() > 1e-6 {
current_fps = 1.0 / frame_duration.as_secs_f64();
}
} // End main loop
}
}