From 8fe137393bedfb308f0de790e9bdaeafee6c2393 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 22 Sep 2024 00:34:10 +0200 Subject: [PATCH 1/9] Starts work with the UI --- Cargo.toml | 3 + src/main.rs | 17 ++- src/structs.rs | 6 ++ src/ui.rs | 274 +++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 297 insertions(+), 3 deletions(-) create mode 100644 src/ui.rs diff --git a/Cargo.toml b/Cargo.toml index c14dee0..7f91205 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,10 +6,13 @@ edition = "2021" [dependencies] byteorder = "1.5.0" clap = { version = "4.5.17", features = ["derive"] } +color-eyre = "0.6.3" csv = "1.3.0" hex = "0.4.3" memchr = "2.7.4" once_cell = "1.19.0" packed_struct = "0.10.1" +ratatui = "0.28.1" serialport = "4.5.0" +strum = { version = "0.26.3", features = ["derive"] } thiserror = "1.0.63" diff --git a/src/main.rs b/src/main.rs index 43db167..79ebbdb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,14 +4,25 @@ //! and will not offer any scripting capabilities #![warn(missing_docs, clippy::missing_docs_in_private_items)] +#![allow(dead_code)] mod scan; mod structs; +mod ui; -use crate::scan::scan; - +use color_eyre::Result; use structs::TinyError; +use ui::AppInfo; fn main() -> Result<(), TinyError> { // let args = Args::parse(); - scan() + // scan() + + color_eyre::install()?; + let terminal = ratatui::init(); + let ports = serialport::available_ports()?; + let app_r = AppInfo::new(ports).run(terminal); + + ratatui::restore(); + + app_r.map_err(TinyError::TUIRuntimeError) } diff --git a/src/structs.rs b/src/structs.rs index 853b31a..a07eac0 100644 --- a/src/structs.rs +++ b/src/structs.rs @@ -16,4 +16,10 @@ pub enum TinyError { /// The given file could't be exported #[error("Couldn't open the given file")] OpenOutput(#[from] std::io::Error), + /// Generic TUI initialization error + #[error("An error occured while creating the TUI")] + TUIInitialization(#[from] color_eyre::Report), + /// A runtime error occured + #[error("A runtime error occured :\n{0}")] + TUIRuntimeError(color_eyre::eyre::Error), } diff --git a/src/ui.rs b/src/ui.rs new file mode 100644 index 0000000..796998d --- /dev/null +++ b/src/ui.rs @@ -0,0 +1,274 @@ +//! The (minimal) user interface to control the program +#![allow(unused_imports)] +use color_eyre::{owo_colors::OwoColorize, Result}; +use ratatui::{ + buffer::Buffer, + crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind}, + layout::{Constraint, Layout, Rect}, + style::{ + palette::tailwind::{BLUE, GREEN, SLATE}, + Color, Modifier, Style, Stylize, + }, + symbols, + text::Line, + widgets::{ + Block, Borders, HighlightSpacing, List, ListDirection, ListItem, ListState, Padding, + Paragraph, StatefulWidget, Widget, Wrap, + }, + DefaultTerminal, Frame, +}; +use serialport::SerialPortInfo; +use strum::EnumIter; +use strum::IntoEnumIterator; + +/// The header style +const HEADER_STYLE: Style = Style::new().fg(SLATE.c100).bg(BLUE.c800); +/// The background color +const NORMAL_ROW_BG: Color = SLATE.c950; +/// Background color for alternated rows +const ALT_ROW_BG_COLOR: Color = SLATE.c900; +/// The style applied to the currently selected item +const SELECTED_STYLE: Style = Style::new().bg(SLATE.c800).add_modifier(Modifier::BOLD); +/// Foreground color +const TEXT_FG_COLOR: Color = SLATE.c200; + +/// This struct holds the current state of the app. +#[derive(Debug)] +pub(crate) struct AppInfo { + /// Wether the app sould immediately quit + should_quit: bool, + /// The list of baudrates + baudrate: BaudRateList, + /// The list of ports + port_list: PortList, +} + +/// The list of all baudrates selectables +#[derive(Debug)] +struct BaudRateList { + /// The selected baudrate (default : BAUD1115200) + selected: usize, + /// The baudrate list + baudrates: Vec, + /// The inner state of the widget + state: ListState, +} +impl BaudRateList { + /// Convert into a vec of strings, this is extremely expensive and shouldn't be done that way + fn to_vecstr(&self) -> Vec { + self.baudrates + .iter() + .map(|i| format!("{}", *i as usize)) + .collect() + } + // fn to_itemlist(&self) -> Vec { + // self.baudrates + // .iter() + // .map(|i| ListItemformat!("{}", *i as usize)) + // .collect() + // } + + /// Pick the baudrate above + fn above(&mut self) { + // self.selected = (self.selected + 1) % self.baudrates.len(); + self.state.select_previous(); + } + + /// Pick the baudrate below + fn below(&mut self) { + // self.selected = (self.selected - 1) % self.baudrates.len(); + self.state.select_next(); + } +} + +impl Default for BaudRateList { + fn default() -> Self { + Self { + selected: 3, + baudrates: BaudRate::iter().collect::>(), + state: ListState::default(), + } + } +} + +// impl Iterator for BaudRateList { +// type Item = &'str; + +// fn next(&mut self) -> Option { +// todo!() +// } +// } +/// A list of possible baudrates +#[derive(Debug, EnumIter, Copy, Clone)] +enum BaudRate { + BAUD19200 = 19_200, + BAUD38400 = 38_400, + BAUD57600 = 57_600, + BAUD115200 = 115_200, + BAUD230400 = 230_400, + BAUD460800 = 460_800, + BAUD921600 = 921_600, + BAUD1843200 = 1_843_200, + BAUD2000000 = 2_000_000, + BAUD3000000 = 3_000_000, +} + +/// A wrapper over the list of ports +#[derive(Debug)] +pub(crate) struct PortList { + /// The list of found ports + ports: Vec, + /// The currently selected port (doing it that way completly avoids the ) + selected: usize, + /// The inner state of the widget + state: ListState, +} + +impl PortList { + /// Make a port list from a serial reading + pub(crate) fn from_serial(info: Vec) -> Self { + let ports: Vec = info.into_iter().map(|port| port.port_name).collect(); + let selected = find_best_port(&ports); + Self { + ports, + selected, + state: ListState::default(), + } + } + + /// Convert the list of ports + /// TODO: Remove the clone part + fn to_vecstr(&self) -> Vec { + self.ports.clone() + } +} + +/// Try to guess the best port to preselect +fn find_best_port(ports: &[String]) -> usize { + let best_ports = ["/dev/ttyACM0", "COM3", "COM5"]; + for port in best_ports { + if let Some(p) = ports.iter().position(|v| v == port) { + return p; + } + } + 0 +} + +impl AppInfo { + /// Create a new app with the port info available + pub(crate) fn new(info: Vec) -> Self { + Self { + should_quit: false, + baudrate: BaudRateList::default(), + port_list: PortList::from_serial(info), + } + } + + /// Handle keys while in the first menu + fn handle_start_keys(&mut self, key: KeyEvent) { + if key.kind != KeyEventKind::Press { + return; + } + match key.code { + KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true, + // KeyCode::Char('h') | KeyCode::Left => self.baudrate. + KeyCode::Char('j') | KeyCode::Down => self.baudrate.above(), + KeyCode::Char('k') | KeyCode::Up => self.baudrate.below(), + // KeyCode::Char('g') | KeyCode::Home => self.select_first(), + // KeyCode::Char('G') | KeyCode::End => self.select_last(), + // KeyCode::Enter => { + // self.toggle_status(); + // } + _ => {} + } + } + + /// Contains the main loop for running the app + pub(crate) fn run(&mut self, mut terminal: DefaultTerminal) -> Result<()> { + loop { + terminal.draw(|v| self.draw_config(v))?; + if let Event::Key(key) = event::read()? { + self.handle_start_keys(key); + }; + if self.should_quit { + break; + } + } + Ok(()) + } + + // fn init_config(&self) -> &Buffer { + // let [_title_area, main_area, _status_area] = Layout::vertical([ + // Constraint::Length(3), + // Constraint::Min(10), + // Constraint::Length(3), + // ]) + // .areas(frame.area()); + // let [_, area_ports, area_baud, _] = Layout::horizontal([ + // Constraint::Min(10), + // Constraint::Percentage(50), + // Constraint::Percentage(50), + // Constraint::Min(10), + // ]) + // .areas(main_area); + // main_area + // } + + /// Draw the config info + // TODO: This config doesn't need to be reinit every frame + fn draw_config(&mut self, frame: &mut Frame) { + let [_title_area, main_area, _status_area] = Layout::vertical([ + Constraint::Length(3), + Constraint::Min(10), + Constraint::Length(3), + ]) + .areas(frame.area()); + let [_, area_ports, area_baud, _] = Layout::horizontal([ + Constraint::Min(10), + Constraint::Percentage(50), + Constraint::Percentage(50), + Constraint::Min(10), + ]) + .areas(main_area); + + let list_baudrates = List::new(self.baudrate.to_vecstr()) + .block(Block::bordered().title("Baudrates")) + .style(Style::default().fg(Color::White)) + .highlight_style(Style::default().add_modifier(Modifier::ITALIC)) + .highlight_symbol(">>") + .repeat_highlight_symbol(true); + let list_ports = List::new(self.port_list.to_vecstr()) + .block(Block::bordered().title("COM Ports")) + .style(Style::default().fg(Color::White)) + .highlight_style(Style::default().add_modifier(Modifier::UNDERLINED)) + .highlight_symbol(">>") + .repeat_highlight_symbol(true); + + // frame.render_widget(list_ports, area_ports); + // frame.render_widget(list_baudrates, area_baud); + frame.render_stateful_widget(list_baudrates, area_baud, &mut self.baudrate.state); + frame.render_stateful_widget(list_ports, area_ports, &mut self.port_list.state); + // self.render_footer(_status_area, frame); + } + + /// Render the selection footer + fn render_footer(&self, area: Rect, buf: &mut Buffer) { + Paragraph::new( + "Use ↓↑ to move, ←→ to change status widget and ↲ to validate configuration.", + ) + .centered() + .render(area, buf); + } // Handle code after validation +} + +#[allow(clippy::missing_docs_in_private_items)] +impl AppInfo {} + +#[allow(clippy::missing_docs_in_private_items)] +const fn alternate_colors(i: usize) -> Color { + if i % 2 == 0 { + NORMAL_ROW_BG + } else { + ALT_ROW_BG_COLOR + } +} From 8f8e4e4f6eefe39271f299ef63adf4da3b13f12e Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 22 Sep 2024 00:50:37 +0200 Subject: [PATCH 2/9] Updates todo/readme --- README.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/README.md b/README.md index 7f5a58b..b3684b7 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,28 @@ Simple tinySA to Workbench converter +# First window +> Selection + +Starts with the most likely com port selected (last used, then usual suspect, then port 0) +Enter selects it (in the validation sense) +Selects the first likely baudrate (same algo) +Enter selects it +Selects the validate text box + +First selection should be enter, then with L/R U/D (or mouse?) you can change the params +(P) to select a port (B) to select a baudrate (Enter) to be put on the selection + +# Second window +> Customisation + +Tab/L/R for navigation, Enter to change a parameter +Starts with selected and either (L/R/U/D) to be put on the fields + +# Third window +> Result + +Show a progress bar, then show a nice message with a prompt to ask where to save, then exits # References From 5ed8d3a7a91cb1cfc89729c1363f2ff22b85fe92 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 22 Sep 2024 23:12:17 +0200 Subject: [PATCH 3/9] First menu done --- src/structs.rs | 9 ++ src/ui.rs | 323 +++++++++++++++++++++++++++++++++++++------------ 2 files changed, 253 insertions(+), 79 deletions(-) diff --git a/src/structs.rs b/src/structs.rs index a07eac0..ccc43b3 100644 --- a/src/structs.rs +++ b/src/structs.rs @@ -23,3 +23,12 @@ pub enum TinyError { #[error("A runtime error occured :\n{0}")] TUIRuntimeError(color_eyre::eyre::Error), } + +#[allow(missing_docs, clippy::missing_docs_in_private_items)] +/// The direction the input was received, usefull for menu where R/L U/D give similar results and implementation +pub(crate) enum InputDirection { + Up, + Down, + Right, + Left, +} diff --git a/src/ui.rs b/src/ui.rs index 796998d..d774a8f 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -4,7 +4,7 @@ use color_eyre::{owo_colors::OwoColorize, Result}; use ratatui::{ buffer::Buffer, crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind}, - layout::{Constraint, Layout, Rect}, + layout::{Constraint, Direction, Layout, Rect}, style::{ palette::tailwind::{BLUE, GREEN, SLATE}, Color, Modifier, Style, Stylize, @@ -13,13 +13,16 @@ use ratatui::{ text::Line, widgets::{ Block, Borders, HighlightSpacing, List, ListDirection, ListItem, ListState, Padding, - Paragraph, StatefulWidget, Widget, Wrap, + Paragraph, ScrollDirection, StatefulWidget, Widget, Wrap, }, DefaultTerminal, Frame, }; use serialport::SerialPortInfo; -use strum::EnumIter; -use strum::IntoEnumIterator; +use std::{cmp::min, fmt::Pointer, iter::Iterator}; +use strum::{EnumCount, EnumIter, EnumProperty}; +use strum::{FromRepr, IntoEnumIterator}; + +use crate::structs::InputDirection; /// The header style const HEADER_STYLE: Style = Style::new().fg(SLATE.c100).bg(BLUE.c800); @@ -31,6 +34,10 @@ const ALT_ROW_BG_COLOR: Color = SLATE.c900; const SELECTED_STYLE: Style = Style::new().bg(SLATE.c800).add_modifier(Modifier::BOLD); /// Foreground color const TEXT_FG_COLOR: Color = SLATE.c200; +/// Color of a selected border +const SELECTED_COLOR: Color = Color::White; +/// Color of an unselected item +const UNSELECTED_COLOR: Color = Color::DarkGray; /// This struct holds the current state of the app. #[derive(Debug)] @@ -41,8 +48,135 @@ pub(crate) struct AppInfo { baudrate: BaudRateList, /// The list of ports port_list: PortList, + /// State of the configuration, akin to tab or window + flow_state: AppState, + // /// Selected item + // item_selected: ItemSelectedState + /// A debug message string + status_message: String, } +// #[derive(ItemSelectedState)] +// /// The item currently selected + +#[derive(Debug)] +/// The inner state of the app, useful for display and keystrokes +enum AppState { + /// Initial config, baudrate and port + InitialConfig(SelectedConfig), + /// Final config, frequencies and points + FinalConfig(SelectedFinalConfig), + /// Popup for text entering + Popup, + /// Save window + Finished, +} + +impl Default for AppState { + fn default() -> Self { + Self::InitialConfig(SelectedConfig::default()) + } +} + +/// Shortcut for move right +macro_rules! mright { + ($v:ident, $cname:ident,$fname:ident) => { + Some(AppState::$cname( + $fname::from_repr(min($v + 1, $fname::COUNT - 1)).unwrap(), + )) + }; +} + +/// Shortcut to move left +macro_rules! mleft { + ($v:ident, $cname:ident,$fname:ident) => { + if $v == 0 { + None + } else { + Some(AppState::$cname($fname::from_repr($v - 1).unwrap())) + } + }; +} + +impl AppInfo { + /// Goes to the next menu depending on the position in the program + fn next_menu(&mut self, direction: InputDirection) { + if let Some(s) = match self.flow_state { + AppState::InitialConfig(ref r) => { + let v = *r as usize; + match direction { + InputDirection::Right => mright!(v, InitialConfig, SelectedConfig), + InputDirection::Left => mleft!(v, InitialConfig, SelectedConfig), + _ => None, + } + } + AppState::FinalConfig(ref r) => { + let v = *r as usize; + match direction { + InputDirection::Right => mright!(v, FinalConfig, SelectedFinalConfig), + InputDirection::Left => mleft!(v, FinalConfig, SelectedFinalConfig), + _ => None, + } + } + AppState::Popup => None, + AppState::Finished => None, + } { + self.flow_state = s; + } + } +} + +/// The selected item in the config +#[derive(Debug, EnumCount, FromRepr, Clone, Copy)] +enum SelectedConfig { + /// Selects the ports + Port, + /// Selects the baudrate + Baudrate, + // /// Selects to proceed + // Proceed, +} + +impl Default for SelectedConfig { + fn default() -> Self { + Self::Port + } +} + +/// The selected item in the final menu +#[derive(Debug, EnumCount, FromRepr, Copy, Clone)] +enum SelectedFinalConfig { + /// Selects the start frequency + StartFreq, + /// Selects the final frequency + FinalFreq, + /// Selects the number of points + Points, + // /// Selects to proceed + // Proceed, +} + +impl Default for SelectedFinalConfig { + fn default() -> Self { + Self::StartFreq + } +} + +// impl SelectedFinalConfig { +// fn change_menu(&mut self, direction: InputDirection) { +// match direction { +// InputDirection::Right => match self { +// SelectedFinalConfig::StartFreq => Self::FinalFreq, +// SelectedFinalConfig::FinalFreq => Self::Points, +// SelectedFinalConfig::Points => Self::Proceed, +// SelectedFinalConfig::Proceed => (), +// }, +// InputDirection::Left => todo!(), +// _ => (), +// } +// } +// } + /// The list of all baudrates selectables #[derive(Debug)] struct BaudRateList { @@ -61,43 +195,27 @@ impl BaudRateList { .map(|i| format!("{}", *i as usize)) .collect() } - // fn to_itemlist(&self) -> Vec { - // self.baudrates - // .iter() - // .map(|i| ListItemformat!("{}", *i as usize)) - // .collect() - // } - /// Pick the baudrate above - fn above(&mut self) { - // self.selected = (self.selected + 1) % self.baudrates.len(); - self.state.select_previous(); - } - - /// Pick the baudrate below - fn below(&mut self) { - // self.selected = (self.selected - 1) % self.baudrates.len(); - self.state.select_next(); + /// Change the cursor position on the baudrates + fn change_cursor(&mut self, direction: InputDirection) { + match direction { + InputDirection::Down => self.state.select_next(), + InputDirection::Up => self.state.select_previous(), + _ => (), + } } } impl Default for BaudRateList { fn default() -> Self { Self { - selected: 3, + selected: 0, baudrates: BaudRate::iter().collect::>(), - state: ListState::default(), + state: ListState::default().with_selected(Some(3)), } } } -// impl Iterator for BaudRateList { -// type Item = &'str; - -// fn next(&mut self) -> Option { -// todo!() -// } -// } /// A list of possible baudrates #[derive(Debug, EnumIter, Copy, Clone)] enum BaudRate { @@ -132,20 +250,29 @@ impl PortList { Self { ports, selected, - state: ListState::default(), + state: ListState::default().with_selected(Some(selected)), } } /// Convert the list of ports - /// TODO: Remove the clone part + // TODO: Remove the clone part fn to_vecstr(&self) -> Vec { self.ports.clone() } + + /// Change the selected item + fn change_cursor(&mut self, direction: InputDirection) { + match direction { + InputDirection::Up => self.state.select_previous(), + InputDirection::Down => self.state.select_next(), + _ => (), + } + } } /// Try to guess the best port to preselect fn find_best_port(ports: &[String]) -> usize { - let best_ports = ["/dev/ttyACM0", "COM3", "COM5"]; + let best_ports = ["/dev/ttyACM0", "COM3", "COM5", "/dev/ttyS16"]; for port in best_ports { if let Some(p) = ports.iter().position(|v| v == port) { return p; @@ -161,6 +288,8 @@ impl AppInfo { should_quit: false, baudrate: BaudRateList::default(), port_list: PortList::from_serial(info), + flow_state: AppState::default(), + status_message: String::new(), } } @@ -171,9 +300,10 @@ impl AppInfo { } match key.code { KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true, - // KeyCode::Char('h') | KeyCode::Left => self.baudrate. - KeyCode::Char('j') | KeyCode::Down => self.baudrate.above(), - KeyCode::Char('k') | KeyCode::Up => self.baudrate.below(), + KeyCode::Char('j') | KeyCode::Down => self.change_cursor_position(InputDirection::Down), + KeyCode::Char('k') | KeyCode::Up => self.change_cursor_position(InputDirection::Up), + KeyCode::Char('h') | KeyCode::Left => self.next_menu(InputDirection::Left), + KeyCode::Char('l') | KeyCode::Right => self.next_menu(InputDirection::Right), // KeyCode::Char('g') | KeyCode::Home => self.select_first(), // KeyCode::Char('G') | KeyCode::End => self.select_last(), // KeyCode::Enter => { @@ -197,68 +327,103 @@ impl AppInfo { Ok(()) } - // fn init_config(&self) -> &Buffer { - // let [_title_area, main_area, _status_area] = Layout::vertical([ - // Constraint::Length(3), - // Constraint::Min(10), - // Constraint::Length(3), - // ]) - // .areas(frame.area()); - // let [_, area_ports, area_baud, _] = Layout::horizontal([ - // Constraint::Min(10), - // Constraint::Percentage(50), - // Constraint::Percentage(50), - // Constraint::Min(10), - // ]) - // .areas(main_area); - // main_area - // } + /// Initialisation of the config window + fn init_config(&mut self) { + // self.flow_state = AppState::InitialConfig(); + } /// Draw the config info // TODO: This config doesn't need to be reinit every frame fn draw_config(&mut self, frame: &mut Frame) { - let [_title_area, main_area, _status_area] = Layout::vertical([ - Constraint::Length(3), + let [title_area, main_area, status_area] = Layout::vertical([ + Constraint::Length(2), Constraint::Min(10), - Constraint::Length(3), + // Constraint::Min(8), + // Constraint::Length(3), + Constraint::Length(1), ]) .areas(frame.area()); let [_, area_ports, area_baud, _] = Layout::horizontal([ - Constraint::Min(10), + Constraint::Min(7), Constraint::Percentage(50), Constraint::Percentage(50), - Constraint::Min(10), + Constraint::Min(7), ]) .areas(main_area); - - let list_baudrates = List::new(self.baudrate.to_vecstr()) - .block(Block::bordered().title("Baudrates")) - .style(Style::default().fg(Color::White)) - .highlight_style(Style::default().add_modifier(Modifier::ITALIC)) - .highlight_symbol(">>") - .repeat_highlight_symbol(true); + let (b_color, p_color) = match self.flow_state { + AppState::InitialConfig(SelectedConfig::Port) => (UNSELECTED_COLOR, SELECTED_COLOR), + AppState::InitialConfig(SelectedConfig::Baudrate) => (SELECTED_COLOR, UNSELECTED_COLOR), + _ => unreachable!(), + }; let list_ports = List::new(self.port_list.to_vecstr()) - .block(Block::bordered().title("COM Ports")) - .style(Style::default().fg(Color::White)) - .highlight_style(Style::default().add_modifier(Modifier::UNDERLINED)) - .highlight_symbol(">>") + .block(Block::bordered().title("COM Ports").border_style(p_color)) + .style(Style::default().fg(p_color)) + .highlight_style( + Style::default() + .add_modifier(Modifier::ITALIC) + .bg(Color::Blue), + ) .repeat_highlight_symbol(true); - - // frame.render_widget(list_ports, area_ports); - // frame.render_widget(list_baudrates, area_baud); - frame.render_stateful_widget(list_baudrates, area_baud, &mut self.baudrate.state); + let list_baudrates = List::new(self.baudrate.to_vecstr()) + .block(Block::bordered().title("Baudrates").border_style(b_color)) + .style(Style::default().fg(b_color)) + .highlight_style( + Style::default() + .add_modifier(Modifier::ITALIC) + .bg(Color::Blue), + ) + .repeat_highlight_symbol(true); + self.status_message = format!("{:?} ", self.flow_state); frame.render_stateful_widget(list_ports, area_ports, &mut self.port_list.state); - // self.render_footer(_status_area, frame); + frame.render_stateful_widget(list_baudrates, area_baud, &mut self.baudrate.state); + frame.render_widget(Paragraph::new(self.status_message.clone()), title_area); + self.render_footer(frame, status_area) } /// Render the selection footer - fn render_footer(&self, area: Rect, buf: &mut Buffer) { - Paragraph::new( - "Use ↓↑ to move, ←→ to change status widget and ↲ to validate configuration.", - ) - .centered() - .render(area, buf); - } // Handle code after validation + fn render_footer(&self, frame: &mut Frame, area: Rect) { + frame.render_widget( + Paragraph::new( + "Use ↓↑ to move, ←→ to change status widget and ↲ to validate configuration.", + ) + .centered(), + area, + ); + } + + /// A directionnal input was received + fn change_cursor_position(&mut self, direction: InputDirection) { + //Where in the menus are we + match self.flow_state { + AppState::InitialConfig(ref selected_menu) => { + // self.status_message = format!( + // "{:?} {:?} {:?}", + // selected_menu, self.baudrate.state, self.port_list.state + // ); + match selected_menu { + SelectedConfig::Baudrate => self.baudrate.change_cursor(direction), + SelectedConfig::Port => self.port_list.change_cursor(direction), + } + } + AppState::FinalConfig(ref selected_menu) => match selected_menu { + SelectedFinalConfig::StartFreq => todo!(), + SelectedFinalConfig::FinalFreq => todo!(), + SelectedFinalConfig::Points => todo!(), + }, + AppState::Popup => (), + AppState::Finished => (), + } + } + + // /// Change the selected menu + // fn change_menu(&mut self, direction: InputDirection) { + // match self.flow_state { + // AppState::InitialConfig(ref menu) => self, + // AppState::FinalConfig(_) => todo!(), + // AppState::Popup => (), + // AppState::Finished => (), + // } + // } // Handle code after validation } #[allow(clippy::missing_docs_in_private_items)] From 373062374e23035ece372027bea52c6ce1361f08 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 23 Sep 2024 02:37:06 +0200 Subject: [PATCH 4/9] Refactor --- .cargo/config.toml | 2 + Cargo.toml | 11 ++ src/scan.rs | 6 +- src/structs.rs | 26 ++++ src/ui.rs | 368 ++++++++++++++++++++++++++++++++------------- 5 files changed, 308 insertions(+), 105 deletions(-) create mode 100644 .cargo/config.toml diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..1ddbba2 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[build] +rustflags = ["-Clink-arg=-fuse-ld=mold"] diff --git a/Cargo.toml b/Cargo.toml index 7f91205..9e24215 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,3 +16,14 @@ ratatui = "0.28.1" serialport = "4.5.0" strum = { version = "0.26.3", features = ["derive"] } thiserror = "1.0.63" +tui-textarea = "0.6.1" + +[profile.release] +opt-level = "z" +strip = true +lto = true +codegen-units = 1 +panic = "abort" + +[profile.dev] +debug = 0 diff --git a/src/scan.rs b/src/scan.rs index a6842d0..271dcbd 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -125,9 +125,9 @@ fn scanraw(port: &mut Box) -> Result<(), TinyError> { // let mut s = String::new(); // let d = f.read_to_string(&mut s)?; // println!("{}", s); - // let v = hex::decode(&s[..s.len() - 1]).unwrap(); + // let v = hex::decode(&s[..s.len() - 1]).?(); // println!("{:?}", v); - // parse_data(v).unwrap(); + // parse_data(v)?; unsafe { send_raw(port, &format!("scanraw {} {} {}\r", START, STOP, POINTS)) } wait_sync(SHORT_WAIT); read_scanraw(port)?; @@ -194,7 +194,7 @@ pub fn parse_data(v: Vec) -> Result<(), TinyError> { let data = &v[begining + 1..end]; for (i, slice) in data.chunks_exact(3).enumerate() { let s: &[u8; 3] = &[slice[0], slice[1], slice[2]]; - let d = DataPoint::unpack(s).unwrap(); + let d = DataPoint::unpack(s)?; // println!( // "{} {} {} -> {} : {}", // x, diff --git a/src/structs.rs b/src/structs.rs index ccc43b3..31b8fa6 100644 --- a/src/structs.rs +++ b/src/structs.rs @@ -22,6 +22,10 @@ pub enum TinyError { /// A runtime error occured #[error("A runtime error occured :\n{0}")] TUIRuntimeError(color_eyre::eyre::Error), + + /// An error occured while trying to parse the result + #[error("An error occured while trying to parse the result")] + TUIPackingError(#[from] packed_struct::PackingError), } #[allow(missing_docs, clippy::missing_docs_in_private_items)] @@ -32,3 +36,25 @@ pub(crate) enum InputDirection { Right, Left, } + +/// All implementation of errors happening while in the UI +#[derive(Error, Debug)] +pub enum TinyUIError { + /// An error due to bad menuing implementation + #[error("An error occured while selecting a menu item")] + MenuSelectionError, + + /// An error due to bad initialization + #[error("The item list ({0}) wasn't initialyzed ({2}:{1})")] + UninitializedItemList(&'static str, u32, &'static str), + + /// An error occured while proccesing the key events + #[error("An error occured while proccesing the key events")] + KeyPress(#[from] std::io::Error), +} + +// impl TinyUIError { +// pub(crate) fn uninitialized_item_list_error(list: &'static str) -> Self { +// Self::UninitializedItemList(list, line!(), file!()) +// } +// } diff --git a/src/ui.rs b/src/ui.rs index d774a8f..f0e83e8 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -7,7 +7,7 @@ use ratatui::{ layout::{Constraint, Direction, Layout, Rect}, style::{ palette::tailwind::{BLUE, GREEN, SLATE}, - Color, Modifier, Style, Stylize, + Color, Modifier, Style, Styled, Stylize, }, symbols, text::Line, @@ -18,11 +18,17 @@ use ratatui::{ DefaultTerminal, Frame, }; use serialport::SerialPortInfo; -use std::{cmp::min, fmt::Pointer, iter::Iterator}; +use std::{ + borrow::{Borrow, BorrowMut}, + cmp::min, + fmt::Pointer, + iter::Iterator, +}; use strum::{EnumCount, EnumIter, EnumProperty}; use strum::{FromRepr, IntoEnumIterator}; +use tui_textarea::{Input, Key, TextArea}; -use crate::structs::InputDirection; +use crate::structs::{InputDirection, TinyError, TinyUIError}; /// The header style const HEADER_STYLE: Style = Style::new().fg(SLATE.c100).bg(BLUE.c800); @@ -41,7 +47,7 @@ const UNSELECTED_COLOR: Color = Color::DarkGray; /// This struct holds the current state of the app. #[derive(Debug)] -pub(crate) struct AppInfo { +pub(crate) struct AppInfo<'a> { /// Wether the app sould immediately quit should_quit: bool, /// The list of baudrates @@ -50,8 +56,8 @@ pub(crate) struct AppInfo { port_list: PortList, /// State of the configuration, akin to tab or window flow_state: AppState, - // /// Selected item - // item_selected: ItemSelectedState + /// The list of menu item generated + menu_items: MenuItems<'a>, /// A debug message string status_message: String, } @@ -82,7 +88,8 @@ impl Default for AppState { macro_rules! mright { ($v:ident, $cname:ident,$fname:ident) => { Some(AppState::$cname( - $fname::from_repr(min($v + 1, $fname::COUNT - 1)).unwrap(), + $fname::from_repr(min($v + 1, $fname::COUNT - 1)) + .ok_or(TinyUIError::MenuSelectionError)?, )) }; } @@ -93,36 +100,113 @@ macro_rules! mleft { if $v == 0 { None } else { - Some(AppState::$cname($fname::from_repr($v - 1).unwrap())) + Some(AppState::$cname( + $fname::from_repr($v - 1).ok_or(TinyUIError::MenuSelectionError)?, + )) } }; } -impl AppInfo { +impl<'a> AppInfo<'a> { /// Goes to the next menu depending on the position in the program - fn next_menu(&mut self, direction: InputDirection) { + fn next_menu(&mut self, direction: InputDirection) -> Result<(), TinyUIError> { if let Some(s) = match self.flow_state { AppState::InitialConfig(ref r) => { let v = *r as usize; - match direction { + let s = match direction { InputDirection::Right => mright!(v, InitialConfig, SelectedConfig), InputDirection::Left => mleft!(v, InitialConfig, SelectedConfig), _ => None, - } + }; + self.update_color()?; + s } AppState::FinalConfig(ref r) => { let v = *r as usize; - match direction { + let s = match direction { InputDirection::Right => mright!(v, FinalConfig, SelectedFinalConfig), InputDirection::Left => mleft!(v, FinalConfig, SelectedFinalConfig), _ => None, - } + }; + self.update_color()?; + s } AppState::Popup => None, AppState::Finished => None, } { self.flow_state = s; } + Ok(()) + } + + /// Put an item a specified color + fn change_color(&mut self, list: List<'a>, color: Color) -> Option> { + Some( + list.block(Block::bordered().border_style(color)) + .style(Style::default().fg(color)), + ) + } + + /// Progress in the flow of the program + fn next_step(&mut self) { + match self.flow_state { + AppState::InitialConfig(_) => { + self.flow_state = AppState::FinalConfig(SelectedFinalConfig::default()) + } + AppState::FinalConfig(_) => self.flow_state = AppState::Finished, + AppState::Popup => todo!(), + AppState::Finished => todo!(), + } + } + + /// Update all the colors + fn update_color(&mut self) -> Result<(), TinyUIError> { + match self.flow_state { + AppState::InitialConfig(ref c) => { + let (p_c, b_c) = match c { + SelectedConfig::Baudrate => (UNSELECTED_COLOR, SELECTED_COLOR), + SelectedConfig::Port => (SELECTED_COLOR, UNSELECTED_COLOR), + }; + let (p, b) = + ( + self.menu_items.portlist.take().ok_or( + TinyUIError::UninitializedItemList("Port List", line!(), file!()), + )?, + self.menu_items.baudlist.take().ok_or( + TinyUIError::UninitializedItemList("Port List", line!(), file!()), + )?, + ); + self.menu_items.portlist = self.change_color(p, p_c); + self.menu_items.baudlist = self.change_color(b, b_c); + self.status_message = format!("{:?}", self.menu_items.portlist); + } + AppState::FinalConfig(ref c) => { + let (mif_color, maf_color, poi_color) = match self.flow_state { + AppState::FinalConfig(SelectedFinalConfig::StartFreq) => { + (SELECTED_COLOR, UNSELECTED_COLOR, UNSELECTED_COLOR) + } + AppState::FinalConfig(SelectedFinalConfig::FinalFreq) => { + (UNSELECTED_COLOR, SELECTED_COLOR, UNSELECTED_COLOR) + } + AppState::FinalConfig(SelectedFinalConfig::Points) => { + (UNSELECTED_COLOR, UNSELECTED_COLOR, SELECTED_COLOR) + } + _ => unreachable!(), + }; + + // let (mif_menu, maf_menu, poi_menu) = ( + // self.menu_items.min_frequency.take()?, + // self.menu_items.max_frequency.take()?, + // self.menu_items.points.take()?, + // ); + // self.change_color(mif_menu, mif_color); + // self.change_color(maf_menu, maf_color); + // self.change_color(poi_menu, poi_color); + } + AppState::Popup => todo!(), + AppState::Finished => todo!(), + } + Ok(()) } } @@ -162,21 +246,6 @@ impl Default for SelectedFinalConfig { } } -// impl SelectedFinalConfig { -// fn change_menu(&mut self, direction: InputDirection) { -// match direction { -// InputDirection::Right => match self { -// SelectedFinalConfig::StartFreq => Self::FinalFreq, -// SelectedFinalConfig::FinalFreq => Self::Points, -// SelectedFinalConfig::Points => Self::Proceed, -// SelectedFinalConfig::Proceed => (), -// }, -// InputDirection::Left => todo!(), -// _ => (), -// } -// } -// } - /// The list of all baudrates selectables #[derive(Debug)] struct BaudRateList { @@ -255,7 +324,6 @@ impl PortList { } /// Convert the list of ports - // TODO: Remove the clone part fn to_vecstr(&self) -> Vec { self.ports.clone() } @@ -270,6 +338,20 @@ impl PortList { } } +#[derive(Debug, Default)] +/// The static list of all menu items +struct MenuItems<'a> { + /// List of port items + portlist: Option>, + /// List of port items + baudlist: Option>, +} + +// impl<'a> Default for MenuItems<'a> { +// fn default() -> Self { +// Self { portlist: None } +// } +// } /// Try to guess the best port to preselect fn find_best_port(ports: &[String]) -> usize { let best_ports = ["/dev/ttyACM0", "COM3", "COM5", "/dev/ttyS16"]; @@ -281,7 +363,7 @@ fn find_best_port(ports: &[String]) -> usize { 0 } -impl AppInfo { +impl<'a> AppInfo<'a> { /// Create a new app with the port info available pub(crate) fn new(info: Vec) -> Self { Self { @@ -290,35 +372,38 @@ impl AppInfo { port_list: PortList::from_serial(info), flow_state: AppState::default(), status_message: String::new(), + menu_items: MenuItems::default(), } } /// Handle keys while in the first menu - fn handle_start_keys(&mut self, key: KeyEvent) { + fn handle_start_keys(&mut self, key: KeyEvent) -> Result<(), TinyUIError> { if key.kind != KeyEventKind::Press { - return; + return Ok(()); } match key.code { KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true, KeyCode::Char('j') | KeyCode::Down => self.change_cursor_position(InputDirection::Down), KeyCode::Char('k') | KeyCode::Up => self.change_cursor_position(InputDirection::Up), - KeyCode::Char('h') | KeyCode::Left => self.next_menu(InputDirection::Left), - KeyCode::Char('l') | KeyCode::Right => self.next_menu(InputDirection::Right), + KeyCode::Char('h') | KeyCode::Left => self.next_menu(InputDirection::Left)?, + KeyCode::Char('l') | KeyCode::Right => self.next_menu(InputDirection::Right)?, // KeyCode::Char('g') | KeyCode::Home => self.select_first(), // KeyCode::Char('G') | KeyCode::End => self.select_last(), - // KeyCode::Enter => { - // self.toggle_status(); - // } + KeyCode::Enter => { + self.next_step(); + } _ => {} } + Ok(()) } /// Contains the main loop for running the app pub(crate) fn run(&mut self, mut terminal: DefaultTerminal) -> Result<()> { + self.init_config(); loop { - terminal.draw(|v| self.draw_config(v))?; + terminal.draw(|v| self.draw(v).inspect_err(|e| panic!("{}", e)).unwrap())?; if let Event::Key(key) = event::read()? { - self.handle_start_keys(key); + self.handle_start_keys(key)?; }; if self.should_quit { break; @@ -327,19 +412,53 @@ impl AppInfo { Ok(()) } + /// Generic draw loop method + fn draw(&mut self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> { + match self.flow_state { + AppState::InitialConfig(_) => self.draw_config(frame), + AppState::FinalConfig(_) => self.draw_final_config(frame), + // AppState::Popup => todo!(), + // AppState::Finished => todo!(), + _ => todo!(), + } + } /// Initialisation of the config window fn init_config(&mut self) { - // self.flow_state = AppState::InitialConfig(); + // self.menu_items.baudlist.new() + let (b_color, p_color) = match self.flow_state { + AppState::InitialConfig(SelectedConfig::Port) => (UNSELECTED_COLOR, SELECTED_COLOR), + AppState::InitialConfig(SelectedConfig::Baudrate) => (SELECTED_COLOR, UNSELECTED_COLOR), + _ => unreachable!(), + }; + self.menu_items.portlist = Some( + List::new(self.port_list.to_vecstr()) + .block(Block::bordered().title("COM Ports").border_style(p_color)) + .style(Style::default().fg(p_color)) + .highlight_style( + Style::default() + .add_modifier(Modifier::ITALIC) + .bg(Color::Blue), + ) + .repeat_highlight_symbol(true), + ); + self.menu_items.baudlist = Some( + List::new(self.baudrate.to_vecstr()) + .block(Block::bordered().title("Baudrates").border_style(b_color)) + .style(Style::default().fg(b_color)) + .highlight_style( + Style::default() + .add_modifier(Modifier::ITALIC) + .bg(Color::Blue), + ) + .repeat_highlight_symbol(true), + ); } /// Draw the config info - // TODO: This config doesn't need to be reinit every frame - fn draw_config(&mut self, frame: &mut Frame) { + fn draw_config(&mut self, frame: &mut Frame) -> Result<(), TinyUIError> { let [title_area, main_area, status_area] = Layout::vertical([ Constraint::Length(2), Constraint::Min(10), - // Constraint::Min(8), - // Constraint::Length(3), Constraint::Length(1), ]) .areas(frame.area()); @@ -350,36 +469,79 @@ impl AppInfo { Constraint::Min(7), ]) .areas(main_area); - let (b_color, p_color) = match self.flow_state { - AppState::InitialConfig(SelectedConfig::Port) => (UNSELECTED_COLOR, SELECTED_COLOR), - AppState::InitialConfig(SelectedConfig::Baudrate) => (SELECTED_COLOR, UNSELECTED_COLOR), - _ => unreachable!(), - }; - let list_ports = List::new(self.port_list.to_vecstr()) - .block(Block::bordered().title("COM Ports").border_style(p_color)) - .style(Style::default().fg(p_color)) - .highlight_style( - Style::default() - .add_modifier(Modifier::ITALIC) - .bg(Color::Blue), - ) - .repeat_highlight_symbol(true); - let list_baudrates = List::new(self.baudrate.to_vecstr()) - .block(Block::bordered().title("Baudrates").border_style(b_color)) - .style(Style::default().fg(b_color)) - .highlight_style( - Style::default() - .add_modifier(Modifier::ITALIC) - .bg(Color::Blue), - ) - .repeat_highlight_symbol(true); + let list_ports = self + .menu_items + .portlist + .as_ref() + .ok_or(TinyUIError::UninitializedItemList("Port", line!(), file!()))?; + let list_baudrates = self + .menu_items + .baudlist + .as_ref() + .ok_or(TinyUIError::UninitializedItemList("Baud", line!(), file!()))?; self.status_message = format!("{:?} ", self.flow_state); frame.render_stateful_widget(list_ports, area_ports, &mut self.port_list.state); frame.render_stateful_widget(list_baudrates, area_baud, &mut self.baudrate.state); frame.render_widget(Paragraph::new(self.status_message.clone()), title_area); - self.render_footer(frame, status_area) + self.render_footer(frame, status_area); + Ok(()) } + /// Draw the final configuration labels + fn draw_final_config(&mut self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> { + let [title_area, main_area, _, status_area] = Layout::vertical([ + Constraint::Length(2), + Constraint::Length(3), + Constraint::Min(0), + Constraint::Length(1), + ]) + .areas(frame.area()); + let [_, area_minf, area_maxf, area_points, _] = Layout::horizontal([ + Constraint::Min(7), + Constraint::Percentage(30), + Constraint::Percentage(30), + Constraint::Percentage(30), + Constraint::Min(7), + ]) + .areas(main_area); + let (mif_color, maf_color, poi_color) = match self.flow_state { + AppState::FinalConfig(SelectedFinalConfig::StartFreq) => { + (SELECTED_COLOR, UNSELECTED_COLOR, UNSELECTED_COLOR) + } + AppState::FinalConfig(SelectedFinalConfig::FinalFreq) => { + (UNSELECTED_COLOR, SELECTED_COLOR, UNSELECTED_COLOR) + } + AppState::FinalConfig(SelectedFinalConfig::Points) => { + (UNSELECTED_COLOR, UNSELECTED_COLOR, SELECTED_COLOR) + } + _ => unreachable!(), + }; + + self.status_message = format!("{:?} ", self.flow_state); + frame.render_widget( + Paragraph::new("Fin") + .block(Block::bordered()) + .style(mif_color), + area_minf, + ); + frame.render_widget( + Paragraph::new("Fin") + .block(Block::bordered()) + .style(maf_color), + area_maxf, + ); + frame.render_widget( + Paragraph::new("Fin") + .block(Block::bordered()) + .style(poi_color), + area_points, + ); + + // frame.render_stateful_widget(list_baudrates, area_baud, &mut self.baudrate.state); + frame.render_widget(Paragraph::new(self.status_message.clone()), title_area); + self.render_footer(frame, status_area); + Ok(()) + } /// Render the selection footer fn render_footer(&self, frame: &mut Frame, area: Rect) { frame.render_widget( @@ -391,22 +553,37 @@ impl AppInfo { ); } + /// Draw the popup for frequency input + fn draw_freq_popup(&self) { + // self.popup = SelectedFinalConfig::StartFreq; + let mut textarea = TextArea::default(); + textarea.set_block( + Block::default() + .borders(Borders::ALL) + .border_style(Style::default().fg(Color::LightBlue)) + .title("Crossterm Popup Example"), + ); + + let area = Rect { + width: 40, + height: 5, + x: 5, + y: 5, + }; + textarea.set_style(Style::default().fg(Color::Yellow)); + textarea.set_placeholder_style(Style::default()); + textarea.set_placeholder_text("prompt message"); + } + /// A directionnal input was received fn change_cursor_position(&mut self, direction: InputDirection) { - //Where in the menus are we match self.flow_state { - AppState::InitialConfig(ref selected_menu) => { - // self.status_message = format!( - // "{:?} {:?} {:?}", - // selected_menu, self.baudrate.state, self.port_list.state - // ); - match selected_menu { - SelectedConfig::Baudrate => self.baudrate.change_cursor(direction), - SelectedConfig::Port => self.port_list.change_cursor(direction), - } - } + AppState::InitialConfig(ref selected_menu) => match selected_menu { + SelectedConfig::Baudrate => self.baudrate.change_cursor(direction), + SelectedConfig::Port => self.port_list.change_cursor(direction), + }, AppState::FinalConfig(ref selected_menu) => match selected_menu { - SelectedFinalConfig::StartFreq => todo!(), + SelectedFinalConfig::StartFreq => self.draw_freq_popup(), SelectedFinalConfig::FinalFreq => todo!(), SelectedFinalConfig::Points => todo!(), }, @@ -414,26 +591,13 @@ impl AppInfo { AppState::Finished => (), } } - - // /// Change the selected menu - // fn change_menu(&mut self, direction: InputDirection) { - // match self.flow_state { - // AppState::InitialConfig(ref menu) => self, - // AppState::FinalConfig(_) => todo!(), - // AppState::Popup => (), - // AppState::Finished => (), - // } - // } // Handle code after validation } -#[allow(clippy::missing_docs_in_private_items)] -impl AppInfo {} - -#[allow(clippy::missing_docs_in_private_items)] -const fn alternate_colors(i: usize) -> Color { - if i % 2 == 0 { - NORMAL_ROW_BG - } else { - ALT_ROW_BG_COLOR - } -} +// #[allow(clippy::missing_docs_in_private_items)] +// const fn alternate_colors(i: usize) -> Color { +// if i % 2 == 0 { +// NORMAL_ROW_BG +// } else { +// ALT_ROW_BG_COLOR +// } +// } From 051bbb1577f1e356c55c58112e82cb48fae62a0e Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 23 Sep 2024 03:14:13 +0200 Subject: [PATCH 5/9] Another refactor --- src/ui.rs | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/src/ui.rs b/src/ui.rs index f0e83e8..f99acda 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -5,6 +5,7 @@ use ratatui::{ buffer::Buffer, crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind}, layout::{Constraint, Direction, Layout, Rect}, + prelude::BlockExt, style::{ palette::tailwind::{BLUE, GREEN, SLATE}, Color, Modifier, Style, Styled, Stylize, @@ -23,6 +24,7 @@ use std::{ cmp::min, fmt::Pointer, iter::Iterator, + time::Instant, }; use strum::{EnumCount, EnumIter, EnumProperty}; use strum::{FromRepr, IntoEnumIterator}; @@ -113,36 +115,35 @@ impl<'a> AppInfo<'a> { if let Some(s) = match self.flow_state { AppState::InitialConfig(ref r) => { let v = *r as usize; - let s = match direction { + + match direction { InputDirection::Right => mright!(v, InitialConfig, SelectedConfig), InputDirection::Left => mleft!(v, InitialConfig, SelectedConfig), _ => None, - }; - self.update_color()?; - s + } } AppState::FinalConfig(ref r) => { let v = *r as usize; - let s = match direction { + + match direction { InputDirection::Right => mright!(v, FinalConfig, SelectedFinalConfig), InputDirection::Left => mleft!(v, FinalConfig, SelectedFinalConfig), _ => None, - }; - self.update_color()?; - s + } } AppState::Popup => None, AppState::Finished => None, } { self.flow_state = s; } + self.update_color()?; Ok(()) } /// Put an item a specified color - fn change_color(&mut self, list: List<'a>, color: Color) -> Option> { + fn change_color(&mut self, name: &'a str, list: List<'a>, color: Color) -> Option> { Some( - list.block(Block::bordered().border_style(color)) + list.block(Block::bordered().title(name).border_style(color)) .style(Style::default().fg(color)), ) } @@ -176,9 +177,9 @@ impl<'a> AppInfo<'a> { TinyUIError::UninitializedItemList("Port List", line!(), file!()), )?, ); - self.menu_items.portlist = self.change_color(p, p_c); - self.menu_items.baudlist = self.change_color(b, b_c); - self.status_message = format!("{:?}", self.menu_items.portlist); + // self.status_message = format!("{:?} p:{:?} {:?} {:?}", Instant::now(), p_c, b_c, c); + self.menu_items.portlist = self.change_color("COM Ports", p, p_c); + self.menu_items.baudlist = self.change_color("Baudrate", b, b_c); } AppState::FinalConfig(ref c) => { let (mif_color, maf_color, poi_color) = match self.flow_state { @@ -479,7 +480,7 @@ impl<'a> AppInfo<'a> { .baudlist .as_ref() .ok_or(TinyUIError::UninitializedItemList("Baud", line!(), file!()))?; - self.status_message = format!("{:?} ", self.flow_state); + // self.status_message = format!("{:?} ", self.flow_state); frame.render_stateful_widget(list_ports, area_ports, &mut self.port_list.state); frame.render_stateful_widget(list_baudrates, area_baud, &mut self.baudrate.state); frame.render_widget(Paragraph::new(self.status_message.clone()), title_area); From 90676d7c5d877ac4c40fbba96ff4e1209691c999 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 23 Sep 2024 21:40:33 +0200 Subject: [PATCH 6/9] Improvement --- .cargo/config.toml | 2 +- Cargo.toml | 15 +- src/main.rs | 3 +- src/scan.rs | 4 +- src/ui.rs | 699 +++++++++++++++------------------------------ src/ui_struct.rs | 393 +++++++++++++++++++++++++ 6 files changed, 641 insertions(+), 475 deletions(-) create mode 100644 src/ui_struct.rs diff --git a/.cargo/config.toml b/.cargo/config.toml index 1ddbba2..128f924 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,2 @@ [build] -rustflags = ["-Clink-arg=-fuse-ld=mold"] +rustflags = ["-Clink-arg=-fuse-ld=lld"] diff --git a/Cargo.toml b/Cargo.toml index 9e24215..e48432d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,11 +4,10 @@ version = "0.1.0" edition = "2021" [dependencies] -byteorder = "1.5.0" +# byteorder = "1.5.0" clap = { version = "4.5.17", features = ["derive"] } color-eyre = "0.6.3" -csv = "1.3.0" -hex = "0.4.3" +# csv = "1.3.0" memchr = "2.7.4" once_cell = "1.19.0" packed_struct = "0.10.1" @@ -27,3 +26,13 @@ panic = "abort" [profile.dev] debug = 0 + +[profile.windows] +inherits = "release" +opt-level = "z" +debug = false +strip = true +lto = true +codegen-units = 1 +incremental = false +panic = "abort" diff --git a/src/main.rs b/src/main.rs index 79ebbdb..524a5e7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,10 +8,11 @@ mod scan; mod structs; mod ui; +mod ui_struct; use color_eyre::Result; use structs::TinyError; -use ui::AppInfo; +use ui_struct::AppInfo; fn main() -> Result<(), TinyError> { // let args = Args::parse(); diff --git a/src/scan.rs b/src/scan.rs index 271dcbd..e3c4c64 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -1,9 +1,9 @@ //! The "lib" used for all scan related functions /// The default start value for a scan -static START: usize = 240000000; +static START: usize = 240_000_000; /// The default stop value for a scan -static STOP: usize = 959000000; +static STOP: usize = 959_000_000; /// The default number of points static POINTS: usize = 290; //(STOP - START) * 10; /// The default increment (deduced from the number of points) diff --git a/src/ui.rs b/src/ui.rs index f99acda..3134229 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -1,9 +1,13 @@ //! The (minimal) user interface to control the program #![allow(unused_imports)] -use color_eyre::{owo_colors::OwoColorize, Result}; +use clap::builder::Resettable; +use color_eyre::owo_colors::OwoColorize; use ratatui::{ buffer::Buffer, - crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind}, + crossterm::{ + event::{self, Event, KeyCode, KeyEvent, KeyEventKind}, + style::Print, + }, layout::{Constraint, Direction, Layout, Rect}, prelude::BlockExt, style::{ @@ -13,8 +17,8 @@ use ratatui::{ symbols, text::Line, widgets::{ - Block, Borders, HighlightSpacing, List, ListDirection, ListItem, ListState, Padding, - Paragraph, ScrollDirection, StatefulWidget, Widget, Wrap, + Block, Borders, HighlightSpacing, LineGauge, List, ListDirection, ListItem, ListState, + Padding, Paragraph, ScrollDirection, StatefulWidget, Widget, Wrap, }, DefaultTerminal, Frame, }; @@ -24,345 +28,21 @@ use std::{ cmp::min, fmt::Pointer, iter::Iterator, + sync::{Arc, Mutex}, time::Instant, }; use strum::{EnumCount, EnumIter, EnumProperty}; use strum::{FromRepr, IntoEnumIterator}; use tui_textarea::{Input, Key, TextArea}; -use crate::structs::{InputDirection, TinyError, TinyUIError}; - -/// The header style -const HEADER_STYLE: Style = Style::new().fg(SLATE.c100).bg(BLUE.c800); -/// The background color -const NORMAL_ROW_BG: Color = SLATE.c950; -/// Background color for alternated rows -const ALT_ROW_BG_COLOR: Color = SLATE.c900; -/// The style applied to the currently selected item -const SELECTED_STYLE: Style = Style::new().bg(SLATE.c800).add_modifier(Modifier::BOLD); -/// Foreground color -const TEXT_FG_COLOR: Color = SLATE.c200; -/// Color of a selected border -const SELECTED_COLOR: Color = Color::White; -/// Color of an unselected item -const UNSELECTED_COLOR: Color = Color::DarkGray; - -/// This struct holds the current state of the app. -#[derive(Debug)] -pub(crate) struct AppInfo<'a> { - /// Wether the app sould immediately quit - should_quit: bool, - /// The list of baudrates - baudrate: BaudRateList, - /// The list of ports - port_list: PortList, - /// State of the configuration, akin to tab or window - flow_state: AppState, - /// The list of menu item generated - menu_items: MenuItems<'a>, - /// A debug message string - status_message: String, -} - -// #[derive(ItemSelectedState)] -// /// The item currently selected - -#[derive(Debug)] -/// The inner state of the app, useful for display and keystrokes -enum AppState { - /// Initial config, baudrate and port - InitialConfig(SelectedConfig), - /// Final config, frequencies and points - FinalConfig(SelectedFinalConfig), - /// Popup for text entering - Popup, - /// Save window - Finished, -} - -impl Default for AppState { - fn default() -> Self { - Self::InitialConfig(SelectedConfig::default()) - } -} - -/// Shortcut for move right -macro_rules! mright { - ($v:ident, $cname:ident,$fname:ident) => { - Some(AppState::$cname( - $fname::from_repr(min($v + 1, $fname::COUNT - 1)) - .ok_or(TinyUIError::MenuSelectionError)?, - )) - }; -} - -/// Shortcut to move left -macro_rules! mleft { - ($v:ident, $cname:ident,$fname:ident) => { - if $v == 0 { - None - } else { - Some(AppState::$cname( - $fname::from_repr($v - 1).ok_or(TinyUIError::MenuSelectionError)?, - )) - } - }; -} - -impl<'a> AppInfo<'a> { - /// Goes to the next menu depending on the position in the program - fn next_menu(&mut self, direction: InputDirection) -> Result<(), TinyUIError> { - if let Some(s) = match self.flow_state { - AppState::InitialConfig(ref r) => { - let v = *r as usize; - - match direction { - InputDirection::Right => mright!(v, InitialConfig, SelectedConfig), - InputDirection::Left => mleft!(v, InitialConfig, SelectedConfig), - _ => None, - } - } - AppState::FinalConfig(ref r) => { - let v = *r as usize; - - match direction { - InputDirection::Right => mright!(v, FinalConfig, SelectedFinalConfig), - InputDirection::Left => mleft!(v, FinalConfig, SelectedFinalConfig), - _ => None, - } - } - AppState::Popup => None, - AppState::Finished => None, - } { - self.flow_state = s; - } - self.update_color()?; - Ok(()) - } - - /// Put an item a specified color - fn change_color(&mut self, name: &'a str, list: List<'a>, color: Color) -> Option> { - Some( - list.block(Block::bordered().title(name).border_style(color)) - .style(Style::default().fg(color)), - ) - } - - /// Progress in the flow of the program - fn next_step(&mut self) { - match self.flow_state { - AppState::InitialConfig(_) => { - self.flow_state = AppState::FinalConfig(SelectedFinalConfig::default()) - } - AppState::FinalConfig(_) => self.flow_state = AppState::Finished, - AppState::Popup => todo!(), - AppState::Finished => todo!(), - } - } - - /// Update all the colors - fn update_color(&mut self) -> Result<(), TinyUIError> { - match self.flow_state { - AppState::InitialConfig(ref c) => { - let (p_c, b_c) = match c { - SelectedConfig::Baudrate => (UNSELECTED_COLOR, SELECTED_COLOR), - SelectedConfig::Port => (SELECTED_COLOR, UNSELECTED_COLOR), - }; - let (p, b) = - ( - self.menu_items.portlist.take().ok_or( - TinyUIError::UninitializedItemList("Port List", line!(), file!()), - )?, - self.menu_items.baudlist.take().ok_or( - TinyUIError::UninitializedItemList("Port List", line!(), file!()), - )?, - ); - // self.status_message = format!("{:?} p:{:?} {:?} {:?}", Instant::now(), p_c, b_c, c); - self.menu_items.portlist = self.change_color("COM Ports", p, p_c); - self.menu_items.baudlist = self.change_color("Baudrate", b, b_c); - } - AppState::FinalConfig(ref c) => { - let (mif_color, maf_color, poi_color) = match self.flow_state { - AppState::FinalConfig(SelectedFinalConfig::StartFreq) => { - (SELECTED_COLOR, UNSELECTED_COLOR, UNSELECTED_COLOR) - } - AppState::FinalConfig(SelectedFinalConfig::FinalFreq) => { - (UNSELECTED_COLOR, SELECTED_COLOR, UNSELECTED_COLOR) - } - AppState::FinalConfig(SelectedFinalConfig::Points) => { - (UNSELECTED_COLOR, UNSELECTED_COLOR, SELECTED_COLOR) - } - _ => unreachable!(), - }; - - // let (mif_menu, maf_menu, poi_menu) = ( - // self.menu_items.min_frequency.take()?, - // self.menu_items.max_frequency.take()?, - // self.menu_items.points.take()?, - // ); - // self.change_color(mif_menu, mif_color); - // self.change_color(maf_menu, maf_color); - // self.change_color(poi_menu, poi_color); - } - AppState::Popup => todo!(), - AppState::Finished => todo!(), - } - Ok(()) - } -} - -/// The selected item in the config -#[derive(Debug, EnumCount, FromRepr, Clone, Copy)] -enum SelectedConfig { - /// Selects the ports - Port, - /// Selects the baudrate - Baudrate, - // /// Selects to proceed - // Proceed, -} - -impl Default for SelectedConfig { - fn default() -> Self { - Self::Port - } -} - -/// The selected item in the final menu -#[derive(Debug, EnumCount, FromRepr, Copy, Clone)] -enum SelectedFinalConfig { - /// Selects the start frequency - StartFreq, - /// Selects the final frequency - FinalFreq, - /// Selects the number of points - Points, - // /// Selects to proceed - // Proceed, -} - -impl Default for SelectedFinalConfig { - fn default() -> Self { - Self::StartFreq - } -} - -/// The list of all baudrates selectables -#[derive(Debug)] -struct BaudRateList { - /// The selected baudrate (default : BAUD1115200) - selected: usize, - /// The baudrate list - baudrates: Vec, - /// The inner state of the widget - state: ListState, -} -impl BaudRateList { - /// Convert into a vec of strings, this is extremely expensive and shouldn't be done that way - fn to_vecstr(&self) -> Vec { - self.baudrates - .iter() - .map(|i| format!("{}", *i as usize)) - .collect() - } - - /// Change the cursor position on the baudrates - fn change_cursor(&mut self, direction: InputDirection) { - match direction { - InputDirection::Down => self.state.select_next(), - InputDirection::Up => self.state.select_previous(), - _ => (), - } - } -} - -impl Default for BaudRateList { - fn default() -> Self { - Self { - selected: 0, - baudrates: BaudRate::iter().collect::>(), - state: ListState::default().with_selected(Some(3)), - } - } -} - -/// A list of possible baudrates -#[derive(Debug, EnumIter, Copy, Clone)] -enum BaudRate { - BAUD19200 = 19_200, - BAUD38400 = 38_400, - BAUD57600 = 57_600, - BAUD115200 = 115_200, - BAUD230400 = 230_400, - BAUD460800 = 460_800, - BAUD921600 = 921_600, - BAUD1843200 = 1_843_200, - BAUD2000000 = 2_000_000, - BAUD3000000 = 3_000_000, -} - -/// A wrapper over the list of ports -#[derive(Debug)] -pub(crate) struct PortList { - /// The list of found ports - ports: Vec, - /// The currently selected port (doing it that way completly avoids the ) - selected: usize, - /// The inner state of the widget - state: ListState, -} - -impl PortList { - /// Make a port list from a serial reading - pub(crate) fn from_serial(info: Vec) -> Self { - let ports: Vec = info.into_iter().map(|port| port.port_name).collect(); - let selected = find_best_port(&ports); - Self { - ports, - selected, - state: ListState::default().with_selected(Some(selected)), - } - } - - /// Convert the list of ports - fn to_vecstr(&self) -> Vec { - self.ports.clone() - } - - /// Change the selected item - fn change_cursor(&mut self, direction: InputDirection) { - match direction { - InputDirection::Up => self.state.select_previous(), - InputDirection::Down => self.state.select_next(), - _ => (), - } - } -} - -#[derive(Debug, Default)] -/// The static list of all menu items -struct MenuItems<'a> { - /// List of port items - portlist: Option>, - /// List of port items - baudlist: Option>, -} - -// impl<'a> Default for MenuItems<'a> { -// fn default() -> Self { -// Self { portlist: None } -// } -// } -/// Try to guess the best port to preselect -fn find_best_port(ports: &[String]) -> usize { - let best_ports = ["/dev/ttyACM0", "COM3", "COM5", "/dev/ttyS16"]; - for port in best_ports { - if let Some(p) = ports.iter().position(|v| v == port) { - return p; - } - } - 0 -} +use crate::{ + mleft, mright, + structs::{InputDirection, TinyError, TinyUIError}, + ui_struct::{ + AppInfo, AppState, BaudRateList, MenuItems, PortList, SelectedConfig, SelectedFinalConfig, + UIUsize, SELECTED_COLOR, UNSELECTED_COLOR, + }, +}; impl<'a> AppInfo<'a> { /// Create a new app with the port info available @@ -374,33 +54,19 @@ impl<'a> AppInfo<'a> { flow_state: AppState::default(), status_message: String::new(), menu_items: MenuItems::default(), + start_frequency: UIUsize::new(240, 10, 960), + stop_frequency: UIUsize::new(960, 10, 960), + points: UIUsize::new(10000, 100, 1000000), + progress: Arc::new(Mutex::new(0)), } } - /// Handle keys while in the first menu - fn handle_start_keys(&mut self, key: KeyEvent) -> Result<(), TinyUIError> { - if key.kind != KeyEventKind::Press { - return Ok(()); - } - match key.code { - KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true, - KeyCode::Char('j') | KeyCode::Down => self.change_cursor_position(InputDirection::Down), - KeyCode::Char('k') | KeyCode::Up => self.change_cursor_position(InputDirection::Up), - KeyCode::Char('h') | KeyCode::Left => self.next_menu(InputDirection::Left)?, - KeyCode::Char('l') | KeyCode::Right => self.next_menu(InputDirection::Right)?, - // KeyCode::Char('g') | KeyCode::Home => self.select_first(), - // KeyCode::Char('G') | KeyCode::End => self.select_last(), - KeyCode::Enter => { - self.next_step(); - } - _ => {} - } - Ok(()) - } - /// Contains the main loop for running the app - pub(crate) fn run(&mut self, mut terminal: DefaultTerminal) -> Result<()> { - self.init_config(); + pub(crate) fn run( + &mut self, + mut terminal: DefaultTerminal, + ) -> Result<(), color_eyre::eyre::Error> { + self.init_config()?; loop { terminal.draw(|v| self.draw(v).inspect_err(|e| panic!("{}", e)).unwrap())?; if let Event::Key(key) = event::read()? { @@ -419,22 +85,16 @@ impl<'a> AppInfo<'a> { AppState::InitialConfig(_) => self.draw_config(frame), AppState::FinalConfig(_) => self.draw_final_config(frame), // AppState::Popup => todo!(), - // AppState::Finished => todo!(), + AppState::Finished => self.draw_progress(frame), _ => todo!(), } } + /// Initialisation of the config window - fn init_config(&mut self) { - // self.menu_items.baudlist.new() - let (b_color, p_color) = match self.flow_state { - AppState::InitialConfig(SelectedConfig::Port) => (UNSELECTED_COLOR, SELECTED_COLOR), - AppState::InitialConfig(SelectedConfig::Baudrate) => (SELECTED_COLOR, UNSELECTED_COLOR), - _ => unreachable!(), - }; + fn init_config(&mut self) -> Result<(), TinyUIError> { self.menu_items.portlist = Some( List::new(self.port_list.to_vecstr()) - .block(Block::bordered().title("COM Ports").border_style(p_color)) - .style(Style::default().fg(p_color)) + .block(Block::bordered().title("COM Ports")) .highlight_style( Style::default() .add_modifier(Modifier::ITALIC) @@ -444,8 +104,7 @@ impl<'a> AppInfo<'a> { ); self.menu_items.baudlist = Some( List::new(self.baudrate.to_vecstr()) - .block(Block::bordered().title("Baudrates").border_style(b_color)) - .style(Style::default().fg(b_color)) + .block(Block::bordered().title("Baudrates")) .highlight_style( Style::default() .add_modifier(Modifier::ITALIC) @@ -453,6 +112,131 @@ impl<'a> AppInfo<'a> { ) .repeat_highlight_symbol(true), ); + self.update_color() + } + + /// Initialisation of all the ui element for the final configuration elements + fn init_final_config(&mut self) -> Result<(), TinyUIError> { + // /// Create a textbox with a custom title + // macro_rules! text_with_title { + // ($name:expr) => {{ + // let mut texta = TextArea::default(); + // let block = Block::default().title($name); + // texta.set_block(block); + // texta + // }}; + // } + self.menu_items.textboxes = vec![ + // text_with_title!("Start Frequency"), + TextArea::default(), + TextArea::default(), + TextArea::default(), + ]; + self.update_color() + } + + /// Draw the final configuration labels + fn draw_final_config(&mut self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> { + let [title_area, main_area, _, status_area] = Layout::vertical([ + Constraint::Length(2), + Constraint::Length(3), + Constraint::Min(0), + Constraint::Length(1), + ]) + .areas(frame.area()); + let [_, area_minf, area_maxf, area_points, _] = Layout::horizontal([ + Constraint::Min(7), + Constraint::Percentage(30), + Constraint::Percentage(30), + Constraint::Percentage(30), + Constraint::Min(7), + ]) + .areas(main_area); + let (mif_color, maf_color, poi_color) = match self.flow_state { + AppState::FinalConfig(SelectedFinalConfig::StartFreq) => { + (SELECTED_COLOR, UNSELECTED_COLOR, UNSELECTED_COLOR) + } + AppState::FinalConfig(SelectedFinalConfig::FinalFreq) => { + (UNSELECTED_COLOR, SELECTED_COLOR, UNSELECTED_COLOR) + } + AppState::FinalConfig(SelectedFinalConfig::Points) => { + (UNSELECTED_COLOR, UNSELECTED_COLOR, SELECTED_COLOR) + } + _ => unreachable!(), + }; + + // self.status_message = format!("{:?} ", self.flow_state); + frame.render_widget( + Paragraph::new(self.start_frequency.int_to_string()) + .block(Block::bordered().title("Start Frequency")) + .style(mif_color), + area_minf, + ); + frame.render_widget( + Paragraph::new(self.stop_frequency.int_to_string()) + .block(Block::bordered().title("Stop Frequency")) + .style(maf_color), + area_maxf, + ); + frame.render_widget( + Paragraph::new(self.points.int_to_string()) + .block(Block::bordered().title("Points")) + .style(poi_color), + area_points, + ); + + frame.render_widget(Paragraph::new(self.status_message.clone()), title_area); + self.render_footer(frame, status_area); + Ok(()) + } + /// Render the selection footer + fn render_footer(&self, frame: &mut Frame, area: Rect) { + frame.render_widget( + Paragraph::new( + "Use ↓↑ to move, ←→ to change status widget and ↲ to validate configuration.", + ) + .centered(), + area, + ); + } + + /// Initialize the progress window + fn init_progress(&mut self) -> Result<(), TinyUIError> { + self.menu_items.progress_bar = Some( + LineGauge::default() + // .block(title) + .filled_style(Style::default().fg(Color::Blue).bg(Color::Blue)) + .unfilled_style(Style::default().fg(Color::Red).bg(Color::Red)) + .label("Background:"), + ); + Ok(()) + } + + /// Draw the progress, updates as the progress is being done + fn draw_progress(&self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> { + // let title = title_block("Blue / red only background"); + let [title_area, main_area, status_area] = Layout::vertical([ + Constraint::Length(2), + Constraint::Min(10), + Constraint::Length(1), + ]) + .areas(frame.area()); + let [_, area_ports, area_baud, _] = Layout::horizontal([ + Constraint::Min(7), + Constraint::Percentage(50), + Constraint::Percentage(50), + Constraint::Min(7), + ]) + .areas(main_area); + // frame.render_widget( + // Paragraph::new(self.points.int_to_string()) + // .block(Block::bordered()) + // .style(poi_color), + // area_points, + // ); + Ok(()) + // .ratio(self.progress); + // .render(area, buf); } /// Draw the config info @@ -488,93 +272,37 @@ impl<'a> AppInfo<'a> { Ok(()) } - /// Draw the final configuration labels - fn draw_final_config(&mut self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> { - let [title_area, main_area, _, status_area] = Layout::vertical([ - Constraint::Length(2), - Constraint::Length(3), - Constraint::Min(0), - Constraint::Length(1), - ]) - .areas(frame.area()); - let [_, area_minf, area_maxf, area_points, _] = Layout::horizontal([ - Constraint::Min(7), - Constraint::Percentage(30), - Constraint::Percentage(30), - Constraint::Percentage(30), - Constraint::Min(7), - ]) - .areas(main_area); - let (mif_color, maf_color, poi_color) = match self.flow_state { - AppState::FinalConfig(SelectedFinalConfig::StartFreq) => { - (SELECTED_COLOR, UNSELECTED_COLOR, UNSELECTED_COLOR) + /// Handle keys while in the first menu + fn handle_start_keys(&mut self, key: KeyEvent) -> Result<(), TinyUIError> { + if key.kind != KeyEventKind::Press { + return Ok(()); + } + match key.code { + KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true, + KeyCode::Char('j') | KeyCode::Down => self.change_cursor_position(InputDirection::Down), + KeyCode::Char('k') | KeyCode::Up => self.change_cursor_position(InputDirection::Up), + KeyCode::Char('h') | KeyCode::Left => self.next_menu(InputDirection::Left)?, + KeyCode::Char('l') | KeyCode::Right => self.next_menu(InputDirection::Right)?, + v @ (KeyCode::Char('0') + | KeyCode::Char('1') + | KeyCode::Char('2') + | KeyCode::Char('3') + | KeyCode::Char('4') + | KeyCode::Char('5') + | KeyCode::Char('6') + | KeyCode::Char('7') + | KeyCode::Char('8') + | KeyCode::Char('a')) => { + self.status_message = format!("{:?}", v); + } // KeyCode::Char('g') | KeyCode::Home => self.select_first(), + // KeyCode::Char('G') | KeyCode::End => self.select_last(), + KeyCode::Enter => { + self.next_step()?; } - AppState::FinalConfig(SelectedFinalConfig::FinalFreq) => { - (UNSELECTED_COLOR, SELECTED_COLOR, UNSELECTED_COLOR) - } - AppState::FinalConfig(SelectedFinalConfig::Points) => { - (UNSELECTED_COLOR, UNSELECTED_COLOR, SELECTED_COLOR) - } - _ => unreachable!(), - }; - - self.status_message = format!("{:?} ", self.flow_state); - frame.render_widget( - Paragraph::new("Fin") - .block(Block::bordered()) - .style(mif_color), - area_minf, - ); - frame.render_widget( - Paragraph::new("Fin") - .block(Block::bordered()) - .style(maf_color), - area_maxf, - ); - frame.render_widget( - Paragraph::new("Fin") - .block(Block::bordered()) - .style(poi_color), - area_points, - ); - - // frame.render_stateful_widget(list_baudrates, area_baud, &mut self.baudrate.state); - frame.render_widget(Paragraph::new(self.status_message.clone()), title_area); - self.render_footer(frame, status_area); + _ => {} + } Ok(()) } - /// Render the selection footer - fn render_footer(&self, frame: &mut Frame, area: Rect) { - frame.render_widget( - Paragraph::new( - "Use ↓↑ to move, ←→ to change status widget and ↲ to validate configuration.", - ) - .centered(), - area, - ); - } - - /// Draw the popup for frequency input - fn draw_freq_popup(&self) { - // self.popup = SelectedFinalConfig::StartFreq; - let mut textarea = TextArea::default(); - textarea.set_block( - Block::default() - .borders(Borders::ALL) - .border_style(Style::default().fg(Color::LightBlue)) - .title("Crossterm Popup Example"), - ); - - let area = Rect { - width: 40, - height: 5, - x: 5, - y: 5, - }; - textarea.set_style(Style::default().fg(Color::Yellow)); - textarea.set_placeholder_style(Style::default()); - textarea.set_placeholder_text("prompt message"); - } /// A directionnal input was received fn change_cursor_position(&mut self, direction: InputDirection) { @@ -584,21 +312,56 @@ impl<'a> AppInfo<'a> { SelectedConfig::Port => self.port_list.change_cursor(direction), }, AppState::FinalConfig(ref selected_menu) => match selected_menu { - SelectedFinalConfig::StartFreq => self.draw_freq_popup(), - SelectedFinalConfig::FinalFreq => todo!(), - SelectedFinalConfig::Points => todo!(), + SelectedFinalConfig::StartFreq => self.start_frequency.change_value(direction), + SelectedFinalConfig::FinalFreq => self.stop_frequency.change_value(direction), + SelectedFinalConfig::Points => self.points.change_value(direction), }, AppState::Popup => (), AppState::Finished => (), } } -} -// #[allow(clippy::missing_docs_in_private_items)] -// const fn alternate_colors(i: usize) -> Color { -// if i % 2 == 0 { -// NORMAL_ROW_BG -// } else { -// ALT_ROW_BG_COLOR -// } -// } + /// Goes to the next menu depending on the position in the program + fn next_menu(&mut self, direction: InputDirection) -> Result<(), TinyUIError> { + if let Some(s) = match self.flow_state { + AppState::InitialConfig(ref r) => { + let v = *r as usize; + + match direction { + InputDirection::Right => mright!(v, InitialConfig, SelectedConfig), + InputDirection::Left => mleft!(v, InitialConfig, SelectedConfig), + _ => None, + } + } + AppState::FinalConfig(ref r) => { + let v = *r as usize; + + match direction { + InputDirection::Right => mright!(v, FinalConfig, SelectedFinalConfig), + InputDirection::Left => mleft!(v, FinalConfig, SelectedFinalConfig), + _ => None, + } + } + AppState::Popup => None, + AppState::Finished => None, + } { + self.flow_state = s; + } + self.update_color()?; + Ok(()) + } + + /// Progress in the flow of the program + fn next_step(&mut self) -> Result<(), TinyUIError> { + match self.flow_state { + AppState::InitialConfig(_) => { + self.flow_state = AppState::FinalConfig(SelectedFinalConfig::default()); + self.init_final_config()?; + } + AppState::FinalConfig(_) => self.flow_state = AppState::Finished, + AppState::Popup => todo!(), + AppState::Finished => todo!(), + } + Ok(()) + } +} diff --git a/src/ui_struct.rs b/src/ui_struct.rs new file mode 100644 index 0000000..afa34f3 --- /dev/null +++ b/src/ui_struct.rs @@ -0,0 +1,393 @@ +//! All ui structures and utility functions + +//! The (minimal) user interface to control the program +#![allow(unused_imports)] +use clap::builder::Resettable; +use color_eyre::{owo_colors::OwoColorize, Result}; +use ratatui::{ + buffer::Buffer, + crossterm::{ + event::{self, Event, KeyCode, KeyEvent, KeyEventKind}, + style::Print, + }, + layout::{Constraint, Direction, Layout, Rect}, + prelude::BlockExt, + style::{ + palette::tailwind::{BLUE, GREEN, SLATE}, + Color, Modifier, Style, Styled, Stylize, + }, + symbols, + text::Line, + widgets::{ + Block, Borders, Chart, HighlightSpacing, LineGauge, List, ListDirection, ListItem, + ListState, Padding, Paragraph, ScrollDirection, StatefulWidget, Widget, Wrap, + }, + DefaultTerminal, Frame, +}; +use serialport::SerialPortInfo; +use std::{ + borrow::{Borrow, BorrowMut}, + cmp::min, + fmt::Pointer, + iter::Iterator, + ops::Add, + sync::{Arc, Mutex}, + time::Instant, +}; +use strum::{EnumCount, EnumIter, EnumProperty}; +use strum::{FromRepr, IntoEnumIterator}; +use tui_textarea::{Input, Key, TextArea}; + +use crate::structs::{InputDirection, TinyUIError}; + +/// The header style +const HEADER_STYLE: Style = Style::new().fg(SLATE.c100).bg(BLUE.c800); +/// The background color +const NORMAL_ROW_BG: Color = SLATE.c950; +/// Background color for alternated rows +const ALT_ROW_BG_COLOR: Color = SLATE.c900; +/// The style applied to the currently selected item +const SELECTED_STYLE: Style = Style::new().bg(SLATE.c800).add_modifier(Modifier::BOLD); +/// Foreground color +const TEXT_FG_COLOR: Color = SLATE.c200; +/// Color of a selected border +pub(crate) const SELECTED_COLOR: Color = Color::White; +/// Color of an unselected item +pub(crate) const UNSELECTED_COLOR: Color = Color::DarkGray; + +/// This struct holds the current state of the app. +#[derive(Debug)] +pub(crate) struct AppInfo<'a> { + /// Wether the app sould immediately quit + pub(crate) should_quit: bool, + /// The list of baudrates + pub(crate) baudrate: BaudRateList, + /// The list of ports + pub(crate) port_list: PortList, + /// State of the configuration, akin to tab or window + pub(crate) flow_state: AppState, + /// The list of menu item generated + pub(crate) menu_items: MenuItems<'a>, + /// A debug message string + pub(crate) status_message: String, + /// The start frequency + pub(crate) start_frequency: UIUsize, + /// The stop frequency + pub(crate) stop_frequency: UIUsize, + /// The number of points + pub(crate) points: UIUsize, + /// Global progress + pub(crate) progress: Arc>, +} + +#[derive(Debug)] +pub(crate) struct UIUsize { + /// Current value held by the usize + value: usize, + /// Increment by witch it can be upped + increment: usize, + /// Max value to clamp it to + clamp: usize, +} + +impl UIUsize { + /// Change the value depending on selection + pub(crate) fn change_value(&mut self, direction: InputDirection) { + match direction { + InputDirection::Up => self.value = self.value.add(self.increment).clamp(0, self.clamp), + InputDirection::Down => self.value = self.value.saturating_sub(self.increment), + _ => (), + } + } + + /// Create a new UIUsize, usefull for TUI manipulation + pub(crate) fn new(value: usize, increment: usize, clamp: usize) -> Self { + Self { + value, + increment, + clamp, + } + } + + /// Convert to a string with the litteral value + pub(crate) fn int_to_string(&self) -> String { + format!("{}", self.value) + } + + /// Convert to mhz multiplying it by 1_000_000 + pub(crate) fn mhz_to_string(&self) -> String { + format!("{}", self.value * 1000000) + } +} + +#[derive(Debug)] +/// The inner state of the app, useful for display and keystrokes +pub(crate) enum AppState { + /// Initial config, baudrate and port + InitialConfig(SelectedConfig), + /// Final config, frequencies and points + FinalConfig(SelectedFinalConfig), + /// Popup for text entering + Popup, + /// Save window + Finished, +} + +impl Default for AppState { + fn default() -> Self { + Self::InitialConfig(SelectedConfig::default()) + } +} + +#[macro_export] +/// Shortcut for move right +macro_rules! mright { + ($v:ident, $cname:ident,$fname:ident) => { + Some(AppState::$cname( + $fname::from_repr(min(($v + 1), $fname::COUNT - 1)) + .ok_or(TinyUIError::MenuSelectionError)?, + )) + }; +} + +#[macro_export] +/// Shortcut to move left +macro_rules! mleft { + ($v:ident, $cname:ident,$fname:ident) => { + if $v == 0 { + None + } else { + Some(AppState::$cname( + $fname::from_repr($v - 1).ok_or(TinyUIError::MenuSelectionError)?, + )) + } + }; +} +/// The selected item in the config +#[derive(Debug, EnumCount, FromRepr, Clone, Copy)] +pub(crate) enum SelectedConfig { + /// Selects the ports + Port, + /// Selects the baudrate + Baudrate, + // /// Selects to proceed + // Proceed, +} + +impl Default for SelectedConfig { + fn default() -> Self { + Self::Port + } +} + +/// The selected item in the final menu +#[derive(Debug, EnumCount, FromRepr, Copy, Clone)] +pub(crate) enum SelectedFinalConfig { + /// Selects the start frequency + StartFreq, + /// Selects the final frequency + FinalFreq, + /// Selects the number of points + Points, + // /// Selects to proceed + // Proceed, +} + +impl Default for SelectedFinalConfig { + fn default() -> Self { + Self::StartFreq + } +} + +/// The list of all baudrates selectables +#[derive(Debug)] +pub(crate) struct BaudRateList { + /// The selected baudrate (default : BAUD1115200) + pub(crate) selected: usize, + /// The baudrate list + pub(crate) baudrates: Vec, + /// The inner state of the widget + pub(crate) state: ListState, +} +impl BaudRateList { + /// Convert into a vec of strings, this is extremely expensive and shouldn't be done that way + pub(crate) fn to_vecstr(&self) -> Vec { + self.baudrates + .iter() + .map(|i| format!("{}", *i as usize)) + .collect() + } + + /// Change the cursor position on the baudrates + pub(crate) fn change_cursor(&mut self, direction: InputDirection) { + match direction { + InputDirection::Down => self.state.select_next(), + InputDirection::Up => self.state.select_previous(), + _ => (), + } + } +} + +impl Default for BaudRateList { + fn default() -> Self { + Self { + selected: 0, + baudrates: BaudRate::iter().collect::>(), + state: ListState::default().with_selected(Some(3)), + } + } +} + +/// A list of possible baudrates +#[derive(Debug, EnumIter, Copy, Clone)] +pub(crate) enum BaudRate { + BAUD19200 = 19_200, + BAUD38400 = 38_400, + BAUD57600 = 57_600, + BAUD115200 = 115_200, + BAUD230400 = 230_400, + BAUD460800 = 460_800, + BAUD921600 = 921_600, + BAUD1843200 = 1_843_200, + BAUD2000000 = 2_000_000, + BAUD3000000 = 3_000_000, +} + +/// A wrapper over the list of ports +#[derive(Debug)] +pub(crate) struct PortList { + /// The list of found ports + pub(crate) ports: Vec, + /// The currently selected port (doing it that way completly avoids the ) + pub(crate) selected: usize, + /// The inner state of the widget + pub(crate) state: ListState, +} + +impl PortList { + /// Make a port list from a serial reading + pub(crate) fn from_serial(info: Vec) -> Self { + let ports: Vec = info.into_iter().map(|port| port.port_name).collect(); + let selected = find_best_port(&ports); + Self { + ports, + selected, + state: ListState::default().with_selected(Some(selected)), + } + } + + /// Convert the list of ports + pub(crate) fn to_vecstr(&self) -> Vec { + self.ports.clone() + } + + /// Change the selected item + pub(crate) fn change_cursor(&mut self, direction: InputDirection) { + match direction { + InputDirection::Up => self.state.select_previous(), + InputDirection::Down => self.state.select_next(), + _ => (), + } + } +} + +#[derive(Debug, Default)] +/// The static list of all menu items +pub(crate) struct MenuItems<'a> { + /// List of port items + pub(crate) portlist: Option>, + /// List of port items + pub(crate) baudlist: Option>, + /// List of all the textboxes + pub(crate) textboxes: Vec>, + /// The progress bar + pub(crate) progress_bar: Option>, + /// Controller info + pub(crate) info: Option>, + /// The final graph + pub(crate) graph: Option>, +} + +/// Try to guess the best port to preselect +fn find_best_port(ports: &[String]) -> usize { + let best_ports = ["/dev/ttyACM0", "COM3", "COM5", "/dev/ttyS16"]; + for port in best_ports { + if let Some(p) = ports.iter().position(|v| v == port) { + return p; + } + } + 0 +} +// #[allow(clippy::missing_docs_in_private_items)] +// const fn alternate_colors(i: usize) -> Color { +// if i % 2 == 0 { +// NORMAL_ROW_BG +// } else { +// ALT_ROW_BG_COLOR +// } +// } +impl<'a> AppInfo<'a> { + /// Put an item a specified color + pub(crate) fn change_color( + &mut self, + name: &'a str, + list: List<'a>, + color: Color, + ) -> Option> { + Some( + list.block(Block::bordered().title(name).border_style(color)) + .style(Style::default().fg(color)), + ) + } +} +impl<'a> AppInfo<'a> { + /// Update all the colors + pub(crate) fn update_color(&mut self) -> Result<(), TinyUIError> { + match self.flow_state { + AppState::InitialConfig(ref c) => { + let (p_c, b_c) = match c { + SelectedConfig::Baudrate => (UNSELECTED_COLOR, SELECTED_COLOR), + SelectedConfig::Port => (SELECTED_COLOR, UNSELECTED_COLOR), + }; + let (p, b) = + ( + self.menu_items.portlist.take().ok_or( + TinyUIError::UninitializedItemList("Port List", line!(), file!()), + )?, + self.menu_items.baudlist.take().ok_or( + TinyUIError::UninitializedItemList("Port List", line!(), file!()), + )?, + ); + // self.status_message = format!("{:?} p:{:?} {:?} {:?}", Instant::now(), p_c, b_c, c); + self.menu_items.portlist = self.change_color("COM Ports", p, p_c); + self.menu_items.baudlist = self.change_color("Baudrate", b, b_c); + } + AppState::FinalConfig(ref c) => { + // let (mif_color, maf_color, poi_color) = match self.flow_state { + let colorlist = match c { + SelectedFinalConfig::StartFreq => { + [SELECTED_COLOR, UNSELECTED_COLOR, UNSELECTED_COLOR] + } + SelectedFinalConfig::FinalFreq => { + [UNSELECTED_COLOR, SELECTED_COLOR, UNSELECTED_COLOR] + } + SelectedFinalConfig::Points => { + [UNSELECTED_COLOR, UNSELECTED_COLOR, SELECTED_COLOR] + } + }; + + for (area, color) in self.menu_items.textboxes.iter_mut().zip(colorlist) { + area.set_block( + Block::default() + .borders(Borders::ALL) + .style(Style::default().fg(color)) + .title(" Inactive (^X to switch) "), + ) + } + } + AppState::Popup => todo!(), + AppState::Finished => todo!(), + } + Ok(()) + } +} From c88ef356b1f9987935b0ec778a87c4c151031b34 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 24 Sep 2024 04:20:28 +0200 Subject: [PATCH 7/9] Finished most of the gui --- src/scan.rs | 176 +++++++++++++++++++---------------------------- src/structs.rs | 5 ++ src/ui.rs | 133 ++++++++++++++++++++++------------- src/ui_struct.rs | 82 +++++++++++++--------- 4 files changed, 210 insertions(+), 186 deletions(-) diff --git a/src/scan.rs b/src/scan.rs index e3c4c64..4483e15 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -24,8 +24,8 @@ use serialport::SerialPort; use std::{ fs::File, io::{BufWriter, Read, Write}, - sync::OnceLock, - thread::sleep, + sync::{Arc, Mutex, OnceLock}, + thread::{self}, time::Duration, }; @@ -44,61 +44,64 @@ pub struct DataPoint { static EOF: OnceLock> = OnceLock::new(); /// Scan a specific range and returns the scan result -pub(crate) fn scan() -> Result<(), TinyError> { - let ports = serialport::available_ports()?; - for p in ports { - println!("{}", p.port_name); - } - let mut port = serialport::new("/dev/ttyACM0", 115_200) +pub(crate) fn scan_with_progress( + progress: Arc>, + scan_info: Arc>, + scan_message: Arc>, + port: String, + start: usize, + stop: usize, + points: usize, +) -> Result<(), TinyError> { + *scan_message.lock().unwrap() = "Oppening connection".to_string(); + let mut port = serialport::new(port, 115_200) .timeout(Duration::from_millis(3000)) .open() .expect("Failed to open port"); + *scan_message.lock().unwrap() = "Initialisation...".to_string(); + *progress.lock().unwrap() = 5.; initialize(&mut port); - println!("{}", send_cmd(&mut port, "help\r", SHORT_WAIT)); - println!("{}", send_cmd(&mut port, "version\r", SHORT_WAIT)); - println!("{}", send_cmd(&mut port, "info\r", SHORT_WAIT)); - println!( - "{}", - send_cmd(&mut port, &format!("zero {}\r", OFFSET), SHORT_WAIT) - ); - println!("{}", send_cmd(&mut port, "leveloffset\r", SHORT_WAIT)); - println!("{}", send_cmd(&mut port, "deviceid\r", SHORT_WAIT)); - println!("{}", send_cmd(&mut port, "vbat offset\r", SHORT_WAIT)); - println!("{}", send_cmd(&mut port, "vbat\r", SHORT_WAIT)); - println!("{}", send_cmd(&mut port, "usart_cfg\r", SHORT_WAIT)); - println!("{}", send_cmd(&mut port, "marker\r", SHORT_WAIT)); + *progress.lock().unwrap() = 15.; + *scan_message.lock().unwrap() = "Acquiring version & info".to_string(); + let v = send_cmd(&mut port, "version\r", SHORT_WAIT); + let i = send_cmd(&mut port, "info\r", SHORT_WAIT); + *scan_info.lock().unwrap() = format!("{}{}", v, i); - println!("{}", send_cmd(&mut port, "sweep\r", SHORT_WAIT)); - println!("{}", send_cmd(&mut port, "mode\r", SHORT_WAIT)); - println!("{}", send_cmd(&mut port, "lna\r", SHORT_WAIT)); + *progress.lock().unwrap() = 16.; + *scan_message.lock().unwrap() = "Setting zero...".to_string(); + send_cmd(&mut port, &format!("zero {}\r", OFFSET), SHORT_WAIT); + // ("{}", send_cmd(&mut port, "leveloffset\r", SHORT_WAIT)); + // ("{}", send_cmd(&mut port, "deviceid\r", SHORT_WAIT)); + // ("{}", send_cmd(&mut port, "usart_cfg\r", SHORT_WAIT)); - println!("{}", send_cmd(&mut port, "pause\r", SHORT_WAIT)); - println!("{}", send_cmd(&mut port, "vbat\r", SHORT_WAIT)); - println!("{}", send_cmd(&mut port, "marker\r", SHORT_WAIT)); - println!("{}", send_cmd(&mut port, "sweep\r", SHORT_WAIT)); - println!("{}", send_cmd(&mut port, "mode high input\r", SHORT_WAIT)); + *progress.lock().unwrap() = 17.; + *scan_message.lock().unwrap() = "Setting up scan & mode".to_string(); + send_cmd(&mut port, "marker\r", SHORT_WAIT); + send_cmd(&mut port, "pause\r", SHORT_WAIT); + send_cmd(&mut port, "mode high input\r", SHORT_WAIT); - println!("{}", send_cmd(&mut port, "sweep\r", SHORT_WAIT)); - println!( - "{}", - send_cmd(&mut port, &format!("sweep start {}\r", START), SHORT_WAIT) + *progress.lock().unwrap() = 18.; + *scan_message.lock().unwrap() = "Setting up sweep".to_string(); + send_cmd(&mut port, &format!("sweep start {}\r", START), SHORT_WAIT); + send_cmd(&mut port, &format!("sweep stop {}\r", STOP), SHORT_WAIT); + + *progress.lock().unwrap() = 20.; + *scan_message.lock().unwrap() = "Starting scan...".to_string(); + send_cmd(&mut port, "sweep\r", SHORT_WAIT); + send_cmd( + &mut port, + &format!("scan {} {} 290 101\r", start, stop), + TIMEOUT, ); - println!( - "{}", - send_cmd(&mut port, &format!("sweep stop {}\r", STOP), SHORT_WAIT) - ); - println!("{}", send_cmd(&mut port, "sweep\r", SHORT_WAIT)); - println!( - "{}", - send_cmd(&mut port, "scan 240000000 959000000 290 101\r", TIMEOUT) - ); - // println!( - // "{}", - // send_cmd(&mut port, &format!("scan {} {} 100 101\r", START, STOP), 50) - // ); - println!("{:?}", scanraw(&mut port)); - println!("{}", send_cmd(&mut port, "resume\r", SHORT_WAIT)); + + *progress.lock().unwrap() = 22.; + scanraw(&mut port, progress.clone(), start, stop, points)?; + + *scan_message.lock().unwrap() = "Scan finished".to_string(); + send_cmd(&mut port, "resume\r", SHORT_WAIT); + + *progress.lock().unwrap() = 100.; wait_sync(LONG_WAIT); Ok(()) } @@ -107,30 +110,26 @@ pub(crate) fn scan() -> Result<(), TinyError> { /// Wait's for a whole timeout for data stuck in the buffer and dumps it fn initialize(port: &mut Box) { wait_sync(SHORT_WAIT); - println!( - "Initializing ... \nUninialized bytes: {:?}", - read_port(port) - ); + read_port(port); wait_sync(SHORT_WAIT) } /// Bad synchronisation method to ensure data is truthfully sent/received fn wait_sync(duration: u64) { - sleep(Duration::from_millis(duration)); + thread::sleep(Duration::from_millis(duration)); } /// Scan raw frequencies -fn scanraw(port: &mut Box) -> Result<(), TinyError> { - // let mut f = File::open("b.txt")?; - // let mut s = String::new(); - // let d = f.read_to_string(&mut s)?; - // println!("{}", s); - // let v = hex::decode(&s[..s.len() - 1]).?(); - // println!("{:?}", v); - // parse_data(v)?; - unsafe { send_raw(port, &format!("scanraw {} {} {}\r", START, STOP, POINTS)) } +fn scanraw( + port: &mut Box, + progress: Arc>, + start: usize, + stop: usize, + points: usize, +) -> Result<(), TinyError> { + unsafe { send_raw(port, &format!("scanraw {} {} {}\r", start, stop, points)) } wait_sync(SHORT_WAIT); - read_scanraw(port)?; + read_scanraw(port, progress, points)?; wait_sync(LONG_WAIT); Ok(()) } @@ -148,7 +147,6 @@ fn send_cmd(port: &mut Box, command: &str, wait: u64) -> String /// This command will produce unknown results if the output buffer is never read unsafe fn send_raw(port: &mut Box, command: &str) { let output = command.as_bytes(); - println!("Sending: {}", command); let _r = port.write(output).expect("Write failed!"); } @@ -164,13 +162,11 @@ fn read_port(port: &mut Box) -> Vec { let finder = EOF.get_or_init(|| memmem::Finder::new("ch>")); while let Ok(r) = port.read(serial_buf.as_mut_slice()) { if let Some(pos) = finder.find(&serial_buf) { - // println!("{:?}", serial_buf); res.extend_from_slice(&serial_buf[..pos]); break; } res.extend_from_slice(&serial_buf[..r]); } - // println!("{:?}", res); res } @@ -178,15 +174,19 @@ fn read_port(port: &mut Box) -> Vec { /// Waits the normal start Character '{' and begins treating data as normal /// /// Returns a struct summerizing the information processed -fn read_scanraw(port: &mut Box) -> Result<(), TinyError> { +fn read_scanraw( + port: &mut Box, + progress: Arc>, + points: usize, +) -> Result<(), TinyError> { let v = read_port(port); // Find the { marking the beggining - parse_data(v) + parse_data(v, progress, points) } /// A utility function used for parsing the raw data of a scan -pub fn parse_data(v: Vec) -> Result<(), TinyError> { - let mut values: Vec = Vec::with_capacity(POINTS); +pub fn parse_data(v: Vec, progress: Arc>, points: usize) -> Result<(), TinyError> { + let mut values: Vec = Vec::with_capacity(points); let mut out = BufWriter::new(File::create("test.csv")?); if let Some(begining) = memchr::memchr(b'{', &v) { // Finds the } marking the end @@ -195,14 +195,6 @@ pub fn parse_data(v: Vec) -> Result<(), TinyError> { for (i, slice) in data.chunks_exact(3).enumerate() { let s: &[u8; 3] = &[slice[0], slice[1], slice[2]]; let d = DataPoint::unpack(s)?; - // println!( - // "{} {} {} -> {} : {}", - // x, - // b1, - // b2, - // d.value, - // u16_to_f64(d.value) - // ); values.push(d.value); writeln!( out, @@ -211,12 +203,6 @@ pub fn parse_data(v: Vec) -> Result<(), TinyError> { u16_to_f64(d.value) // bytes_to_f64(b1, b2) )?; } - println!( - "Found {} values, min: {:?}, max: {:?}", - values.len(), - u16_to_f64(*values.iter().min().unwrap_or(&0)), - u16_to_f64(*values.iter().max().unwrap_or(&0)), - ); Ok(()) } else { Err(TinyError::ParseEnd("}".to_owned())) @@ -239,25 +225,3 @@ fn u16_to_f64(v: u16) -> f64 { // status: ScanStatus, // data: Vec, // } - -// pub enum ScanStatus { -// Success, -// Failure, -// Interrupted, -// } -// loop { -// // println!("{}", send_cmd(&mut port, "0\r")); -// print!("ch> "); -// io::stdout().flush().expect("IO error"); -// let mut input = String::new(); -// match io::stdin().read_line(&mut input) { -// Ok(_) => { -// println!("{}", send_cmd(&mut port, &format!("{}\r", input))); -// } -// Err(e) => println!("Error {}", e), -// } -// // println!("{}", send_cmd(&mut port, "scan 240m 960m 240 11\r")); -// // println!("{}", send_cmd(&mut port, "scanraw 240m 960m 10000\r")); -// // // println!("{}", send_cmd(&mut port, "scanraw 240m 960m 1000\r")); -// // send_cmd(&mut port, "resume\r"); -// } diff --git a/src/structs.rs b/src/structs.rs index 31b8fa6..15bac25 100644 --- a/src/structs.rs +++ b/src/structs.rs @@ -1,4 +1,5 @@ //! All the structs used internally + use thiserror::Error; /// The most common error, exposed to the lib user and end used @@ -51,6 +52,10 @@ pub enum TinyUIError { /// An error occured while proccesing the key events #[error("An error occured while proccesing the key events")] KeyPress(#[from] std::io::Error), + + /// Mutex error likely a data race mishandled + #[error("An error occured while trying to fetch progress")] + Mutex, } // impl TinyUIError { diff --git a/src/ui.rs b/src/ui.rs index 3134229..f88e204 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -1,7 +1,8 @@ //! The (minimal) user interface to control the program #![allow(unused_imports)] use clap::builder::Resettable; -use color_eyre::owo_colors::OwoColorize; +use color_eyre::{owo_colors::OwoColorize, Section}; +use core::time; use ratatui::{ buffer::Buffer, crossterm::{ @@ -29,14 +30,15 @@ use std::{ fmt::Pointer, iter::Iterator, sync::{Arc, Mutex}, - time::Instant, + thread, + time::{Duration, Instant}, }; use strum::{EnumCount, EnumIter, EnumProperty}; use strum::{FromRepr, IntoEnumIterator}; use tui_textarea::{Input, Key, TextArea}; use crate::{ - mleft, mright, + mleft, mright, scan, structs::{InputDirection, TinyError, TinyUIError}, ui_struct::{ AppInfo, AppState, BaudRateList, MenuItems, PortList, SelectedConfig, SelectedFinalConfig, @@ -57,7 +59,9 @@ impl<'a> AppInfo<'a> { start_frequency: UIUsize::new(240, 10, 960), stop_frequency: UIUsize::new(960, 10, 960), points: UIUsize::new(10000, 100, 1000000), - progress: Arc::new(Mutex::new(0)), + progress: Arc::new(Mutex::new(0.)), + scan_info: Arc::new(Mutex::new(String::new())), + scan_message: Arc::new(Mutex::new(String::new())), } } @@ -69,11 +73,14 @@ impl<'a> AppInfo<'a> { self.init_config()?; loop { terminal.draw(|v| self.draw(v).inspect_err(|e| panic!("{}", e)).unwrap())?; - if let Event::Key(key) = event::read()? { - self.handle_start_keys(key)?; - }; - if self.should_quit { - break; + let timeout = Duration::from_millis(16); + if event::poll(timeout)? { + if let Event::Key(key) = event::read()? { + self.handle_start_keys(key)?; + }; + if self.should_quit { + break; + } } } Ok(()) @@ -117,21 +124,7 @@ impl<'a> AppInfo<'a> { /// Initialisation of all the ui element for the final configuration elements fn init_final_config(&mut self) -> Result<(), TinyUIError> { - // /// Create a textbox with a custom title - // macro_rules! text_with_title { - // ($name:expr) => {{ - // let mut texta = TextArea::default(); - // let block = Block::default().title($name); - // texta.set_block(block); - // texta - // }}; - // } - self.menu_items.textboxes = vec![ - // text_with_title!("Start Frequency"), - TextArea::default(), - TextArea::default(), - TextArea::default(), - ]; + self.menu_items.textboxes = vec![Paragraph::new("")]; self.update_color() } @@ -152,6 +145,7 @@ impl<'a> AppInfo<'a> { Constraint::Min(7), ]) .areas(main_area); + // TODO: Move this in the color update let (mif_color, maf_color, poi_color) = match self.flow_state { AppState::FinalConfig(SelectedFinalConfig::StartFreq) => { (SELECTED_COLOR, UNSELECTED_COLOR, UNSELECTED_COLOR) @@ -185,6 +179,7 @@ impl<'a> AppInfo<'a> { area_points, ); + self.update_color()?; frame.render_widget(Paragraph::new(self.status_message.clone()), title_area); self.render_footer(frame, status_area); Ok(()) @@ -205,38 +200,67 @@ impl<'a> AppInfo<'a> { self.menu_items.progress_bar = Some( LineGauge::default() // .block(title) - .filled_style(Style::default().fg(Color::Blue).bg(Color::Blue)) - .unfilled_style(Style::default().fg(Color::Red).bg(Color::Red)) - .label("Background:"), + .filled_style(Style::default().fg(Color::Blue)) + .unfilled_style(Style::default().fg(Color::Red)) + // .filled_style(Style::default().fg(Color::Blue).bg(Color::Blue)) + // .unfilled_style(Style::default().fg(Color::Red).bg(Color::Red)) + .label("Progress:"), ); Ok(()) } /// Draw the progress, updates as the progress is being done - fn draw_progress(&self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> { + fn draw_progress(&mut self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> { // let title = title_block("Blue / red only background"); - let [title_area, main_area, status_area] = Layout::vertical([ - Constraint::Length(2), - Constraint::Min(10), - Constraint::Length(1), + + let [_, main_s, _] = Layout::horizontal([ + Constraint::Min(7), + Constraint::Percentage(90), + Constraint::Min(7), ]) .areas(frame.area()); - let [_, area_ports, area_baud, _] = Layout::horizontal([ - Constraint::Min(7), - Constraint::Percentage(50), - Constraint::Percentage(50), - Constraint::Min(7), + let [title_area, _, main_area, _, progress_area] = Layout::vertical([ + Constraint::Length(3), + // Constraint::Length(1), + Constraint::Length(1), + // Constraint::Length(1), + Constraint::Min(10), + Constraint::Length(1), + Constraint::Length(1), ]) - .areas(main_area); - // frame.render_widget( - // Paragraph::new(self.points.int_to_string()) - // .block(Block::bordered()) - // .style(poi_color), - // area_points, - // ); + .areas(main_s); + let (pb, status, message) = { + let status = self.scan_message.try_lock().unwrap(); + let status = Paragraph::new(status.clone()) + .block(Block::bordered().title("Operation")) + .style(SELECTED_COLOR); + let message = self.scan_info.try_lock().unwrap(); + let message = Paragraph::new(message.clone()) + .block(Block::bordered().title("TinySA Info")) + .style(SELECTED_COLOR); + let progress = self.progress.try_lock().unwrap(); + + let pb = self + .menu_items + .progress_bar + .take() + .ok_or(TinyUIError::UninitializedItemList( + "ProgressBar", + line!(), + file!(), + ))? + .ratio(*progress / 100.); + (pb, status, message) + }; + // let self= pb.clone + frame.render_widget(pb.clone(), progress_area); + frame.render_widget(status, title_area); + frame.render_widget(message, main_area); + // frame.render_widget(Paragraph::new(format!("{:?}", Instant::now())), main_area); + // thread::sleep(Duration::from_millis(100)); + self.menu_items.progress_bar = Some(pb); + // TODO: If progress = 100 move to final step and show S / enter to save G for graph Ok(()) - // .ratio(self.progress); - // .render(area, buf); } /// Draw the config info @@ -358,7 +382,22 @@ impl<'a> AppInfo<'a> { self.flow_state = AppState::FinalConfig(SelectedFinalConfig::default()); self.init_final_config()?; } - AppState::FinalConfig(_) => self.flow_state = AppState::Finished, + AppState::FinalConfig(_) => { + self.flow_state = AppState::Finished; + self.init_progress()?; + // Start the scan + let pmtx = self.progress.clone(); + let mmtx = self.scan_info.clone(); + let cmtx = self.scan_message.clone(); + let port = self.port_list.selected_port(); + let start = self.start_frequency.mhz_to_usize(); + let stop = self.stop_frequency.mhz_to_usize(); + let points = self.points.int_to_usize(); + thread::spawn(move || { + scan::scan_with_progress(pmtx, mmtx, cmtx, port, start, stop, points).unwrap() + }); + // scan::scan_with_progress(pmtx, mmtx, cmtx, port).unwrap(); + } AppState::Popup => todo!(), AppState::Finished => todo!(), } diff --git a/src/ui_struct.rs b/src/ui_struct.rs index afa34f3..efdabab 100644 --- a/src/ui_struct.rs +++ b/src/ui_struct.rs @@ -31,6 +31,7 @@ use std::{ fmt::Pointer, iter::Iterator, ops::Add, + str::FromStr, sync::{Arc, Mutex}, time::Instant, }; @@ -77,9 +78,12 @@ pub(crate) struct AppInfo<'a> { /// The number of points pub(crate) points: UIUsize, /// Global progress - pub(crate) progress: Arc>, + pub(crate) progress: Arc>, + /// Global initialisation data + pub(crate) scan_info: Arc>, + /// Global message + pub(crate) scan_message: Arc>, } - #[derive(Debug)] pub(crate) struct UIUsize { /// Current value held by the usize @@ -115,8 +119,13 @@ impl UIUsize { } /// Convert to mhz multiplying it by 1_000_000 - pub(crate) fn mhz_to_string(&self) -> String { - format!("{}", self.value * 1000000) + pub(crate) fn mhz_to_usize(&self) -> usize { + self.value * 1000000 + } + + /// Output inner value + pub(crate) fn int_to_usize(&self) -> usize { + self.value } } @@ -289,6 +298,11 @@ impl PortList { _ => (), } } + + /// Returns the final selected port + pub(crate) fn selected_port(&self) -> String { + self.ports[self.state.selected().unwrap()].clone() + } } #[derive(Debug, Default)] @@ -299,7 +313,7 @@ pub(crate) struct MenuItems<'a> { /// List of port items pub(crate) baudlist: Option>, /// List of all the textboxes - pub(crate) textboxes: Vec>, + pub(crate) textboxes: Vec>, /// The progress bar pub(crate) progress_bar: Option>, /// Controller info @@ -318,14 +332,7 @@ fn find_best_port(ports: &[String]) -> usize { } 0 } -// #[allow(clippy::missing_docs_in_private_items)] -// const fn alternate_colors(i: usize) -> Color { -// if i % 2 == 0 { -// NORMAL_ROW_BG -// } else { -// ALT_ROW_BG_COLOR -// } -// } + impl<'a> AppInfo<'a> { /// Put an item a specified color pub(crate) fn change_color( @@ -363,27 +370,26 @@ impl<'a> AppInfo<'a> { self.menu_items.baudlist = self.change_color("Baudrate", b, b_c); } AppState::FinalConfig(ref c) => { - // let (mif_color, maf_color, poi_color) = match self.flow_state { - let colorlist = match c { - SelectedFinalConfig::StartFreq => { - [SELECTED_COLOR, UNSELECTED_COLOR, UNSELECTED_COLOR] - } - SelectedFinalConfig::FinalFreq => { - [UNSELECTED_COLOR, SELECTED_COLOR, UNSELECTED_COLOR] - } - SelectedFinalConfig::Points => { - [UNSELECTED_COLOR, UNSELECTED_COLOR, SELECTED_COLOR] - } - }; + // self.status_message = format!("Moo"); + // let colorlist = match c { + // SelectedFinalConfig::StartFreq => { + // [SELECTED_COLOR, UNSELECTED_COLOR, UNSELECTED_COLOR] + // } + // SelectedFinalConfig::FinalFreq => { + // [UNSELECTED_COLOR, SELECTED_COLOR, UNSELECTED_COLOR] + // } + // SelectedFinalConfig::Points => { + // [UNSELECTED_COLOR, UNSELECTED_COLOR, SELECTED_COLOR] + // } + // }; - for (area, color) in self.menu_items.textboxes.iter_mut().zip(colorlist) { - area.set_block( - Block::default() - .borders(Borders::ALL) - .style(Style::default().fg(color)) - .title(" Inactive (^X to switch) "), - ) - } + // for (area, color) in self.menu_items.textboxes.iter_mut().zip(colorlist) { + // .block( + // Block::default() + // // .borders(Borders::ALL) + // .style(Style::default().fg(Color::Blue)), // .title(" Inactive (^X to switch) "), + // ) + // } } AppState::Popup => todo!(), AppState::Finished => todo!(), @@ -391,3 +397,13 @@ impl<'a> AppInfo<'a> { Ok(()) } } + +// /// Create a textbox with a custom title +// macro_rules! text_with_title { +// ($name:expr) => {{ +// let mut texta = TextArea::default(); +// let block = Block::default().title($name); +// texta.set_block(block); +// texta +// }}; +// } From 8fcf27496594d5cc4ae4758b70a7b796c0806039 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 24 Sep 2024 16:32:59 +0200 Subject: [PATCH 8/9] Finishes the scan --- Cargo.toml | 1 + src/main.rs | 5 +- src/scan.rs | 63 +++++----- src/ui.rs | 291 +++++++++++++++++++++++++++++++++-------------- src/ui_struct.rs | 35 ++---- 5 files changed, 254 insertions(+), 141 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e48432d..a0e44e4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ edition = "2021" # byteorder = "1.5.0" clap = { version = "4.5.17", features = ["derive"] } color-eyre = "0.6.3" +human-panic = "2.0.1" # csv = "1.3.0" memchr = "2.7.4" once_cell = "1.19.0" diff --git a/src/main.rs b/src/main.rs index 524a5e7..43a76f7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,15 +11,14 @@ mod ui; mod ui_struct; use color_eyre::Result; +// use human_panic::setup_panic; use structs::TinyError; use ui_struct::AppInfo; fn main() -> Result<(), TinyError> { - // let args = Args::parse(); - // scan() - color_eyre::install()?; let terminal = ratatui::init(); + // setup_panic!(); let ports = serialport::available_ports()?; let app_r = AppInfo::new(ports).run(terminal); diff --git a/src/scan.rs b/src/scan.rs index 4483e15..336ae24 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -45,7 +45,7 @@ static EOF: OnceLock> = OnceLock::new(); /// Scan a specific range and returns the scan result pub(crate) fn scan_with_progress( - progress: Arc>, + progress: Arc>, scan_info: Arc>, scan_message: Arc>, port: String, @@ -59,34 +59,31 @@ pub(crate) fn scan_with_progress( .open() .expect("Failed to open port"); *scan_message.lock().unwrap() = "Initialisation...".to_string(); - *progress.lock().unwrap() = 5.; + *progress.lock().unwrap() = 5; initialize(&mut port); - *progress.lock().unwrap() = 15.; + *progress.lock().unwrap() = 15; *scan_message.lock().unwrap() = "Acquiring version & info".to_string(); let v = send_cmd(&mut port, "version\r", SHORT_WAIT); let i = send_cmd(&mut port, "info\r", SHORT_WAIT); *scan_info.lock().unwrap() = format!("{}{}", v, i); - *progress.lock().unwrap() = 16.; + *progress.lock().unwrap() = 16; *scan_message.lock().unwrap() = "Setting zero...".to_string(); send_cmd(&mut port, &format!("zero {}\r", OFFSET), SHORT_WAIT); - // ("{}", send_cmd(&mut port, "leveloffset\r", SHORT_WAIT)); - // ("{}", send_cmd(&mut port, "deviceid\r", SHORT_WAIT)); - // ("{}", send_cmd(&mut port, "usart_cfg\r", SHORT_WAIT)); - *progress.lock().unwrap() = 17.; + *progress.lock().unwrap() = 17; *scan_message.lock().unwrap() = "Setting up scan & mode".to_string(); send_cmd(&mut port, "marker\r", SHORT_WAIT); send_cmd(&mut port, "pause\r", SHORT_WAIT); send_cmd(&mut port, "mode high input\r", SHORT_WAIT); - *progress.lock().unwrap() = 18.; + *progress.lock().unwrap() = 18; *scan_message.lock().unwrap() = "Setting up sweep".to_string(); send_cmd(&mut port, &format!("sweep start {}\r", START), SHORT_WAIT); send_cmd(&mut port, &format!("sweep stop {}\r", STOP), SHORT_WAIT); - *progress.lock().unwrap() = 20.; + *progress.lock().unwrap() = 20; *scan_message.lock().unwrap() = "Starting scan...".to_string(); send_cmd(&mut port, "sweep\r", SHORT_WAIT); send_cmd( @@ -95,14 +92,14 @@ pub(crate) fn scan_with_progress( TIMEOUT, ); - *progress.lock().unwrap() = 22.; + *progress.lock().unwrap() = 22; scanraw(&mut port, progress.clone(), start, stop, points)?; *scan_message.lock().unwrap() = "Scan finished".to_string(); send_cmd(&mut port, "resume\r", SHORT_WAIT); - *progress.lock().unwrap() = 100.; wait_sync(LONG_WAIT); + *progress.lock().unwrap() = 100; Ok(()) } @@ -122,7 +119,7 @@ fn wait_sync(duration: u64) { /// Scan raw frequencies fn scanraw( port: &mut Box, - progress: Arc>, + progress: Arc>, start: usize, stop: usize, points: usize, @@ -156,6 +153,29 @@ fn read_utf8(port: &mut Box) -> String { } /// Reads the serial port until it reaches EOF +fn read_port_with_progress( + port: &mut Box, + expected: usize, + progress: Arc>, +) -> Vec { + let mut serial_buf: Vec = vec![0; 64]; + let mut res = Vec::new(); + let finder = EOF.get_or_init(|| memmem::Finder::new("ch>")); + while let Ok(r) = port.read(serial_buf.as_mut_slice()) { + *progress.lock().unwrap() = (100usize.saturating_sub( + (80 * (expected.saturating_sub(res.len())).clamp(0, expected)) / expected, + )) + .clamp(20, 99); + if let Some(pos) = finder.find(&serial_buf) { + res.extend_from_slice(&serial_buf[..pos]); + break; + } + res.extend_from_slice(&serial_buf[..r]); + } + res +} + +/// Read port without updating progress fn read_port(port: &mut Box) -> Vec { let mut serial_buf: Vec = vec![0; 256]; let mut res = Vec::new(); @@ -176,16 +196,16 @@ fn read_port(port: &mut Box) -> Vec { /// Returns a struct summerizing the information processed fn read_scanraw( port: &mut Box, - progress: Arc>, + progress: Arc>, points: usize, ) -> Result<(), TinyError> { - let v = read_port(port); + let v = read_port_with_progress(port, points * 3 + 6, progress); // Find the { marking the beggining - parse_data(v, progress, points) + parse_data(v, points) } /// A utility function used for parsing the raw data of a scan -pub fn parse_data(v: Vec, progress: Arc>, points: usize) -> Result<(), TinyError> { +pub fn parse_data(v: Vec, points: usize) -> Result<(), TinyError> { let mut values: Vec = Vec::with_capacity(points); let mut out = BufWriter::new(File::create("test.csv")?); if let Some(begining) = memchr::memchr(b'{', &v) { @@ -216,12 +236,3 @@ pub fn parse_data(v: Vec, progress: Arc>, points: usize) -> Resul fn u16_to_f64(v: u16) -> f64 { (v as f64) / 32. - OFFSET as f64 } - -// /// The result of a scan -// pub struct ScanResult { -// start: usize, -// stop: usize, -// points: usize, -// status: ScanStatus, -// data: Vec, -// } diff --git a/src/ui.rs b/src/ui.rs index f88e204..5ccf950 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -2,24 +2,25 @@ #![allow(unused_imports)] use clap::builder::Resettable; use color_eyre::{owo_colors::OwoColorize, Section}; -use core::time; +use core::{panic, time}; use ratatui::{ buffer::Buffer, crossterm::{ event::{self, Event, KeyCode, KeyEvent, KeyEventKind}, style::Print, }, - layout::{Constraint, Direction, Layout, Rect}, + layout::{Alignment, Constraint, Direction, Layout, Rect}, prelude::BlockExt, style::{ palette::tailwind::{BLUE, GREEN, SLATE}, Color, Modifier, Style, Styled, Stylize, }, - symbols, + symbols::{self, Marker}, text::Line, widgets::{ - Block, Borders, HighlightSpacing, LineGauge, List, ListDirection, ListItem, ListState, - Padding, Paragraph, ScrollDirection, StatefulWidget, Widget, Wrap, + block::Title, Axis, Block, Borders, Chart, Dataset, GraphType, HighlightSpacing, LineGauge, + List, ListDirection, ListItem, ListState, Padding, Paragraph, ScrollDirection, + StatefulWidget, Widget, Wrap, }, DefaultTerminal, Frame, }; @@ -59,7 +60,7 @@ impl<'a> AppInfo<'a> { start_frequency: UIUsize::new(240, 10, 960), stop_frequency: UIUsize::new(960, 10, 960), points: UIUsize::new(10000, 100, 1000000), - progress: Arc::new(Mutex::new(0.)), + progress: Arc::new(Mutex::new(0)), scan_info: Arc::new(Mutex::new(String::new())), scan_message: Arc::new(Mutex::new(String::new())), } @@ -91,9 +92,9 @@ impl<'a> AppInfo<'a> { match self.flow_state { AppState::InitialConfig(_) => self.draw_config(frame), AppState::FinalConfig(_) => self.draw_final_config(frame), - // AppState::Popup => todo!(), AppState::Finished => self.draw_progress(frame), - _ => todo!(), + AppState::EndWindow => self.draw_end_window(frame), + // _ => unimplemented!(), } } @@ -128,6 +129,11 @@ impl<'a> AppInfo<'a> { self.update_color() } + /// Initialisation of all the final ui elements + pub(crate) fn init_end(&self) -> Result<(), TinyUIError> { + Ok(()) + } + /// Draw the final configuration labels fn draw_final_config(&mut self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> { let [title_area, main_area, _, status_area] = Layout::vertical([ @@ -209,60 +215,6 @@ impl<'a> AppInfo<'a> { Ok(()) } - /// Draw the progress, updates as the progress is being done - fn draw_progress(&mut self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> { - // let title = title_block("Blue / red only background"); - - let [_, main_s, _] = Layout::horizontal([ - Constraint::Min(7), - Constraint::Percentage(90), - Constraint::Min(7), - ]) - .areas(frame.area()); - let [title_area, _, main_area, _, progress_area] = Layout::vertical([ - Constraint::Length(3), - // Constraint::Length(1), - Constraint::Length(1), - // Constraint::Length(1), - Constraint::Min(10), - Constraint::Length(1), - Constraint::Length(1), - ]) - .areas(main_s); - let (pb, status, message) = { - let status = self.scan_message.try_lock().unwrap(); - let status = Paragraph::new(status.clone()) - .block(Block::bordered().title("Operation")) - .style(SELECTED_COLOR); - let message = self.scan_info.try_lock().unwrap(); - let message = Paragraph::new(message.clone()) - .block(Block::bordered().title("TinySA Info")) - .style(SELECTED_COLOR); - let progress = self.progress.try_lock().unwrap(); - - let pb = self - .menu_items - .progress_bar - .take() - .ok_or(TinyUIError::UninitializedItemList( - "ProgressBar", - line!(), - file!(), - ))? - .ratio(*progress / 100.); - (pb, status, message) - }; - // let self= pb.clone - frame.render_widget(pb.clone(), progress_area); - frame.render_widget(status, title_area); - frame.render_widget(message, main_area); - // frame.render_widget(Paragraph::new(format!("{:?}", Instant::now())), main_area); - // thread::sleep(Duration::from_millis(100)); - self.menu_items.progress_bar = Some(pb); - // TODO: If progress = 100 move to final step and show S / enter to save G for graph - Ok(()) - } - /// Draw the config info fn draw_config(&mut self, frame: &mut Frame) -> Result<(), TinyUIError> { let [title_area, main_area, status_area] = Layout::vertical([ @@ -296,6 +248,180 @@ impl<'a> AppInfo<'a> { Ok(()) } + /// Draw the progress, updates as the progress is being done + fn draw_progress(&mut self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> { + let [_, main_s, _] = Layout::horizontal([ + Constraint::Min(7), + Constraint::Percentage(90), + Constraint::Min(7), + ]) + .areas(frame.area()); + let [title_area, progress_area, main_area, _, _] = Layout::vertical([ + Constraint::Length(3), + Constraint::Length(1), + Constraint::Min(10), + Constraint::Length(1), + Constraint::Length(1), + ]) + .areas(main_s); + let (pb, status, message) = { + let status = self.scan_message.try_lock().unwrap(); + let status = Paragraph::new(status.clone()) + .block(Block::bordered().title("Operation")) + .style(SELECTED_COLOR); + let message = self.scan_info.try_lock().unwrap(); + let message = Paragraph::new(message.clone()) + .block(Block::bordered().title("TinySA Info")) + .style(SELECTED_COLOR); + let progress = self.progress.try_lock().unwrap(); + + let pb = self + .menu_items + .progress_bar + .take() + .ok_or(TinyUIError::UninitializedItemList( + "ProgressBar", + line!(), + file!(), + ))? + .ratio(*progress as f64 / 100.); + (pb, status, message) + }; + frame.render_widget(pb.clone(), progress_area); + frame.render_widget(status, title_area); + frame.render_widget(message, main_area); + self.menu_items.progress_bar = Some(pb); + if *self.progress.lock().unwrap() >= 100 { + self.next_step()?; + } + Ok(()) + } + + /// Draw the last confirmation window + fn draw_end_window(&mut self, frame: &mut Frame) -> Result<(), TinyUIError> { + let [_, main_s, _] = Layout::horizontal([ + Constraint::Min(7), + Constraint::Percentage(90), + Constraint::Min(7), + ]) + .areas(frame.area()); + let [title_area, main_area, graph_area, _, footer_area] = Layout::vertical([ + Constraint::Length(3), + Constraint::Length(4), + Constraint::Min(10), + Constraint::Length(1), + Constraint::Length(1), + ]) + .areas(main_s); + let status = Paragraph::new(format!( + "The scan ({}Mhz - {}Mhz) of {} points finished sucessfuly", + self.start_frequency.int_to_usize(), + self.stop_frequency.int_to_usize(), + self.points.int_to_usize() + )) + .block(Block::bordered().title("Status")) + .style(SELECTED_COLOR); + // let dataset = Dataset::default() + // .marker(symbols::Marker::HalfBlock) + // .style(Style::new().fg(Color::Blue)) + // .graph_type(GraphType::Bar) + // // a bell curve + // .data(&[ + // (250., -2.9), + // (260., -13.5), + // (270., -41.1), + // (280., -80.1), + // (390., -100.0), + // (500., -80.1), + // (610., -41.1), + // (720., -13.5), + // (830., -2.9), + // (930., -2.9), + // ]); + + // let chart = Chart::new(vec![dataset]) + // .block( + // Block::bordered().title( + // Title::default() + // .content("Bar chart".cyan().bold()) + // .alignment(Alignment::Center), + // ), + // ) + // .x_axis( + // Axis::default() + // .style(Style::default().gray()) + // .bounds([ + // self.start_frequency.mhz_to_usize() as f64, + // self.stop_frequency.mhz_to_usize() as f64, + // ]) + // .labels([ + // self.start_frequency.int_to_string().bold(), + // format!( + // "{}", + // (self.stop_frequency.int_to_usize() + // - self.start_frequency.int_to_usize() / 2) + // ) + // .into(), + // self.stop_frequency.int_to_string().bold(), + // ]), + // ) + // .y_axis( + // Axis::default() + // .style(Style::default().gray()) + // .bounds([-128.0, 0.]) + // .labels(["-128".bold(), "-64".into(), "0".bold()]), + // ); + // // .hidden_legend_constraints((Constraint::Ratio(1, 2), Constraint::Ratio(1, 2))); + + let datasets = vec![Dataset::default() + .name("Heavy") + .marker(Marker::Dot) + .graph_type(GraphType::Scatter) + .style(Style::new().yellow()) + .data(&[ + (1965., -82.), + (1967., -54.), + (1981., -65.), + (1989., -30.), + (1997., -10.), + (2004., -11.), + (2014., -45.), + (2016., -79.), + (2018., -15.), + ])]; + + let chart = Chart::new(datasets) + .block( + Block::bordered().title( + Title::default() + .content("Scatter chart".cyan().bold()) + .alignment(Alignment::Center), + ), + ) + .x_axis( + Axis::default() + .title("Year") + .bounds([1960., 2020.]) + .style(Style::default().fg(Color::Gray)) + .labels(["1960", "1990", "2020"]), + ) + .y_axis( + Axis::default() + .title("Cost") + .bounds([-128., 0.]) + .style(Style::default().fg(Color::Gray)) + .labels(["0", "37 500", "75 000"]), + ) + .hidden_legend_constraints((Constraint::Ratio(1, 2), Constraint::Ratio(1, 2))); + frame.render_widget(chart, graph_area); + let footer = + Paragraph::new("Press ↲ to save the data as a csv or q to exit without saving.") + .centered(); + frame.render_widget(status, title_area); + frame.render_widget(footer, footer_area); + Ok(()) + } + /// Handle keys while in the first menu fn handle_start_keys(&mut self, key: KeyEvent) -> Result<(), TinyUIError> { if key.kind != KeyEventKind::Press { @@ -307,22 +433,10 @@ impl<'a> AppInfo<'a> { KeyCode::Char('k') | KeyCode::Up => self.change_cursor_position(InputDirection::Up), KeyCode::Char('h') | KeyCode::Left => self.next_menu(InputDirection::Left)?, KeyCode::Char('l') | KeyCode::Right => self.next_menu(InputDirection::Right)?, - v @ (KeyCode::Char('0') - | KeyCode::Char('1') - | KeyCode::Char('2') - | KeyCode::Char('3') - | KeyCode::Char('4') - | KeyCode::Char('5') - | KeyCode::Char('6') - | KeyCode::Char('7') - | KeyCode::Char('8') - | KeyCode::Char('a')) => { - self.status_message = format!("{:?}", v); - } // KeyCode::Char('g') | KeyCode::Home => self.select_first(), - // KeyCode::Char('G') | KeyCode::End => self.select_last(), - KeyCode::Enter => { - self.next_step()?; - } + KeyCode::Enter => match self.flow_state { + AppState::Finished => (), + _ => self.next_step()?, + }, _ => {} } Ok(()) @@ -340,7 +454,7 @@ impl<'a> AppInfo<'a> { SelectedFinalConfig::FinalFreq => self.stop_frequency.change_value(direction), SelectedFinalConfig::Points => self.points.change_value(direction), }, - AppState::Popup => (), + AppState::EndWindow => (), AppState::Finished => (), } } @@ -366,7 +480,7 @@ impl<'a> AppInfo<'a> { _ => None, } } - AppState::Popup => None, + AppState::EndWindow => None, AppState::Finished => None, } { self.flow_state = s; @@ -393,13 +507,20 @@ impl<'a> AppInfo<'a> { let start = self.start_frequency.mhz_to_usize(); let stop = self.stop_frequency.mhz_to_usize(); let points = self.points.int_to_usize(); - thread::spawn(move || { - scan::scan_with_progress(pmtx, mmtx, cmtx, port, start, stop, points).unwrap() - }); + // BYPASS + *self.progress.lock().unwrap() = 100; + // thread::spawn(move || { + // scan::scan_with_progress(pmtx, mmtx, cmtx, port, start, stop, points).unwrap() + // }); // scan::scan_with_progress(pmtx, mmtx, cmtx, port).unwrap(); } - AppState::Popup => todo!(), - AppState::Finished => todo!(), + AppState::EndWindow => { + self.should_quit = true; + } + AppState::Finished => { + self.flow_state = AppState::EndWindow; + self.init_end()?; + } } Ok(()) } diff --git a/src/ui_struct.rs b/src/ui_struct.rs index efdabab..a35ebfb 100644 --- a/src/ui_struct.rs +++ b/src/ui_struct.rs @@ -78,7 +78,7 @@ pub(crate) struct AppInfo<'a> { /// The number of points pub(crate) points: UIUsize, /// Global progress - pub(crate) progress: Arc>, + pub(crate) progress: Arc>, /// Global initialisation data pub(crate) scan_info: Arc>, /// Global message @@ -136,8 +136,8 @@ pub(crate) enum AppState { InitialConfig(SelectedConfig), /// Final config, frequencies and points FinalConfig(SelectedFinalConfig), - /// Popup for text entering - Popup, + /// The end window for confirmation + EndWindow, /// Save window Finished, } @@ -324,6 +324,7 @@ pub(crate) struct MenuItems<'a> { /// Try to guess the best port to preselect fn find_best_port(ports: &[String]) -> usize { + // TODO: Try to load from disk then save to disk let best_ports = ["/dev/ttyACM0", "COM3", "COM5", "/dev/ttyS16"]; for port in best_ports { if let Some(p) = ports.iter().position(|v| v == port) { @@ -347,6 +348,7 @@ impl<'a> AppInfo<'a> { ) } } + impl<'a> AppInfo<'a> { /// Update all the colors pub(crate) fn update_color(&mut self) -> Result<(), TinyUIError> { @@ -369,30 +371,9 @@ impl<'a> AppInfo<'a> { self.menu_items.portlist = self.change_color("COM Ports", p, p_c); self.menu_items.baudlist = self.change_color("Baudrate", b, b_c); } - AppState::FinalConfig(ref c) => { - // self.status_message = format!("Moo"); - // let colorlist = match c { - // SelectedFinalConfig::StartFreq => { - // [SELECTED_COLOR, UNSELECTED_COLOR, UNSELECTED_COLOR] - // } - // SelectedFinalConfig::FinalFreq => { - // [UNSELECTED_COLOR, SELECTED_COLOR, UNSELECTED_COLOR] - // } - // SelectedFinalConfig::Points => { - // [UNSELECTED_COLOR, UNSELECTED_COLOR, SELECTED_COLOR] - // } - // }; - - // for (area, color) in self.menu_items.textboxes.iter_mut().zip(colorlist) { - // .block( - // Block::default() - // // .borders(Borders::ALL) - // .style(Style::default().fg(Color::Blue)), // .title(" Inactive (^X to switch) "), - // ) - // } - } - AppState::Popup => todo!(), - AppState::Finished => todo!(), + // TODO: Have all color update here + AppState::FinalConfig(_selected_final_config) => (), + _ => (), } Ok(()) } From 83b78b632c7d2996ccfb64b6fb48386ef8785141 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 24 Sep 2024 21:24:51 +0200 Subject: [PATCH 9/9] First "working" version --- .gitignore | 1 + Cargo.toml | 3 ++ src/main.rs | 2 +- src/scan.rs | 79 +++++++++++++++++++++++----------- src/structs.rs | 70 +++++++++++++++++++++++++++--- src/ui.rs | 109 +++++++++++++++++++++++++++++------------------ src/ui_struct.rs | 106 ++++++++++++++++++++++----------------------- 7 files changed, 244 insertions(+), 126 deletions(-) diff --git a/.gitignore b/.gitignore index 3c68812..365d39a 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,4 @@ Cargo.lock /target *.csv +config.toml diff --git a/Cargo.toml b/Cargo.toml index a0e44e4..510afda 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,7 @@ version = "0.1.0" edition = "2021" [dependencies] +chrono = "0.4.38" # byteorder = "1.5.0" clap = { version = "4.5.17", features = ["derive"] } color-eyre = "0.6.3" @@ -13,9 +14,11 @@ memchr = "2.7.4" once_cell = "1.19.0" packed_struct = "0.10.1" ratatui = "0.28.1" +serde = { version = "1.0.210", features = ["derive"] } serialport = "4.5.0" strum = { version = "0.26.3", features = ["derive"] } thiserror = "1.0.63" +toml = "0.8.19" tui-textarea = "0.6.1" [profile.release] diff --git a/src/main.rs b/src/main.rs index 43a76f7..7a4603d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,7 +4,7 @@ //! and will not offer any scripting capabilities #![warn(missing_docs, clippy::missing_docs_in_private_items)] -#![allow(dead_code)] +// #![allow(dead_code)] mod scan; mod structs; mod ui; diff --git a/src/scan.rs b/src/scan.rs index 336ae24..1e02dc1 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -4,10 +4,6 @@ static START: usize = 240_000_000; /// The default stop value for a scan static STOP: usize = 959_000_000; -/// The default number of points -static POINTS: usize = 290; //(STOP - START) * 10; -/// The default increment (deduced from the number of points) -static INCREMENT: usize = (STOP - START) / POINTS; // 1000/100 /// The offset used for sending data static OFFSET: usize = 128; /// The base delay used inbetween commands @@ -29,6 +25,8 @@ use std::{ time::Duration, }; +use chrono::Local; + /// A single datapoint, using a struct might be overkill but msb/lsb could become a problem in the future #[derive(PackedStruct, Debug)] #[packed_struct(endian = "lsb")] @@ -44,20 +42,26 @@ pub struct DataPoint { static EOF: OnceLock> = OnceLock::new(); /// Scan a specific range and returns the scan result +#[allow(clippy::too_many_arguments)] pub(crate) fn scan_with_progress( progress: Arc>, scan_info: Arc>, scan_message: Arc>, + return_data: Arc>>, port: String, start: usize, stop: usize, points: usize, ) -> Result<(), TinyError> { *scan_message.lock().unwrap() = "Oppening connection".to_string(); - let mut port = serialport::new(port, 115_200) + let port = serialport::new(port, 115_200) .timeout(Duration::from_millis(3000)) - .open() - .expect("Failed to open port"); + .open(); // .expect("Failed to open port"); + if let Err(e) = port { + *scan_message.lock().unwrap() = "Noo".to_string(); + return Err(TinyError::PortConnection(e)); + } + let mut port = port.unwrap(); *scan_message.lock().unwrap() = "Initialisation...".to_string(); *progress.lock().unwrap() = 5; initialize(&mut port); @@ -93,9 +97,16 @@ pub(crate) fn scan_with_progress( ); *progress.lock().unwrap() = 22; - scanraw(&mut port, progress.clone(), start, stop, points)?; + let name = scanraw( + &mut port, + progress.clone(), + return_data.clone(), + start, + stop, + points, + )?; - *scan_message.lock().unwrap() = "Scan finished".to_string(); + *scan_message.lock().unwrap() = format!("Scan saved as {}", name); send_cmd(&mut port, "resume\r", SHORT_WAIT); wait_sync(LONG_WAIT); @@ -120,15 +131,23 @@ fn wait_sync(duration: u64) { fn scanraw( port: &mut Box, progress: Arc>, + return_data: Arc>>, start: usize, stop: usize, points: usize, -) -> Result<(), TinyError> { +) -> Result { unsafe { send_raw(port, &format!("scanraw {} {} {}\r", start, stop, points)) } wait_sync(SHORT_WAIT); - read_scanraw(port, progress, points)?; + let (name, val) = read_scanraw( + port, + progress, + points, + start, + (stop - start) as f64 / points as f64, + )?; + *return_data.lock().unwrap() = val; wait_sync(LONG_WAIT); - Ok(()) + Ok(name) } /// Send a command and reads it to a string @@ -198,16 +217,25 @@ fn read_scanraw( port: &mut Box, progress: Arc>, points: usize, -) -> Result<(), TinyError> { + start: usize, + increment: f64, +) -> Result<(String, Vec<(f64, f64)>), TinyError> { let v = read_port_with_progress(port, points * 3 + 6, progress); // Find the { marking the beggining - parse_data(v, points) + parse_data(v, points, start, increment) } /// A utility function used for parsing the raw data of a scan -pub fn parse_data(v: Vec, points: usize) -> Result<(), TinyError> { - let mut values: Vec = Vec::with_capacity(points); - let mut out = BufWriter::new(File::create("test.csv")?); +pub fn parse_data( + v: Vec, + points: usize, + start: usize, + increment: f64, +) -> Result<(String, Vec<(f64, f64)>), TinyError> { + // let mut values: Vec = Vec::with_capacity(points); + let name = format!("scan_{}.csv", Local::now().format("%Y%m%d %H_%M_%S")); + let mut out = BufWriter::new(File::create(&name)?); + let mut csvdata = Vec::with_capacity(points); if let Some(begining) = memchr::memchr(b'{', &v) { // Finds the } marking the end if let Some(end) = memchr::memchr(b'}', &v) { @@ -215,15 +243,16 @@ pub fn parse_data(v: Vec, points: usize) -> Result<(), TinyError> { for (i, slice) in data.chunks_exact(3).enumerate() { let s: &[u8; 3] = &[slice[0], slice[1], slice[2]]; let d = DataPoint::unpack(s)?; - values.push(d.value); - writeln!( - out, - "{},{}", - (i * INCREMENT + START) as f64 / 1000000., - u16_to_f64(d.value) // bytes_to_f64(b1, b2) - )?; + let (pos, val) = ( + (i as f64 * increment + start as f64) / 1000000., + u16_to_f64(d.value), + ); + + csvdata.push((pos, val)); + writeln!(out, "{},{}", pos, val)?; } - Ok(()) + // TODO: Dont return use mutex + Ok((name, csvdata)) } else { Err(TinyError::ParseEnd("}".to_owned())) } diff --git a/src/structs.rs b/src/structs.rs index 15bac25..1d5b8c5 100644 --- a/src/structs.rs +++ b/src/structs.rs @@ -1,7 +1,15 @@ //! All the structs used internally +use std::{ + fs::File, + io::{Read, Write}, +}; + +use serde::{Deserialize, Serialize}; use thiserror::Error; +use crate::ui_struct::AppInfo; + /// The most common error, exposed to the lib user and end used #[derive(Error, Debug)] pub enum TinyError { @@ -23,10 +31,18 @@ pub enum TinyError { /// A runtime error occured #[error("A runtime error occured :\n{0}")] TUIRuntimeError(color_eyre::eyre::Error), - /// An error occured while trying to parse the result #[error("An error occured while trying to parse the result")] TUIPackingError(#[from] packed_struct::PackingError), + /// The config file couldn't be opened + #[error("The config file couldn't be opened")] + ConfigNotFound, + /// The config file couldn't be parsed as a valid toml + #[error("The config config.toml couldn't be read")] + InvalidConfig(#[from] toml::de::Error), + /// The config file couldn't be parsed as a valid toml + #[error("The config config.toml couldn't be written")] + InvalidDataForConfig(#[from] toml::ser::Error), } #[allow(missing_docs, clippy::missing_docs_in_private_items)] @@ -52,10 +68,10 @@ pub enum TinyUIError { /// An error occured while proccesing the key events #[error("An error occured while proccesing the key events")] KeyPress(#[from] std::io::Error), - - /// Mutex error likely a data race mishandled - #[error("An error occured while trying to fetch progress")] - Mutex, + // /// Mutex error likely a data race mishandled + // #[allow(dead_code)] + // #[error("An error occured while trying to fetch progress")] + // Mutex, } // impl TinyUIError { @@ -63,3 +79,47 @@ pub enum TinyUIError { // Self::UninitializedItemList(list, line!(), file!()) // } // } + +#[derive(Serialize, Deserialize, Debug)] +pub(crate) struct SavedConfig { + /// The default com port + pub(crate) port: String, + /// The default baudrate + pub(crate) baudrate: usize, + /// The default start frequency + pub(crate) start_frequency: usize, + /// The default stop frequency + pub(crate) stop_frequency: usize, + /// The default number of points + pub(crate) points: usize, +} +impl SavedConfig { + /// Create a config from file or returns an error + pub(crate) fn new() -> Result { + if let Ok(mut f) = File::open("config.toml") { + let mut s = String::new(); + f.read_to_string(&mut s)?; + let c = toml::from_str(&s)?; + Ok(c) + } else { + Err(TinyError::ConfigNotFound) + } + } + + /// Save the config with all runtime parameters + pub(crate) fn save(arg: &AppInfo) -> Result<(), TinyUIError> { + let mut f = File::create("config.toml")?; + f.write_all( + toml::to_string(&Self { + port: arg.port_list.selected_port(), + baudrate: arg.baudrate.state.selected().unwrap(), + start_frequency: arg.start_frequency.int_to_usize(), + stop_frequency: arg.stop_frequency.int_to_usize(), + points: arg.points.int_to_usize(), + }) + .unwrap() + .as_bytes(), + )?; + Ok(()) + } +} diff --git a/src/ui.rs b/src/ui.rs index 5ccf950..6e91b0b 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -40,7 +40,7 @@ use tui_textarea::{Input, Key, TextArea}; use crate::{ mleft, mright, scan, - structs::{InputDirection, TinyError, TinyUIError}, + structs::{InputDirection, SavedConfig, TinyError, TinyUIError}, ui_struct::{ AppInfo, AppState, BaudRateList, MenuItems, PortList, SelectedConfig, SelectedFinalConfig, UIUsize, SELECTED_COLOR, UNSELECTED_COLOR, @@ -50,19 +50,36 @@ use crate::{ impl<'a> AppInfo<'a> { /// Create a new app with the port info available pub(crate) fn new(info: Vec) -> Self { + let loaded_conf = SavedConfig::new(); + let (start_frequency, stop_frequency, points) = { + if let Ok(c) = &loaded_conf { + ( + UIUsize::new(c.start_frequency, 10, 960), + UIUsize::new(c.stop_frequency, 10, 960), + UIUsize::new(c.points, 100, 1000000), + ) + } else { + ( + UIUsize::new(240, 10, 960), + UIUsize::new(960, 10, 960), + UIUsize::new(10000, 100, 1000000), + ) + } + }; Self { should_quit: false, - baudrate: BaudRateList::default(), - port_list: PortList::from_serial(info), + baudrate: BaudRateList::from_conf(&loaded_conf), + port_list: PortList::from_serial(info, &loaded_conf), flow_state: AppState::default(), status_message: String::new(), menu_items: MenuItems::default(), - start_frequency: UIUsize::new(240, 10, 960), - stop_frequency: UIUsize::new(960, 10, 960), - points: UIUsize::new(10000, 100, 1000000), + start_frequency, + stop_frequency, + points, progress: Arc::new(Mutex::new(0)), scan_info: Arc::new(Mutex::new(String::new())), scan_message: Arc::new(Mutex::new(String::new())), + return_data: Arc::new(Mutex::new(Vec::new())), } } @@ -94,7 +111,6 @@ impl<'a> AppInfo<'a> { AppState::FinalConfig(_) => self.draw_final_config(frame), AppState::Finished => self.draw_progress(frame), AppState::EndWindow => self.draw_end_window(frame), - // _ => unimplemented!(), } } @@ -305,9 +321,9 @@ impl<'a> AppInfo<'a> { Constraint::Min(7), ]) .areas(frame.area()); - let [title_area, main_area, graph_area, _, footer_area] = Layout::vertical([ + let [title_area, _main_area, graph_area, _, footer_area] = Layout::vertical([ Constraint::Length(3), - Constraint::Length(4), + Constraint::Length(1), Constraint::Min(10), Constraint::Length(1), Constraint::Length(1), @@ -373,50 +389,55 @@ impl<'a> AppInfo<'a> { // ); // // .hidden_legend_constraints((Constraint::Ratio(1, 2), Constraint::Ratio(1, 2))); + // TODO: Don't acquire a mutex at 60Hz + let binding = self.return_data.lock().unwrap(); let datasets = vec![Dataset::default() - .name("Heavy") + // .name("Heavy") .marker(Marker::Dot) .graph_type(GraphType::Scatter) .style(Style::new().yellow()) - .data(&[ - (1965., -82.), - (1967., -54.), - (1981., -65.), - (1989., -30.), - (1997., -10.), - (2004., -11.), - (2014., -45.), - (2016., -79.), - (2018., -15.), - ])]; + .data(&binding)]; let chart = Chart::new(datasets) - .block( - Block::bordered().title( - Title::default() - .content("Scatter chart".cyan().bold()) - .alignment(Alignment::Center), - ), - ) + // .block( + // Block::bordered().title( + // Title::default() + // .content("Scatter chart".cyan().bold()) + // .alignment(Alignment::Center), + // ), + // ) .x_axis( Axis::default() - .title("Year") - .bounds([1960., 2020.]) + // .title("Year") + .bounds([ + self.start_frequency.int_to_usize() as f64, + self.stop_frequency.int_to_usize() as f64, + ]) .style(Style::default().fg(Color::Gray)) - .labels(["1960", "1990", "2020"]), + .labels([ + self.start_frequency.int_to_string(), + format!( + "{}", + (self.stop_frequency.int_to_usize() + - self.start_frequency.int_to_usize()) + / 2 + ), + self.stop_frequency.int_to_string(), + ]), ) .y_axis( Axis::default() - .title("Cost") + // .title("Cost") .bounds([-128., 0.]) .style(Style::default().fg(Color::Gray)) - .labels(["0", "37 500", "75 000"]), - ) - .hidden_legend_constraints((Constraint::Ratio(1, 2), Constraint::Ratio(1, 2))); + .labels(["-128dbm", "-64dbm", "0dbm"]), + ); frame.render_widget(chart, graph_area); - let footer = - Paragraph::new("Press ↲ to save the data as a csv or q to exit without saving.") - .centered(); + let footer = Paragraph::new(format!( + "{}, press ↲ or q to exit", + self.scan_message.lock().unwrap().clone() + )) + .centered(); frame.render_widget(status, title_area); frame.render_widget(footer, footer_area); Ok(()) @@ -500,18 +521,24 @@ impl<'a> AppInfo<'a> { self.flow_state = AppState::Finished; self.init_progress()?; // Start the scan + // TODO: Have a struct to avoid this clusterfk let pmtx = self.progress.clone(); let mmtx = self.scan_info.clone(); let cmtx = self.scan_message.clone(); + let rdata = self.return_data.clone(); let port = self.port_list.selected_port(); let start = self.start_frequency.mhz_to_usize(); let stop = self.stop_frequency.mhz_to_usize(); let points = self.points.int_to_usize(); // BYPASS *self.progress.lock().unwrap() = 100; - // thread::spawn(move || { - // scan::scan_with_progress(pmtx, mmtx, cmtx, port, start, stop, points).unwrap() - // }); + self.save_config()?; + thread::spawn(move || { + let status = scan::scan_with_progress( + pmtx, mmtx, cmtx, rdata, port, start, stop, points, + ); + // TODO: Do something with bad status to avoid false positive + }); // scan::scan_with_progress(pmtx, mmtx, cmtx, port).unwrap(); } AppState::EndWindow => { diff --git a/src/ui_struct.rs b/src/ui_struct.rs index a35ebfb..9fa56c0 100644 --- a/src/ui_struct.rs +++ b/src/ui_struct.rs @@ -1,56 +1,22 @@ //! All ui structures and utility functions //! The (minimal) user interface to control the program -#![allow(unused_imports)] -use clap::builder::Resettable; -use color_eyre::{owo_colors::OwoColorize, Result}; +use color_eyre::Result; use ratatui::{ - buffer::Buffer, - crossterm::{ - event::{self, Event, KeyCode, KeyEvent, KeyEventKind}, - style::Print, - }, - layout::{Constraint, Direction, Layout, Rect}, - prelude::BlockExt, - style::{ - palette::tailwind::{BLUE, GREEN, SLATE}, - Color, Modifier, Style, Styled, Stylize, - }, - symbols, - text::Line, - widgets::{ - Block, Borders, Chart, HighlightSpacing, LineGauge, List, ListDirection, ListItem, - ListState, Padding, Paragraph, ScrollDirection, StatefulWidget, Widget, Wrap, - }, - DefaultTerminal, Frame, + style::{Color, Style}, + widgets::{Block, LineGauge, List, ListState, Paragraph}, }; use serialport::SerialPortInfo; use std::{ - borrow::{Borrow, BorrowMut}, - cmp::min, - fmt::Pointer, iter::Iterator, ops::Add, - str::FromStr, sync::{Arc, Mutex}, - time::Instant, }; -use strum::{EnumCount, EnumIter, EnumProperty}; +use strum::{EnumCount, EnumIter}; use strum::{FromRepr, IntoEnumIterator}; -use tui_textarea::{Input, Key, TextArea}; -use crate::structs::{InputDirection, TinyUIError}; +use crate::structs::{InputDirection, SavedConfig, TinyError, TinyUIError}; -/// The header style -const HEADER_STYLE: Style = Style::new().fg(SLATE.c100).bg(BLUE.c800); -/// The background color -const NORMAL_ROW_BG: Color = SLATE.c950; -/// Background color for alternated rows -const ALT_ROW_BG_COLOR: Color = SLATE.c900; -/// The style applied to the currently selected item -const SELECTED_STYLE: Style = Style::new().bg(SLATE.c800).add_modifier(Modifier::BOLD); -/// Foreground color -const TEXT_FG_COLOR: Color = SLATE.c200; /// Color of a selected border pub(crate) const SELECTED_COLOR: Color = Color::White; /// Color of an unselected item @@ -83,6 +49,8 @@ pub(crate) struct AppInfo<'a> { pub(crate) scan_info: Arc>, /// Global message pub(crate) scan_message: Arc>, + /// Return scan data + pub(crate) return_data: Arc>>, } #[derive(Debug)] pub(crate) struct UIUsize { @@ -211,8 +179,8 @@ impl Default for SelectedFinalConfig { /// The list of all baudrates selectables #[derive(Debug)] pub(crate) struct BaudRateList { - /// The selected baudrate (default : BAUD1115200) - pub(crate) selected: usize, + // /// The selected baudrate (default : BAUD1115200) + // pub(crate) selected: usize, /// The baudrate list pub(crate) baudrates: Vec, /// The inner state of the widget @@ -235,12 +203,27 @@ impl BaudRateList { _ => (), } } + + /// Create a baudrate from a config file + pub(crate) fn from_conf(loaded_conf: &Result) -> BaudRateList { + // TODO: Actually load from baudrate + if let Ok(c) = loaded_conf { + for (i, baud) in BaudRate::iter().enumerate() { + if c.baudrate == baud as usize { + return Self { + state: ListState::default().with_selected(Some(i)), + ..Default::default() + }; + } + } + } + Self::default() + } } impl Default for BaudRateList { fn default() -> Self { Self { - selected: 0, baudrates: BaudRate::iter().collect::>(), state: ListState::default().with_selected(Some(3)), } @@ -267,20 +250,23 @@ pub(crate) enum BaudRate { pub(crate) struct PortList { /// The list of found ports pub(crate) ports: Vec, - /// The currently selected port (doing it that way completly avoids the ) - pub(crate) selected: usize, + // /// The currently selected port (doing it that way completly avoids the ) + // pub(crate) selected: usize, /// The inner state of the widget pub(crate) state: ListState, } impl PortList { /// Make a port list from a serial reading - pub(crate) fn from_serial(info: Vec) -> Self { + pub(crate) fn from_serial( + info: Vec, + saved_config: &Result, + ) -> Self { let ports: Vec = info.into_iter().map(|port| port.port_name).collect(); - let selected = find_best_port(&ports); + let selected = find_best_port(&ports, saved_config); Self { ports, - selected, + // selected, state: ListState::default().with_selected(Some(selected)), } } @@ -316,17 +302,24 @@ pub(crate) struct MenuItems<'a> { pub(crate) textboxes: Vec>, /// The progress bar pub(crate) progress_bar: Option>, - /// Controller info - pub(crate) info: Option>, - /// The final graph - pub(crate) graph: Option>, + // /// Controller info + // pub(crate) info: Option>, + // /// The final graph + // pub(crate) graph: Option>, } /// Try to guess the best port to preselect -fn find_best_port(ports: &[String]) -> usize { +fn find_best_port(ports: &[String], saved_config: &Result) -> usize { // TODO: Try to load from disk then save to disk - let best_ports = ["/dev/ttyACM0", "COM3", "COM5", "/dev/ttyS16"]; - for port in best_ports { + let mut best_ports = vec!["/dev/ttyACM0", "COM3", "COM5", "/dev/ttyS16"]; + let p: Vec<&str> = if let Ok(c) = saved_config { + let mut v = vec![&*c.port]; + v.append(&mut best_ports); + v + } else { + best_ports + }; + for port in p { if let Some(p) = ports.iter().position(|v| v == port) { return p; } @@ -347,6 +340,11 @@ impl<'a> AppInfo<'a> { .style(Style::default().fg(color)), ) } + + /// Save the config with the current runtime variables + pub(crate) fn save_config(&self) -> Result<(), TinyUIError> { + SavedConfig::save(self) + } } impl<'a> AppInfo<'a> {