From e76878f424d72b943713ef84e95e25fada77d79e Mon Sep 17 00:00:00 2001 From: Jack Wills <32690432+mrjackwills@users.noreply.github.com> Date: Sat, 1 Oct 2022 19:57:27 +0000 Subject: [PATCH] refactor: Impl Copy where able to --- .../workflows/create_release_and_build.yml | 6 +- CHANGELOG.md | 2 +- containerised/DOCKERHUB_README.md | 2 +- src/app_data/container_state.rs | 65 +++++++-------- src/app_data/mod.rs | 82 +++++++++++-------- src/app_error.rs | 2 +- src/docker_data/mod.rs | 6 +- src/input_handler/message.rs | 2 +- src/input_handler/mod.rs | 12 +-- src/main.rs | 18 ++-- src/ui/color_match.rs | 10 +-- src/ui/draw_blocks.rs | 28 ++++--- src/ui/gui_state.rs | 9 +- src/ui/mod.rs | 12 +-- 14 files changed, 138 insertions(+), 118 deletions(-) diff --git a/.github/workflows/create_release_and_build.yml b/.github/workflows/create_release_and_build.yml index 83df16e..a398b2c 100644 --- a/.github/workflows/create_release_and_build.yml +++ b/.github/workflows/create_release_and_build.yml @@ -46,7 +46,7 @@ jobs: uses: actions-rs/toolchain@v1 with: toolchain: stable - target: arm-unknown-linux-musleabihf + target: arm-unknown-linux-musleabihf override: true - uses: actions-rs/cargo@v1 with: @@ -61,7 +61,7 @@ jobs: uses: actions-rs/toolchain@v1 with: toolchain: stable - target: x86_64-pc-windows-gnu + target: x86_64-pc-windows-gnu override: true - uses: actions-rs/cargo@v1 with: @@ -86,7 +86,7 @@ jobs: run: | docker build --platform linux/arm/v6,linux/arm64,linux/amd64 \ -t ${{ secrets.DOCKERHUB_USERNAME }}/oxker:latest \ - --push \ + --push \ -f containerised/Dockerfile . - name: Release diff --git a/CHANGELOG.md b/CHANGELOG.md index 9dfa2ef..4d7817b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -118,7 +118,7 @@ ### 2022-04-29 ### Features -+ allow toggling of mouse caputre, to select & copy text with mouse, closes #2, [aec184ea](https://github.com/mrjackwills/oxker/commit/aec184ea22b289e91942a4c3e6a415685884bc47), ++ allow toggling of mouse caputre, to select & copy text with mouse, closes #2, [aec184ea](https://github.com/mrjackwills/oxker/commit/aec184ea22b289e91942a4c3e6a415685884bc47), + show id column, [b10f9274](https://github.com/mrjackwills/oxker/commit/b10f927481c9e38a48c1d4b94e744ec48e8b6ba6), + draw_popup, using enum to draw in one of 9 areas, closes #6, [1017850a](https://github.com/mrjackwills/oxker/commit/1017850a6cc91328abc1127bdb117495f5e909d8), + use a message rx/sx for all docker commands, remove update loop, wait for update message from gui instead, [9b70fdfa](https://github.com/mrjackwills/oxker/commit/9b70fdfad7b38361ebee301bdc2545d3f0dfcf9e), diff --git a/containerised/DOCKERHUB_README.md b/containerised/DOCKERHUB_README.md index bdc6af3..d073b02 100644 --- a/containerised/DOCKERHUB_README.md +++ b/containerised/DOCKERHUB_README.md @@ -2,7 +2,7 @@

oxker

-
+
A simple tui to view & control docker containers

