use std::fs::File; use std::path::PathBuf; use std::io::{Write, BufRead, BufReader}; use color_eyre::Result; use crossterm::event::{KeyCode, KeyEvent}; use ratatui::layout::{Constraint, Margin}; use ratatui::style::{Stylize, Modifier}; use ratatui::{ text::Text, layout::{Alignment, Rect}, widgets::{ Block, Cell, Row, Table, TableState, Scrollbar, Padding, ScrollbarOrientation, ScrollbarState, }, Frame }; use tokio::sync::mpsc::UnboundedSender; use super::{PartialComponent, Component, CurrentTab}; use crate::types::EraRewardPoints; use crate::{ action::Action, config::Config, palette::StylePalette, }; pub struct CurrentValidators { is_active: bool, action_tx: Option>, known_validators_file: PathBuf, palette: StylePalette, scroll_state: ScrollbarState, table_state: TableState, individual: Vec, known_validators: std::collections::HashMap<[u8; 32], String>, total_points: u32, era_index: u32, my_stash_id: Option<[u8; 32]>, } impl Default for CurrentValidators { fn default() -> Self { Self::new() } } impl CurrentValidators { const KNOWN_VALIDATORS_FILE: &str = "known-validators"; pub fn new() -> Self { Self { is_active: false, action_tx: None, known_validators_file: Default::default(), scroll_state: ScrollbarState::new(0), table_state: TableState::new(), individual: Default::default(), known_validators: Default::default(), total_points: 0, era_index: 0, my_stash_id: None, palette: StylePalette::default(), } } fn update_choosen_details(&self, index: usize) { if let Some(action_tx) = &self.action_tx { let _ = action_tx.send(Action::SetChoosenValidator( self.individual[index].account_id, self.individual[index].points, self.total_points)); } } fn save_validator_name(&mut self, new_name: String) { if let Some(index) = self.table_state.selected() { let account_id = self.individual[index].account_id; let _ = self.known_validators.insert(account_id, new_name); let mut file = File::create(&self.known_validators_file) .expect("file should be accessible; qed"); for (account_id, name) in self.known_validators.iter() { let seed = hex::encode(account_id); writeln!(file, "{}:0x{}", &name, &seed).unwrap(); } } } fn update_known_validator_record(&mut self) { if self.table_state.selected().is_some() { if let Some(action_tx) = &self.action_tx { let _ = action_tx.send(Action::RenameKnownValidatorRecord); } } } fn read_known_validators(&mut self, file_path: &PathBuf) -> Result<()> { if let Ok(file) = File::open(file_path) { let reader = BufReader::new(file); for line in reader.lines() { let line = line?.replace("\n", ""); let line_split_at = line.find(":").unwrap_or(line.len()); let (name, seed) = line.split_at(line_split_at); let seed_str = &seed[3..]; let account_id: [u8; 32] = hex::decode(seed_str) .expect("stored seed is valid hex string; qed") .as_slice() .try_into() .expect("stored seed is valid length; qed"); let _ = self.known_validators.insert(account_id, name.to_string()); } } Ok(()) } fn first_row(&mut self) { if self.individual.len() > 0 { self.table_state.select(Some(0)); self.scroll_state = self.scroll_state.position(0); self.update_choosen_details(0); } } fn next_row(&mut self) { let i = match self.table_state.selected() { Some(i) => { if i >= self.individual.len() - 1 { i } else { i + 1 } }, None => 0, }; self.table_state.select(Some(i)); self.scroll_state = self.scroll_state.position(i); self.update_choosen_details(i); } fn last_row(&mut self) { if self.individual.len() > 0 { let last = self.individual.len() - 1; self.table_state.select(Some(last)); self.scroll_state = self.scroll_state.position(last); self.update_choosen_details(last); } } fn previous_row(&mut self) { let i = match self.table_state.selected() { Some(i) => { if i == 0 { 0 } else { i - 1 } }, None => 0 }; self.table_state.select(Some(i)); self.scroll_state = self.scroll_state.position(i); self.update_choosen_details(i); } fn update_era_rewards( &mut self, era_index: u32, total_points: u32, individual: &Vec, ) { self.individual = individual.to_vec(); self.total_points = total_points; self.era_index = era_index; if let Some(account_id) = self.my_stash_id { if self.individual.len() > 1 { if let Some(index) = self.individual .iter() .position(|item| item.account_id == account_id) { self.individual.swap(0, index); } } } self.scroll_state = self.scroll_state.content_length(self.individual.len()); if let Some(index) = self.table_state.selected() { self.update_choosen_details(index); } } } impl PartialComponent for CurrentValidators { fn set_active(&mut self, current_tab: CurrentTab) { match current_tab { CurrentTab::CurrentValidators => self.is_active = true, _ => self.is_active = false, } } } impl Component for CurrentValidators { fn register_action_handler(&mut self, tx: UnboundedSender) -> Result<()> { self.action_tx = Some(tx); Ok(()) } fn register_config_handler(&mut self, config: Config) -> Result<()> { if let Some(style) = config.styles.get(&crate::app::Mode::Nominator) { self.palette.with_normal_style(style.get("normal_style").copied()); self.palette.with_hover_style(style.get("hover_style").copied()); self.palette.with_normal_border_style(style.get("normal_border_style").copied()); self.palette.with_hover_border_style(style.get("hover_border_style").copied()); self.palette.with_normal_title_style(style.get("normal_title_style").copied()); self.palette.with_hover_title_style(style.get("hover_title_style").copied()); self.palette.with_highlight_style(style.get("highlight_style").copied()); self.palette.with_scrollbar_style(style.get("scrollbar_style").copied()); } let mut known_validators_file = config.config.data_dir; known_validators_file.push(Self::KNOWN_VALIDATORS_FILE); self.read_known_validators(&known_validators_file)?; self.known_validators_file = known_validators_file; Ok(()) } fn update(&mut self, action: Action) -> Result> { match action { Action::UpdateKnownValidator(validator_name) => self.save_validator_name(validator_name), Action::SetStashAccount(account_id) => self.my_stash_id = Some(account_id), Action::SetCurrentValidatorEraRewards(era_index, total_points, individual) => self.update_era_rewards(era_index, total_points, &individual), _ => {} }; Ok(None) } fn handle_key_event(&mut self, key: KeyEvent) -> Result> { if self.is_active { match key.code { KeyCode::Up | KeyCode::Char('k') => self.previous_row(), KeyCode::Down | KeyCode::Char('j') => self.next_row(), KeyCode::Char('g') => self.first_row(), KeyCode::Char('G') => self.last_row(), KeyCode::Char('R') => self.update_known_validator_record(), _ => {}, }; } Ok(None) } fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> { let [place, _] = super::validator_details_layout(area); let (border_style, border_type) = self.palette.create_border_style(self.is_active); let table = Table::new( self.individual .iter() .enumerate() .map(|(index, info)| { let mut address_text = Text::from(info.address.clone()).alignment(Alignment::Center); let mut points_text = Text::from(info.points.to_string()).alignment(Alignment::Right); if info.disabled { address_text = address_text.add_modifier(Modifier::CROSSED_OUT); points_text = points_text.add_modifier(Modifier::CROSSED_OUT); } if self.my_stash_id.is_some() && index == 0 { let name = self.known_validators .get(&info.account_id) .cloned() .unwrap_or("My stash".to_string()); Row::new(vec![ Cell::from(Text::from(name).alignment(Alignment::Left)), Cell::from(address_text), Cell::from(points_text), ]).style(self.palette.create_highlight_style()) } else { let name = self.known_validators .get(&info.account_id) .cloned() .unwrap_or("Ghostie".to_string()); Row::new(vec![ Cell::from(Text::from(name).alignment(Alignment::Left)), Cell::from(address_text), Cell::from(points_text), ]) } }), [ Constraint::Length(12), Constraint::Min(0), Constraint::Length(6), ], ) .style(self.palette.create_basic_style(false)) .highlight_style(self.palette.create_basic_style(true)) .column_spacing(1) .block(Block::bordered() .border_style(border_style) .border_type(border_type) .padding(Padding::right(2)) .title_alignment(Alignment::Right) .title_style(self.palette.create_title_style(false)) .title(format!("Validators | Total points: {}", self.total_points))); let scrollbar = Scrollbar::default() .orientation(ScrollbarOrientation::VerticalRight) .begin_symbol(None) .end_symbol(None) .style(self.palette.create_scrollbar_style()); frame.render_stateful_widget(table, place, &mut self.table_state); frame.render_stateful_widget( scrollbar, place.inner(Margin { vertical: 1, horizontal: 1 }), &mut self.scroll_state, ); Ok(()) } }