refactor: Impl Copy where able to

This commit is contained in:
Jack Wills
2022-10-01 19:57:27 +00:00
parent 15597dbe69
commit e76878f424
14 changed files with 138 additions and 118 deletions
+32 -31
View File
@@ -7,7 +7,6 @@ use tui::{
use super::Header; use super::Header;
const ONE_KB: f64 = 1000.0; const ONE_KB: f64 = 1000.0;
const ONE_MB: f64 = ONE_KB * 1000.0; const ONE_MB: f64 = ONE_KB * 1000.0;
const ONE_GB: f64 = ONE_MB * 1000.0; const ONE_GB: f64 = ONE_MB * 1000.0;
@@ -25,6 +24,7 @@ impl<T> StatefulList<T> {
items, items,
} }
} }
pub fn end(&mut self) { pub fn end(&mut self) {
let len = self.items.len(); let len = self.items.len();
if len > 0 { if len > 0 {
@@ -83,7 +83,7 @@ impl<T> StatefulList<T> {
} }
/// States of the container /// States of the container
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd)] #[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd)]
pub enum State { pub enum State {
Dead, Dead,
Exited, Exited,
@@ -95,7 +95,7 @@ pub enum State {
} }
impl State { impl State {
pub const fn get_color(&self) -> Color { pub const fn get_color(self) -> Color {
match self { match self {
Self::Running => Color::Green, Self::Running => Color::Green,
Self::Removing => Color::LightRed, Self::Removing => Color::LightRed,
@@ -105,15 +105,15 @@ impl State {
} }
} }
// Dirty way to create order for the state, rather than impl Ord // 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 { match self {
Self::Running => "a", Self::Running => 0,
Self::Paused => "b", Self::Paused => 1,
Self::Restarting => "c", Self::Restarting => 2,
Self::Removing => "d", Self::Removing => 3,
Self::Exited => "e", Self::Exited => 4,
Self::Dead => "f", Self::Dead => 5,
Self::Unknown => "g", Self::Unknown => 6,
} }
} }
} }
@@ -162,7 +162,7 @@ impl fmt::Display for State {
} }
/// Items for the container control list /// Items for the container control list
#[derive(Debug, Clone)] #[derive(Debug, Clone, Copy)]
pub enum DockerControls { pub enum DockerControls {
Pause, Pause,
Unpause, Unpause,
@@ -172,7 +172,7 @@ pub enum DockerControls {
} }
impl DockerControls { impl DockerControls {
pub const fn get_color(&self) -> Color { pub const fn get_color(self) -> Color {
match self { match self {
Self::Start => Color::Green, Self::Start => Color::Green,
Self::Stop => Color::Red, Self::Stop => Color::Red,
@@ -182,7 +182,8 @@ impl DockerControls {
} }
} }
pub fn gen_vec(state: &State) -> Vec<Self> { /// Docker commands available depending on the containers state
pub fn gen_vec(state: State) -> Vec<Self> {
match state { match state {
State::Dead | State::Exited => vec![Self::Start, Self::Restart], State::Dead | State::Exited => vec![Self::Start, Self::Restart],
State::Paused => vec![Self::Unpause, Self::Stop], State::Paused => vec![Self::Unpause, Self::Stop],
@@ -213,7 +214,7 @@ pub trait Stats {
/// Struct for frequently updated CPU stats /// Struct for frequently updated CPU stats
/// So can use custom display formatter /// So can use custom display formatter
/// Use trait Stats for use as generic in draw_chart function /// Use trait Stats for use as generic in draw_chart function
#[derive(Clone, Debug)] #[derive(Debug, Clone, Copy)]
pub struct CpuStats { pub struct CpuStats {
value: f64, value: f64,
} }
@@ -266,7 +267,7 @@ impl fmt::Display for CpuStats {
/// Struct for frequently updated memory usage stats /// Struct for frequently updated memory usage stats
/// So can use custom display formatter /// So can use custom display formatter
/// Use trait Stats for use as generic in draw_chart function /// Use trait Stats for use as generic in draw_chart function
#[derive(Clone, Debug, Eq)] #[derive(Debug, Clone, Copy, Eq)]
pub struct ByteStats { pub struct ByteStats {
value: u64, 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 { impl fmt::Display for ByteStats {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 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 as_f64 = self.value as f64;
let p = match as_f64 { let p = match as_f64 {
x if x >= ONE_GB => format!("{y:.2} GB", y = as_f64 / ONE_GB), 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 /// Info for each container
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ContainerItem { pub struct ContainerItem {
@@ -336,13 +340,10 @@ pub struct ContainerItem {
pub status: String, pub status: String,
} }
pub type MemTuple = (Vec<(f64, f64)>, ByteStats, State);
pub type CpuTuple = (Vec<(f64, f64)>, CpuStats, State);
impl ContainerItem { impl ContainerItem {
/// Create a new container item /// Create a new container item
pub fn new(id: String, status: String, image: String, state: State, name: String) -> Self { 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(); docker_controls.start();
Self { Self {
cpu_stats: VecDeque::with_capacity(60), 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 { fn max_cpu_stats(&self) -> CpuStats {
match self.cpu_stats.iter().max() { match self.cpu_stats.iter().max() {
Some(value) => value.clone(), Some(value) => *value,
None => CpuStats::new(0.0), 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 { fn max_mem_stats(&self) -> ByteStats {
match self.mem_stats.iter().max() { match self.mem_stats.iter().max() {
Some(value) => value.clone(), Some(value) => *value,
None => ByteStats::new(0), None => ByteStats::new(0),
} }
} }
@@ -382,11 +383,11 @@ impl ContainerItem {
self.cpu_stats self.cpu_stats
.iter() .iter()
.enumerate() .enumerate()
.map(|i| (i.0 as f64, i.1.value)) .map(|i| (i.0 as f64, i.1.value as f64))
.collect::<Vec<_>>() .collect::<Vec<_>>()
} }
/// 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)> { fn get_mem_dataset(&self) -> Vec<(f64, f64)> {
self.mem_stats self.mem_stats
.iter() .iter()
@@ -400,7 +401,7 @@ impl ContainerItem {
( (
self.get_cpu_dataset(), self.get_cpu_dataset(),
self.max_cpu_stats(), self.max_cpu_stats(),
self.state.clone(), self.state,
) )
} }
@@ -409,7 +410,7 @@ impl ContainerItem {
( (
self.get_mem_dataset(), self.get_mem_dataset(),
self.max_mem_stats(), self.max_mem_stats(),
self.state.clone(), self.state,
) )
} }
@@ -421,7 +422,7 @@ impl ContainerItem {
} }
/// Container information panel headings + widths, for nice pretty formatting /// Container information panel headings + widths, for nice pretty formatting
#[derive(Debug)] #[derive(Debug, Clone, Copy)]
pub struct Columns { pub struct Columns {
pub state: (Header, usize), pub state: (Header, usize),
pub status: (Header, usize), pub status: (Header, usize),
+47 -33
View File
@@ -9,7 +9,7 @@ use crate::{app_error::AppError, parse_args::CliArgs, ui::log_sanitizer};
pub use container_state::*; pub use container_state::*;
/// Global app_state, stored in an Arc<Mutex> /// Global app_state, stored in an Arc<Mutex>
#[derive(Debug)] #[derive(Debug, Clone)]
pub struct AppData { pub struct AppData {
args: CliArgs, args: CliArgs,
error: Option<AppError>, error: Option<AppError>,
@@ -20,13 +20,13 @@ pub struct AppData {
sorted_by: Option<(Header, SortedOrder)>, sorted_by: Option<(Header, SortedOrder)>,
} }
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum SortedOrder { pub enum SortedOrder {
Asc, Asc,
Desc, Desc,
} }
#[derive(Debug, Clone, PartialEq, Hash, Eq)] #[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub enum Header { pub enum Header {
State, State,
Status, Status,
@@ -58,20 +58,19 @@ impl fmt::Display for Header {
} }
impl AppData { impl AppData {
pub fn get_sorted(&self) -> Option<(Header, SortedOrder)> { pub const fn get_sorted(&self) -> Option<(Header, SortedOrder)> {
self.sorted_by.clone() self.sorted_by
} }
/// Change the sorted order, also set the selected container state to match new order /// Change the sorted order, also set the selected container state to match new order
pub fn set_sorted(&mut self, x: Option<(Header, SortedOrder)>) { pub fn set_sorted(&mut self, x: Option<(Header, SortedOrder)>) {
self.sorted_by = x; self.sorted_by = x;
let id = self.get_selected_container_id();
self.sort_containers(); self.sort_containers();
self.containers.state.select( self.containers.state.select(
self.containers self.containers
.items .items
.iter() .iter()
.position(|i| Some(i.id.clone()) == id), .position(|i| Some(i.id.clone()) == self.get_selected_container_id()),
); );
} }
/// Generate a default app_state /// Generate a default app_state
@@ -106,8 +105,7 @@ impl AppData {
.state .state
.selected() .selected()
{ {
output = output = Some(self.containers.items[index].docker_controls.items[control_index]);
Some(self.containers.items[index].docker_controls.items[control_index].clone());
} }
} }
output output
@@ -116,34 +114,42 @@ impl AppData {
/// Change selected choice of docker commands of selected container /// Change selected choice of docker commands of selected container
pub fn docker_command_next(&mut self) { pub fn docker_command_next(&mut self) {
if let Some(index) = self.containers.state.selected() { 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 /// Change selected choice of docker commands of selected container
pub fn docker_command_previous(&mut self) { pub fn docker_command_previous(&mut self) {
if let Some(index) = self.containers.state.selected() { 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 /// Change selected choice of docker commands of selected container
pub fn docker_command_start(&mut self) { pub fn docker_command_start(&mut self) {
if let Some(index) = self.containers.state.selected() { 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 /// Change selected choice of docker commands of selected container
pub fn docker_command_end(&mut self) { pub fn docker_command_end(&mut self) {
if let Some(index) = self.containers.state.selected() { 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 /// return single app_state error
pub fn get_error(&self) -> Option<AppError> { pub const fn get_error(&self) -> Option<AppError> {
self.error.clone() self.error
} }
/// remove single app_state error /// remove single app_state error
@@ -177,19 +183,19 @@ impl AppData {
/// Sort the containers vec, based on a heading, either ascending or descending /// Sort the containers vec, based on a heading, either ascending or descending
pub fn sort_containers(&mut self) { 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 { match head {
Header::State => match so { Header::State => match ord {
SortedOrder::Desc => self SortedOrder::Desc => self
.containers .containers
.items .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 SortedOrder::Asc => self
.containers .containers
.items .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 SortedOrder::Asc => self
.containers .containers
.items .items
@@ -199,7 +205,7 @@ impl AppData {
.items .items
.sort_by(|a, b| b.status.cmp(&a.status)), .sort_by(|a, b| b.status.cmp(&a.status)),
}, },
Header::Cpu => match so { Header::Cpu => match ord {
SortedOrder::Asc => self SortedOrder::Asc => self
.containers .containers
.items .items
@@ -209,7 +215,7 @@ impl AppData {
.items .items
.sort_by(|a, b| b.cpu_stats.back().cmp(&a.cpu_stats.back())), .sort_by(|a, b| b.cpu_stats.back().cmp(&a.cpu_stats.back())),
}, },
Header::Memory => match so { Header::Memory => match ord {
SortedOrder::Asc => self SortedOrder::Asc => self
.containers .containers
.items .items
@@ -219,25 +225,25 @@ impl AppData {
.items .items
.sort_by(|a, b| b.mem_stats.back().cmp(&a.mem_stats.back())), .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::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)), 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::Asc => self.containers.items.sort_by(|a, b| a.image.cmp(&b.image)),
SortedOrder::Desc => { SortedOrder::Desc => {
self.containers.items.sort_by(|a, b| b.image.cmp(&a.image)); 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::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)), 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::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)), 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::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)), 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 /// select next selected log line
pub fn log_next(&mut self) { pub fn log_next(&mut self) {
if let Some(index) = self.get_selected_log_index() { 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 /// select previous selected log line
pub fn log_previous(&mut self) { pub fn log_previous(&mut self) {
if let Some(index) = self.get_selected_log_index() { 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 /// select last selected log line
pub fn log_end(&mut self) { pub fn log_end(&mut self) {
if let Some(index) = self.get_selected_log_index() { 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 /// select first selected log line
pub fn log_start(&mut self) { pub fn log_start(&mut self) {
if let Some(index) = self.get_selected_log_index() { 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; current_container.status = status;
}; };
if current_container.state != state { 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 // Update the list state, needs to be None if the gen_vec returns an empty vec
match state { match state {
@@ -511,7 +525,7 @@ impl AppData {
let lines = if color { let lines = if color {
log_sanitizer::colorize_logs(i) log_sanitizer::colorize_logs(i)
} else if raw { } else if raw {
log_sanitizer::raw(i.clone()) log_sanitizer::raw(i)
} else { } else {
log_sanitizer::remove_ansi(i) log_sanitizer::remove_ansi(i)
}; };
+1 -1
View File
@@ -3,7 +3,7 @@ use std::fmt;
/// app errors to set in global state /// app errors to set in global state
#[allow(unused)] #[allow(unused)]
#[derive(Debug, Clone)] #[derive(Debug, Clone, Copy)]
pub enum AppError { pub enum AppError {
DockerConnect, DockerConnect,
DockerInterval, DockerInterval,
+3 -3
View File
@@ -24,7 +24,7 @@ use crate::{
mod message; mod message;
pub use message::DockerMessage; pub use message::DockerMessage;
#[derive(Debug, Hash, Clone, PartialEq, Eq)] #[derive(Debug, Clone, Eq, Hash, PartialEq)]
enum SpawnId { enum SpawnId {
Stats((String, Binate)), Stats((String, Binate)),
Log(String), 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 /// 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 /// 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 /// 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 { enum Binate {
One, One,
Two, Two,
@@ -61,7 +61,7 @@ pub struct DockerData {
} }
impl 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 { fn calculate_usage(stats: &Stats) -> f64 {
let mut cpu_percentage = 0.0; let mut cpu_percentage = 0.0;
let previous_cpu = stats.precpu_stats.cpu_usage.total_usage; let previous_cpu = stats.precpu_stats.cpu_usage.total_usage;
+1 -1
View File
@@ -1,6 +1,6 @@
use crossterm::event::{KeyCode, MouseEvent}; use crossterm::event::{KeyCode, MouseEvent};
#[derive(Debug, Clone)] #[derive(Debug, Clone, Copy)]
pub enum InputMessages { pub enum InputMessages {
ButtonPress(KeyCode), ButtonPress(KeyCode),
MouseEvent(MouseEvent), MouseEvent(MouseEvent),
+6 -6
View File
@@ -77,8 +77,8 @@ impl InputHandler {
} }
} }
/// Mouse button /// Toggle the mouse capture (via input of the 'm' key)
fn m_button(&mut self) { fn m_key(&mut self) {
if self.mouse_capture { if self.mouse_capture {
match execute!(std::io::stdout(), DisableMouseCapture) { match execute!(std::io::stdout(), DisableMouseCapture) {
Ok(_) => self 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 /// Sort containers based on a given header, switch asc to desc if already sorted, else always desc
fn sort(&self, header: Header) { 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(); let mut locked_data = self.app_data.lock();
if let Some((h, order)) = locked_data.get_sorted().as_ref() { if let Some((h, order)) = locked_data.get_sorted().as_ref() {
if &SortedOrder::Desc == order && h == &header { if &SortedOrder::Desc == order && h == &header {
@@ -128,7 +128,7 @@ impl InputHandler {
locked_data.set_sorted(output); 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) { async fn quit(&self) {
match self.docker_sender.send(DockerMessage::Quit).await { match self.docker_sender.send(DockerMessage::Quit).await {
Ok(_) => (), Ok(_) => (),
@@ -154,7 +154,7 @@ impl InputHandler {
match key_code { match key_code {
KeyCode::Char('q' | 'Q') => self.quit().await, KeyCode::Char('q' | 'Q') => self.quit().await,
KeyCode::Char('h' | 'H') => self.gui_state.lock().show_help = false, 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 { } else {
@@ -171,7 +171,7 @@ impl InputHandler {
KeyCode::Char('9') => self.sort(Header::Tx), KeyCode::Char('9') => self.sort(Header::Tx),
KeyCode::Char('q' | 'Q') => self.quit().await, KeyCode::Char('q' | 'Q') => self.quit().await,
KeyCode::Char('h' | 'H') => self.gui_state.lock().show_help = true, 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 => { KeyCode::Tab => {
// Skip control panel if no containers, could be refactored // Skip control panel if no containers, could be refactored
let has_containers = self.app_data.lock().get_container_len() == 0; let has_containers = self.app_data.lock().get_container_len() == 0;
+6 -8
View File
@@ -35,27 +35,24 @@ fn setup_tracing() {
async fn main() { async fn main() {
setup_tracing(); setup_tracing();
let args = CliArgs::new(); 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 gui_state = Arc::new(Mutex::new(GuiState::default()));
let is_running = Arc::new(AtomicBool::new(true)); let is_running = Arc::new(AtomicBool::new(true));
let docker_args = args.clone();
let docker_app_data = Arc::clone(&app_data); let docker_app_data = Arc::clone(&app_data);
let docker_gui_state = Arc::clone(&gui_state); let docker_gui_state = Arc::clone(&gui_state);
let (docker_sx, docker_rx) = tokio::sync::mpsc::channel(16); 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 // Create docker daemon handler, and only spawn up the docker data handler if ping returns non-error
match Docker::connect_with_socket_defaults() { match Docker::connect_with_socket_defaults() {
Ok(docker) => { Ok(docker) => {
let docker = Arc::new(docker);
match docker.ping().await { match docker.ping().await {
Ok(_) => { Ok(_) => {
let docker = Arc::clone(&docker); let docker = Arc::new(docker);
let is_running = Arc::clone(&is_running); let is_running = Arc::clone(&is_running);
tokio::spawn(DockerData::init( tokio::spawn(DockerData::init(
docker_args, args,
docker_app_data, docker_app_data,
docker, docker,
docker_gui_state, docker_gui_state,
@@ -85,7 +82,7 @@ async fn main() {
input_is_running, input_is_running,
)); ));
// Debug mode for testing, mostly pointless, doesn't take terminal nor draw gui
if args.gui { if args.gui {
let update_duration = std::time::Duration::from_millis(u64::from(args.docker_interval)); let update_duration = std::time::Duration::from_millis(u64::from(args.docker_interval));
create_ui( create_ui(
@@ -99,8 +96,9 @@ async fn main() {
.await .await
.unwrap_or(()); .unwrap_or(());
} else { } 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 { loop {
// TODO this needs to be improved to display something useful
info!("in debug mode"); info!("in debug mode");
tokio::time::sleep(std::time::Duration::from_millis(5000)).await; tokio::time::sleep(std::time::Duration::from_millis(5000)).await;
} }
+5 -5
View File
@@ -7,7 +7,7 @@ pub mod log_sanitizer {
}; };
/// Attempt to colorize the given string to tui-rs standards /// Attempt to colorize the given string to tui-rs standards
pub fn colorize_logs(input: &str) -> Vec<Spans<'static>> { pub fn colorize_logs<'a>(input: &str) -> Vec<Spans<'a>> {
vec![Spans::from( vec![Spans::from(
categorise_text(input) categorise_text(input)
.into_iter() .into_iter()
@@ -40,17 +40,17 @@ pub mod log_sanitizer {
} }
/// Remove all ansi formatting from a given string and create tui-rs spans /// Remove all ansi formatting from a given string and create tui-rs spans
pub fn remove_ansi(input: &str) -> Vec<Spans<'static>> { pub fn remove_ansi<'a>(input: &str) -> Vec<Spans<'a>> {
let mut output = String::from(""); let mut output = String::from("");
for i in categorise_text(input) { for i in categorise_text(input) {
output.push_str(i.text); output.push_str(i.text);
} }
raw(output) raw(&output)
} }
/// create tui-rs spans that exactly match the given strings /// create tui-rs spans that exactly match the given strings
pub fn raw(input: String) -> Vec<Spans<'static>> { pub fn raw<'a>(input: &str) -> Vec<Spans<'a>> {
vec![Spans::from(Span::raw(input))] vec![Spans::from(Span::raw(input.to_owned()))]
} }
/// Change from ansi to tui colors /// Change from ansi to tui colors
+15 -11
View File
@@ -39,6 +39,8 @@ const REPO: &str = env!("CARGO_PKG_REPOSITORY");
const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION"); const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION");
const ORANGE: Color = Color::Rgb(255, 178, 36); const ORANGE: Color = Color::Rgb(255, 178, 36);
const MARGIN: &str = " "; const MARGIN: &str = " ";
const ARROW: &str = "";
const CIRCLE: &str ="";
/// Generate block, add a border if is the selected panel, /// Generate block, add a border if is the selected panel,
/// add custom title based on state of each panel /// add custom title based on state of each panel
@@ -99,7 +101,7 @@ pub fn commands<B: Backend>(
let items = List::new(items) let items = List::new(items)
.block(block) .block(block)
.highlight_style(Style::default().add_modifier(Modifier::BOLD)) .highlight_style(Style::default().add_modifier(Modifier::BOLD))
.highlight_symbol(""); .highlight_symbol(ARROW);
f.render_stateful_widget( f.render_stateful_widget(
items, items,
@@ -201,7 +203,7 @@ pub fn containers<B: Backend>(
let items = List::new(items) let items = List::new(items)
.block(block) .block(block)
.highlight_style(Style::default().add_modifier(Modifier::BOLD)) .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); f.render_stateful_widget(items, area, &mut app_data.lock().containers.state);
} }
@@ -237,7 +239,7 @@ pub fn logs<B: Backend>(
let items = List::new(items) let items = List::new(items)
.block(block) .block(block)
.highlight_symbol("") .highlight_symbol(ARROW)
.highlight_style(Style::default().add_modifier(Modifier::BOLD)); .highlight_style(Style::default().add_modifier(Modifier::BOLD));
f.render_stateful_widget( f.render_stateful_widget(
items, items,
@@ -281,8 +283,8 @@ pub fn chart<B: Backend>(
.data(&mem.0)]; .data(&mem.0)];
let cpu_stats = CpuStats::new(cpu.0.last().map_or(0.00, |f| f.1)); 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 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 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 mem_chart = make_chart(mem.2, "memory", mem_dataset, &mem_stats, &mem.1);
f.render_widget(cpu_chart, area[0]); f.render_widget(cpu_chart, area[0]);
f.render_widget(mem_chart, area[1]); f.render_widget(mem_chart, area[1]);
@@ -292,7 +294,7 @@ pub fn chart<B: Backend>(
/// Create charts /// Create charts
fn make_chart<'a, T: Stats + Display>( fn make_chart<'a, T: Stats + Display>(
state: &State, state: State,
name: &'a str, name: &'a str,
dataset: Vec<Dataset<'a>>, dataset: Vec<Dataset<'a>>,
current: &'a T, current: &'a T,
@@ -347,7 +349,7 @@ pub fn heading_bar<B: Backend>(
f: &mut Frame<'_, B>, f: &mut Frame<'_, B>,
has_containers: bool, has_containers: bool,
loading_icon: &str, loading_icon: &str,
sorted_by: &Option<(Header, SortedOrder)>, sorted_by: Option<(Header, SortedOrder)>,
gui_state: &Arc<Mutex<GuiState>>, gui_state: &Arc<Mutex<GuiState>>,
) { ) {
let block = || Block::default().style(Style::default().bg(Color::Magenta).fg(Color::Black)); let block = || Block::default().style(Style::default().bg(Color::Magenta).fg(Color::Black));
@@ -412,7 +414,7 @@ pub fn heading_bar<B: Backend>(
(status, count) (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 = [ let header_meta = [
(Header::State, columns.state.1), (Header::State, columns.state.1),
(Header::Status, columns.status.1), (Header::Status, columns.status.1),
@@ -429,7 +431,7 @@ pub fn heading_bar<B: Backend>(
.iter() .iter()
.map(|i| { .map(|i| {
let header_block = gen_header(&i.0, i.1); 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::<Vec<_>>(); .collect::<Vec<_>>();
@@ -469,11 +471,12 @@ pub fn heading_bar<B: Backend>(
.block(block()) .block(block())
.alignment(Alignment::Right); .alignment(Alignment::Right);
// If no containers, don't display the headers, could maybe do this first?
let index = if has_containers { 1 } else { 0 }; let index = if has_containers { 1 } else { 0 };
f.render_widget(paragraph, split_bar[index]); 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 { fn max_line_width(text: &str) -> usize {
let mut max_line_width = 0; let mut max_line_width = 0;
text.lines().into_iter().for_each(|line| { 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 /// 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<B: Backend>(f: &mut Frame<'_, B>) { pub fn help_box<B: Backend>(f: &mut Frame<'_, B>) {
let title = format!(" {} ", VERSION); let title = format!(" {} ", VERSION);
@@ -564,7 +568,7 @@ pub fn help_box<B: Backend>(f: &mut Frame<'_, B>) {
} }
/// Draw an error popup over whole screen /// Draw an error popup over whole screen
pub fn error<B: Backend>(f: &mut Frame<'_, B>, error: &AppError, seconds: Option<u8>) { pub fn error<B: Backend>(f: &mut Frame<'_, B>, error: AppError, seconds: Option<u8>) {
let block = Block::default() let block = Block::default()
.title(" Error ") .title(" Error ")
.border_type(BorderType::Rounded) .border_type(BorderType::Rounded)
+4 -3
View File
@@ -7,7 +7,7 @@ use uuid::Uuid;
use crate::app_data::Header; 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 { pub enum SelectablePanel {
Containers, Containers,
Commands, Commands,
@@ -38,6 +38,7 @@ impl SelectablePanel {
} }
} }
#[derive(Debug, Copy, Clone)]
pub enum Region { pub enum Region {
Panel(SelectablePanel), Panel(SelectablePanel),
Header(Header), 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( pub const fn get_horizontal_constraints(
self, self,
blank_vertical: u16, blank_vertical: u16,
@@ -221,7 +222,7 @@ impl GuiState {
.filter(|i| i.1.intersects(rect)) .filter(|i| i.1.intersects(rect))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.get(0) .get(0)
.map(|data| data.0.clone()) .map(|data| *data.0)
} }
/// Insert, or updates header area panel into heading_map /// Insert, or updates header area panel into heading_map
+5 -3
View File
@@ -93,7 +93,7 @@ async fn run_app<B: Backend + Send>(
break; break;
} }
if terminal if terminal
.draw(|f| draw_blocks::error(f, &AppError::DockerConnect, Some(seconds))) .draw(|f| draw_blocks::error(f, AppError::DockerConnect, Some(seconds)))
.is_err() .is_err()
{ {
return Err(AppError::Terminal); return Err(AppError::Terminal);
@@ -107,6 +107,8 @@ async fn run_app<B: Backend + Send>(
if terminal.draw(|f| ui(f, &app_data, &gui_state)).is_err() { if terminal.draw(|f| ui(f, &app_data, &gui_state)).is_err() {
return Err(AppError::Terminal); 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 crossterm::event::poll(input_poll_rate).unwrap_or(false) {
if let Ok(event) = event::read() { if let Ok(event) = event::read() {
if let Event::Key(key) = event { if let Event::Key(key) = event {
@@ -213,7 +215,7 @@ fn ui<B: Backend>(
f, f,
has_containers, has_containers,
&loading_icon, &loading_icon,
&sorted_by, sorted_by,
gui_state, gui_state,
); );
@@ -233,6 +235,6 @@ fn ui<B: Backend>(
if let Some(error) = has_error { if let Some(error) = has_error {
app_data.lock().show_error = true; app_data.lock().show_error = true;
draw_blocks::error(f, &error, None); draw_blocks::error(f, error, None);
} }
} }