diff --git a/src/app_data/container_state.rs b/src/app_data/container_state.rs index 03c0c1c..bc334c2 100644 --- a/src/app_data/container_state.rs +++ b/src/app_data/container_state.rs @@ -7,7 +7,6 @@ use tui::{ use super::Header; - const ONE_KB: f64 = 1000.0; const ONE_MB: f64 = ONE_KB * 1000.0; const ONE_GB: f64 = ONE_MB * 1000.0; @@ -25,6 +24,7 @@ impl StatefulList { items, } } + pub fn end(&mut self) { let len = self.items.len(); if len > 0 { @@ -83,7 +83,7 @@ impl StatefulList { } /// States of the container -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd)] +#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd)] pub enum State { Dead, Exited, @@ -95,7 +95,7 @@ pub enum State { } impl State { - pub const fn get_color(&self) -> Color { + pub const fn get_color(self) -> Color { match self { Self::Running => Color::Green, Self::Removing => Color::LightRed, @@ -105,15 +105,15 @@ impl State { } } // Dirty way to create order for the state, rather than impl Ord - pub const fn order(&self) -> &'static str { + pub const fn order(self) -> u8 { match self { - Self::Running => "a", - Self::Paused => "b", - Self::Restarting => "c", - Self::Removing => "d", - Self::Exited => "e", - Self::Dead => "f", - Self::Unknown => "g", + Self::Running => 0, + Self::Paused => 1, + Self::Restarting => 2, + Self::Removing => 3, + Self::Exited => 4, + Self::Dead => 5, + Self::Unknown => 6, } } } @@ -162,7 +162,7 @@ impl fmt::Display for State { } /// Items for the container control list -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Copy)] pub enum DockerControls { Pause, Unpause, @@ -172,7 +172,7 @@ pub enum DockerControls { } impl DockerControls { - pub const fn get_color(&self) -> Color { + pub const fn get_color(self) -> Color { match self { Self::Start => Color::Green, Self::Stop => Color::Red, @@ -182,7 +182,8 @@ impl DockerControls { } } - pub fn gen_vec(state: &State) -> Vec { + /// Docker commands available depending on the containers state + pub fn gen_vec(state: State) -> Vec { match state { State::Dead | State::Exited => vec![Self::Start, Self::Restart], State::Paused => vec![Self::Unpause, Self::Stop], @@ -213,7 +214,7 @@ pub trait Stats { /// Struct for frequently updated CPU stats /// So can use custom display formatter /// Use trait Stats for use as generic in draw_chart function -#[derive(Clone, Debug)] +#[derive(Debug, Clone, Copy)] pub struct CpuStats { value: f64, } @@ -266,7 +267,7 @@ impl fmt::Display for CpuStats { /// Struct for frequently updated memory usage stats /// So can use custom display formatter /// Use trait Stats for use as generic in draw_chart function -#[derive(Clone, Debug, Eq)] +#[derive(Debug, Clone, Copy, Eq)] pub struct ByteStats { value: u64, } @@ -303,10 +304,9 @@ impl Stats for ByteStats { } } -// convert from bytes to kB, MB, GB etc +/// convert from bytes to kB, MB, GB etc impl fmt::Display for ByteStats { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // TODO these can be consts outside of this definition let as_f64 = self.value as f64; let p = match as_f64 { x if x >= ONE_GB => format!("{y:.2} GB", y = as_f64 / ONE_GB), @@ -318,6 +318,10 @@ impl fmt::Display for ByteStats { } } + +pub type MemTuple = (Vec<(f64, f64)>, ByteStats, State); +pub type CpuTuple = (Vec<(f64, f64)>, CpuStats, State); + /// Info for each container #[derive(Debug, Clone)] pub struct ContainerItem { @@ -336,13 +340,10 @@ pub struct ContainerItem { pub status: String, } -pub type MemTuple = (Vec<(f64, f64)>, ByteStats, State); -pub type CpuTuple = (Vec<(f64, f64)>, CpuStats, State); - impl ContainerItem { /// Create a new container item pub fn new(id: String, status: String, image: String, state: State, name: String) -> Self { - let mut docker_controls = StatefulList::new(DockerControls::gen_vec(&state)); + let mut docker_controls = StatefulList::new(DockerControls::gen_vec(state)); docker_controls.start(); Self { cpu_stats: VecDeque::with_capacity(60), @@ -361,18 +362,18 @@ impl ContainerItem { } } - /// Find the max value in the last 30 items in the cpu stats vec + /// Find the max value in the cpu stats VecDeque fn max_cpu_stats(&self) -> CpuStats { match self.cpu_stats.iter().max() { - Some(value) => value.clone(), + Some(value) => *value, None => CpuStats::new(0.0), } } - /// Find the max value in the last 30 items in the mem stats vec + /// Find the max value in the mem stats VecDeque fn max_mem_stats(&self) -> ByteStats { match self.mem_stats.iter().max() { - Some(value) => value.clone(), + Some(value) => *value, None => ByteStats::new(0), } } @@ -382,11 +383,11 @@ impl ContainerItem { self.cpu_stats .iter() .enumerate() - .map(|i| (i.0 as f64, i.1.value)) + .map(|i| (i.0 as f64, i.1.value as f64)) .collect::>() } - /// Convert mem stats into a vec for the charts function + /// Convert mem stats into a Vec for the charts function fn get_mem_dataset(&self) -> Vec<(f64, f64)> { self.mem_stats .iter() @@ -400,7 +401,7 @@ impl ContainerItem { ( self.get_cpu_dataset(), self.max_cpu_stats(), - self.state.clone(), + self.state, ) } @@ -409,7 +410,7 @@ impl ContainerItem { ( self.get_mem_dataset(), self.max_mem_stats(), - self.state.clone(), + self.state, ) } @@ -421,7 +422,7 @@ impl ContainerItem { } /// Container information panel headings + widths, for nice pretty formatting -#[derive(Debug)] +#[derive(Debug, Clone, Copy)] pub struct Columns { pub state: (Header, usize), pub status: (Header, usize), @@ -450,4 +451,4 @@ impl Columns { net_tx: (Header::Tx, 5), } } -} +} \ No newline at end of file diff --git a/src/app_data/mod.rs b/src/app_data/mod.rs index 6c7924d..a0ba4d9 100644 --- a/src/app_data/mod.rs +++ b/src/app_data/mod.rs @@ -9,7 +9,7 @@ use crate::{app_error::AppError, parse_args::CliArgs, ui::log_sanitizer}; pub use container_state::*; /// Global app_state, stored in an Arc -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct AppData { args: CliArgs, error: Option, @@ -20,13 +20,13 @@ pub struct AppData { sorted_by: Option<(Header, SortedOrder)>, } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum SortedOrder { Asc, Desc, } -#[derive(Debug, Clone, PartialEq, Hash, Eq)] +#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)] pub enum Header { State, Status, @@ -58,20 +58,19 @@ impl fmt::Display for Header { } impl AppData { - pub fn get_sorted(&self) -> Option<(Header, SortedOrder)> { - self.sorted_by.clone() + pub const fn get_sorted(&self) -> Option<(Header, SortedOrder)> { + self.sorted_by } /// Change the sorted order, also set the selected container state to match new order pub fn set_sorted(&mut self, x: Option<(Header, SortedOrder)>) { self.sorted_by = x; - let id = self.get_selected_container_id(); self.sort_containers(); self.containers.state.select( self.containers .items .iter() - .position(|i| Some(i.id.clone()) == id), + .position(|i| Some(i.id.clone()) == self.get_selected_container_id()), ); } /// Generate a default app_state @@ -106,8 +105,7 @@ impl AppData { .state .selected() { - output = - Some(self.containers.items[index].docker_controls.items[control_index].clone()); + output = Some(self.containers.items[index].docker_controls.items[control_index]); } } output @@ -116,34 +114,42 @@ impl AppData { /// Change selected choice of docker commands of selected container pub fn docker_command_next(&mut self) { if let Some(index) = self.containers.state.selected() { - self.containers.items[index].docker_controls.next(); + if let Some(i) = self.containers.items.get_mut(index) { + i.docker_controls.next(); + } } } /// Change selected choice of docker commands of selected container pub fn docker_command_previous(&mut self) { if let Some(index) = self.containers.state.selected() { - self.containers.items[index].docker_controls.previous(); + if let Some(i) = self.containers.items.get_mut(index) { + i.docker_controls.previous(); + } } } /// Change selected choice of docker commands of selected container pub fn docker_command_start(&mut self) { if let Some(index) = self.containers.state.selected() { - self.containers.items[index].docker_controls.start(); + if let Some(i) = self.containers.items.get_mut(index) { + i.docker_controls.start(); + } } } /// Change selected choice of docker commands of selected container pub fn docker_command_end(&mut self) { if let Some(index) = self.containers.state.selected() { - self.containers.items[index].docker_controls.end(); + if let Some(i) = self.containers.items.get_mut(index) { + i.docker_controls.end(); + } } } /// return single app_state error - pub fn get_error(&self) -> Option { - self.error.clone() + pub const fn get_error(&self) -> Option { + self.error } /// remove single app_state error @@ -177,19 +183,19 @@ impl AppData { /// Sort the containers vec, based on a heading, either ascending or descending pub fn sort_containers(&mut self) { - if let Some((head, so)) = self.sorted_by.as_ref() { + if let Some((head, ord)) = self.sorted_by.as_ref() { match head { - Header::State => match so { + Header::State => match ord { SortedOrder::Desc => self .containers .items - .sort_by(|a, b| a.state.order().cmp(b.state.order())), + .sort_by(|a, b| a.state.order().cmp(&b.state.order())), SortedOrder::Asc => self .containers .items - .sort_by(|a, b| b.state.order().cmp(a.state.order())), + .sort_by(|a, b| b.state.order().cmp(&a.state.order())), }, - Header::Status => match so { + Header::Status => match ord { SortedOrder::Asc => self .containers .items @@ -199,7 +205,7 @@ impl AppData { .items .sort_by(|a, b| b.status.cmp(&a.status)), }, - Header::Cpu => match so { + Header::Cpu => match ord { SortedOrder::Asc => self .containers .items @@ -209,7 +215,7 @@ impl AppData { .items .sort_by(|a, b| b.cpu_stats.back().cmp(&a.cpu_stats.back())), }, - Header::Memory => match so { + Header::Memory => match ord { SortedOrder::Asc => self .containers .items @@ -219,25 +225,25 @@ impl AppData { .items .sort_by(|a, b| b.mem_stats.back().cmp(&a.mem_stats.back())), }, - Header::Id => match so { + Header::Id => match ord { SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.id.cmp(&b.id)), SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.id.cmp(&a.id)), }, - Header::Image => match so { + Header::Image => match ord { SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.image.cmp(&b.image)), SortedOrder::Desc => { self.containers.items.sort_by(|a, b| b.image.cmp(&a.image)); } }, - Header::Name => match so { + Header::Name => match ord { SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.name.cmp(&b.name)), SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.name.cmp(&a.name)), }, - Header::Rx => match so { + Header::Rx => match ord { SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.rx.cmp(&b.rx)), SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.rx.cmp(&a.rx)), }, - Header::Tx => match so { + Header::Tx => match ord { SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.tx.cmp(&b.tx)), SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.tx.cmp(&a.tx)), }, @@ -268,28 +274,36 @@ impl AppData { /// select next selected log line pub fn log_next(&mut self) { if let Some(index) = self.get_selected_log_index() { - self.containers.items[index].logs.next(); + if let Some(i) = self.containers.items.get_mut(index) { + i.logs.next(); + } } } /// select previous selected log line pub fn log_previous(&mut self) { if let Some(index) = self.get_selected_log_index() { - self.containers.items[index].logs.previous(); + if let Some(i) = self.containers.items.get_mut(index) { + i.logs.previous(); + } } } /// select last selected log line pub fn log_end(&mut self) { if let Some(index) = self.get_selected_log_index() { - self.containers.items[index].logs.end(); + if let Some(i) = self.containers.items.get_mut(index) { + i.logs.end(); + } } } /// select first selected log line pub fn log_start(&mut self) { if let Some(index) = self.get_selected_log_index() { - self.containers.items[index].logs.start(); + if let Some(i) = self.containers.items.get_mut(index) { + i.logs.start(); + } } } @@ -470,7 +484,7 @@ impl AppData { current_container.status = status; }; if current_container.state != state { - current_container.docker_controls.items = DockerControls::gen_vec(&state); + current_container.docker_controls.items = DockerControls::gen_vec(state); // Update the list state, needs to be None if the gen_vec returns an empty vec match state { @@ -488,7 +502,7 @@ impl AppData { }; } else { // limit image name to 64 chars? - // let mut container = ContainerItem::new(id.clone(), status, image.chars().into_iter().take(64).collect(), state, name); + // let mut container = ContainerItem::new(id.clone(), status, image.chars().into_iter().take(64).collect(), state, name); let mut container = ContainerItem::new(id.clone(), status, image, state, name); container.logs.end(); self.containers.items.push(container); @@ -511,7 +525,7 @@ impl AppData { let lines = if color { log_sanitizer::colorize_logs(i) } else if raw { - log_sanitizer::raw(i.clone()) + log_sanitizer::raw(i) } else { log_sanitizer::remove_ansi(i) }; diff --git a/src/app_error.rs b/src/app_error.rs index b1bcd83..385b227 100644 --- a/src/app_error.rs +++ b/src/app_error.rs @@ -3,7 +3,7 @@ use std::fmt; /// app errors to set in global state #[allow(unused)] -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Copy)] pub enum AppError { DockerConnect, DockerInterval, diff --git a/src/docker_data/mod.rs b/src/docker_data/mod.rs index 32e168c..4547f11 100644 --- a/src/docker_data/mod.rs +++ b/src/docker_data/mod.rs @@ -24,7 +24,7 @@ use crate::{ mod message; pub use message::DockerMessage; -#[derive(Debug, Hash, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, Eq, Hash, PartialEq)] enum SpawnId { Stats((String, Binate)), Log(String), @@ -33,7 +33,7 @@ enum SpawnId { /// Cpu & Mem stats take twice as long as the update interval to get a value, so will have two being executed at the same time /// SpawnId::Stats takes container_id and binate value to enable both cycles of the same container_id to be inserted into the hashmap /// Binate value is toggled when all join handles have been spawned off -#[derive(Debug, Hash, Clone, PartialEq, Eq, Copy)] +#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)] enum Binate { One, Two, @@ -61,7 +61,7 @@ pub struct DockerData { } impl DockerData { - /// Use docker stats for work out current cpu usage + /// Use docker stats to caluclate current cpu usage fn calculate_usage(stats: &Stats) -> f64 { let mut cpu_percentage = 0.0; let previous_cpu = stats.precpu_stats.cpu_usage.total_usage; diff --git a/src/input_handler/message.rs b/src/input_handler/message.rs index cbefb49..f87e2e9 100644 --- a/src/input_handler/message.rs +++ b/src/input_handler/message.rs @@ -1,6 +1,6 @@ use crossterm::event::{KeyCode, MouseEvent}; -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Copy)] pub enum InputMessages { ButtonPress(KeyCode), MouseEvent(MouseEvent), diff --git a/src/input_handler/mod.rs b/src/input_handler/mod.rs index 731b005..b253beb 100644 --- a/src/input_handler/mod.rs +++ b/src/input_handler/mod.rs @@ -77,8 +77,8 @@ impl InputHandler { } } - /// Mouse button - fn m_button(&mut self) { + /// Toggle the mouse capture (via input of the 'm' key) + fn m_key(&mut self) { if self.mouse_capture { match execute!(std::io::stdout(), DisableMouseCapture) { Ok(_) => self @@ -118,7 +118,7 @@ impl InputHandler { /// Sort containers based on a given header, switch asc to desc if already sorted, else always desc fn sort(&self, header: Header) { - let mut output = Some((header.clone(), SortedOrder::Desc)); + let mut output = Some((header, SortedOrder::Desc)); let mut locked_data = self.app_data.lock(); if let Some((h, order)) = locked_data.get_sorted().as_ref() { if &SortedOrder::Desc == order && h == &header { @@ -128,7 +128,7 @@ impl InputHandler { locked_data.set_sorted(output); } - /// Send a quit message to docker, to abort all spawns, if error, quit here instead + /// Send a quit message to docker, to abort all spawns, if an error is return, set is_running to false here instead async fn quit(&self) { match self.docker_sender.send(DockerMessage::Quit).await { Ok(_) => (), @@ -154,7 +154,7 @@ impl InputHandler { match key_code { KeyCode::Char('q' | 'Q') => self.quit().await, KeyCode::Char('h' | 'H') => self.gui_state.lock().show_help = false, - KeyCode::Char('m' | 'M') => self.m_button(), + KeyCode::Char('m' | 'M') => self.m_key(), _ => (), } } else { @@ -171,7 +171,7 @@ impl InputHandler { KeyCode::Char('9') => self.sort(Header::Tx), KeyCode::Char('q' | 'Q') => self.quit().await, KeyCode::Char('h' | 'H') => self.gui_state.lock().show_help = true, - KeyCode::Char('m' | 'M') => self.m_button(), + KeyCode::Char('m' | 'M') => self.m_key(), KeyCode::Tab => { // Skip control panel if no containers, could be refactored let has_containers = self.app_data.lock().get_container_len() == 0; diff --git a/src/main.rs b/src/main.rs index f4b67b0..b39db48 100644 --- a/src/main.rs +++ b/src/main.rs @@ -35,27 +35,24 @@ fn setup_tracing() { async fn main() { setup_tracing(); let args = CliArgs::new(); - let app_data = Arc::new(Mutex::new(AppData::default(args.clone()))); + let app_data = Arc::new(Mutex::new(AppData::default(args))); let gui_state = Arc::new(Mutex::new(GuiState::default())); let is_running = Arc::new(AtomicBool::new(true)); - let docker_args = args.clone(); let docker_app_data = Arc::clone(&app_data); let docker_gui_state = Arc::clone(&gui_state); let (docker_sx, docker_rx) = tokio::sync::mpsc::channel(16); // Create docker daemon handler, and only spawn up the docker data handler if ping returns non-error - match Docker::connect_with_socket_defaults() { Ok(docker) => { - let docker = Arc::new(docker); - match docker.ping().await { - Ok(_) => { - let docker = Arc::clone(&docker); + match docker.ping().await { + Ok(_) => { + let docker = Arc::new(docker); let is_running = Arc::clone(&is_running); tokio::spawn(DockerData::init( - docker_args, + args, docker_app_data, docker, docker_gui_state, @@ -85,7 +82,7 @@ async fn main() { input_is_running, )); - // Debug mode for testing, mostly pointless, doesn't take terminal nor draw gui + if args.gui { let update_duration = std::time::Duration::from_millis(u64::from(args.docker_interval)); create_ui( @@ -99,8 +96,9 @@ async fn main() { .await .unwrap_or(()); } else { + // Debug mode for testing, mostly pointless, doesn't take terminal nor draw gui + // TODO this needs to be improved to display something actually useful loop { - // TODO this needs to be improved to display something useful info!("in debug mode"); tokio::time::sleep(std::time::Duration::from_millis(5000)).await; } diff --git a/src/ui/color_match.rs b/src/ui/color_match.rs index a95dc88..5c423f9 100644 --- a/src/ui/color_match.rs +++ b/src/ui/color_match.rs @@ -7,7 +7,7 @@ pub mod log_sanitizer { }; /// Attempt to colorize the given string to tui-rs standards - pub fn colorize_logs(input: &str) -> Vec> { + pub fn colorize_logs<'a>(input: &str) -> Vec> { vec![Spans::from( categorise_text(input) .into_iter() @@ -40,17 +40,17 @@ pub mod log_sanitizer { } /// Remove all ansi formatting from a given string and create tui-rs spans - pub fn remove_ansi(input: &str) -> Vec> { + pub fn remove_ansi<'a>(input: &str) -> Vec> { let mut output = String::from(""); for i in categorise_text(input) { output.push_str(i.text); } - raw(output) + raw(&output) } /// create tui-rs spans that exactly match the given strings - pub fn raw(input: String) -> Vec> { - vec![Spans::from(Span::raw(input))] + pub fn raw<'a>(input: &str) -> Vec> { + vec![Spans::from(Span::raw(input.to_owned()))] } /// Change from ansi to tui colors diff --git a/src/ui/draw_blocks.rs b/src/ui/draw_blocks.rs index 1573a37..26e56ac 100644 --- a/src/ui/draw_blocks.rs +++ b/src/ui/draw_blocks.rs @@ -39,6 +39,8 @@ const REPO: &str = env!("CARGO_PKG_REPOSITORY"); const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION"); const ORANGE: Color = Color::Rgb(255, 178, 36); const MARGIN: &str = " "; +const ARROW: &str = "▶ "; +const CIRCLE: &str ="⚪ "; /// Generate block, add a border if is the selected panel, /// add custom title based on state of each panel @@ -99,7 +101,7 @@ pub fn commands( let items = List::new(items) .block(block) .highlight_style(Style::default().add_modifier(Modifier::BOLD)) - .highlight_symbol("▶ "); + .highlight_symbol(ARROW); f.render_stateful_widget( items, @@ -201,7 +203,7 @@ pub fn containers( let items = List::new(items) .block(block) .highlight_style(Style::default().add_modifier(Modifier::BOLD)) - .highlight_symbol("⚪ "); + .highlight_symbol(CIRCLE); f.render_stateful_widget(items, area, &mut app_data.lock().containers.state); } @@ -237,7 +239,7 @@ pub fn logs( let items = List::new(items) .block(block) - .highlight_symbol("▶ ") + .highlight_symbol(ARROW) .highlight_style(Style::default().add_modifier(Modifier::BOLD)); f.render_stateful_widget( items, @@ -281,8 +283,8 @@ pub fn chart( .data(&mem.0)]; let cpu_stats = CpuStats::new(cpu.0.last().map_or(0.00, |f| f.1)); let mem_stats = ByteStats::new(mem.0.last().map_or(0, |f| f.1 as u64)); - let cpu_chart = make_chart(&cpu.2, "cpu", cpu_dataset, &cpu_stats, &cpu.1); - let mem_chart = make_chart(&mem.2, "memory", mem_dataset, &mem_stats, &mem.1); + let cpu_chart = make_chart(cpu.2, "cpu", cpu_dataset, &cpu_stats, &cpu.1); + let mem_chart = make_chart(mem.2, "memory", mem_dataset, &mem_stats, &mem.1); f.render_widget(cpu_chart, area[0]); f.render_widget(mem_chart, area[1]); @@ -292,7 +294,7 @@ pub fn chart( /// Create charts fn make_chart<'a, T: Stats + Display>( - state: &State, + state: State, name: &'a str, dataset: Vec>, current: &'a T, @@ -340,14 +342,14 @@ fn make_chart<'a, T: Stats + Display>( ) } -/// Draw heading bar at top of program, always visible +/// Draw heading bar at top of program, always visible pub fn heading_bar( area: Rect, columns: &Columns, f: &mut Frame<'_, B>, has_containers: bool, loading_icon: &str, - sorted_by: &Option<(Header, SortedOrder)>, + sorted_by: Option<(Header, SortedOrder)>, gui_state: &Arc>, ) { let block = || Block::default().style(Style::default().bg(Color::Magenta).fg(Color::Black)); @@ -412,7 +414,7 @@ pub fn heading_bar( (status, count) }; - // Meta data for iterate over to create blocks and correct widths + // Meta data to iterate over to create blocks with correct widths let header_meta = [ (Header::State, columns.state.1), (Header::Status, columns.status.1), @@ -429,7 +431,7 @@ pub fn heading_bar( .iter() .map(|i| { let header_block = gen_header(&i.0, i.1); - (header_block.0, i.0.clone(), Constraint::Max(header_block.1)) + (header_block.0, i.0, Constraint::Max(header_block.1)) }) .collect::>(); @@ -469,11 +471,12 @@ pub fn heading_bar( .block(block()) .alignment(Alignment::Right); + // If no containers, don't display the headers, could maybe do this first? let index = if has_containers { 1 } else { 0 }; f.render_widget(paragraph, split_bar[index]); } -/// From a given &String, return the maximum number of chars on a single line +/// From a given &str, return the maximum number of chars on a single line fn max_line_width(text: &str) -> usize { let mut max_line_width = 0; text.lines().into_iter().for_each(|line| { @@ -486,6 +489,7 @@ fn max_line_width(text: &str) -> usize { } /// Draw the help box in the centre of the screen +/// TODO this is message, should make every line it's own renderable span pub fn help_box(f: &mut Frame<'_, B>) { let title = format!(" {} ", VERSION); @@ -564,7 +568,7 @@ pub fn help_box(f: &mut Frame<'_, B>) { } /// Draw an error popup over whole screen -pub fn error(f: &mut Frame<'_, B>, error: &AppError, seconds: Option) { +pub fn error(f: &mut Frame<'_, B>, error: AppError, seconds: Option) { let block = Block::default() .title(" Error ") .border_type(BorderType::Rounded) diff --git a/src/ui/gui_state.rs b/src/ui/gui_state.rs index 1239e20..b4c586f 100644 --- a/src/ui/gui_state.rs +++ b/src/ui/gui_state.rs @@ -7,7 +7,7 @@ use uuid::Uuid; use crate::app_data::Header; -#[derive(Debug, PartialEq, std::hash::Hash, std::cmp::Eq, Clone, Copy)] +#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)] pub enum SelectablePanel { Containers, Commands, @@ -38,6 +38,7 @@ impl SelectablePanel { } } +#[derive(Debug, Copy, Clone)] pub enum Region { Panel(SelectablePanel), Header(Header), @@ -72,7 +73,7 @@ impl BoxLocation { } } - // Should combine and just return a tuple? + // Should combine with get_vertical_constraints and just return a tuple of (vc, hc)? pub const fn get_horizontal_constraints( self, blank_vertical: u16, @@ -221,7 +222,7 @@ impl GuiState { .filter(|i| i.1.intersects(rect)) .collect::>() .get(0) - .map(|data| data.0.clone()) + .map(|data| *data.0) } /// Insert, or updates header area panel into heading_map @@ -260,7 +261,7 @@ impl GuiState { pub fn get_loading(&mut self) -> String { if self.is_loading.is_empty() { String::from(" ") - } else { + } else { self.loading_icon.to_string() } } diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 3f5fc07..35a8b28 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -93,7 +93,7 @@ async fn run_app( break; } if terminal - .draw(|f| draw_blocks::error(f, &AppError::DockerConnect, Some(seconds))) + .draw(|f| draw_blocks::error(f, AppError::DockerConnect, Some(seconds))) .is_err() { return Err(AppError::Terminal); @@ -104,9 +104,11 @@ async fn run_app( } else { let mut now = Instant::now(); loop { - if terminal.draw(|f| ui(f, &app_data, &gui_state)).is_err() { - return Err(AppError::Terminal); + if terminal.draw(|f| ui(f, &app_data, &gui_state)).is_err() { + return Err(AppError::Terminal); } + // TODO could only draw if in gui mode, that way all inputs & docker commands will run, and can just trace!("{event"}) all over the place + // refactor this into own function, so can be called without drawing to the terminal if crossterm::event::poll(input_poll_rate).unwrap_or(false) { if let Ok(event) = event::read() { if let Event::Key(key) = event { @@ -213,7 +215,7 @@ fn ui( f, has_containers, &loading_icon, - &sorted_by, + sorted_by, gui_state, ); @@ -233,6 +235,6 @@ fn ui( if let Some(error) = has_error { app_data.lock().show_error = true; - draw_blocks::error(f, &error, None); + draw_blocks::error(f, error, None); } }