diff --git a/Cargo.toml b/Cargo.toml index e2f90ce5..9c1a4bbe 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,7 @@ path = "src/main.rs" [dependencies] chrono = "0.4.9" clap = "2.33.0" -crossterm = "^0.10" +crossterm = "0.13" failure = "0.1.5" futures-preview = "0.3.0-alpha.18" fern = "0.5" @@ -32,10 +32,8 @@ sysinfo = "0.9.4" tokio = "0.2.0-alpha.4" winapi = "0.3.8" -[dependencies.tui-temp-fork] -#git = "https://github.com/ClementTsang/tui-rs" -path = "../tui-rs" -version = "0.6" +[dependencies.tui] +version = "0.7" default-features = false features = ['crossterm'] diff --git a/rustfmt.toml b/rustfmt.toml index 4bc25f6e..7aa76c5c 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,4 +1,5 @@ max_width = 150 +newline_style = "Unix" reorder_imports = true control_brace_style = "ClosingNextLine" fn_args_layout = "Compressed" diff --git a/src/app.rs b/src/app.rs index 752b0be9..59f376a3 100644 --- a/src/app.rs +++ b/src/app.rs @@ -21,56 +21,55 @@ pub enum ScrollDirection { } pub struct App { - pub process_sorting_type : processes::ProcessSorting, - pub process_sorting_reverse : bool, - pub to_be_resorted : bool, - pub currently_selected_process_position : i64, - pub currently_selected_disk_position : i64, - pub currently_selected_temperature_position : i64, - pub temperature_type : temperature::TemperatureType, - pub update_rate_in_milliseconds : u64, - pub show_average_cpu : bool, - pub current_application_position : ApplicationPosition, - pub current_zoom_level_percent : f64, // Make at most 200, least 50? - pub data : data_collection::Data, - pub scroll_direction : ScrollDirection, - pub previous_disk_position : i64, - pub previous_temp_position : i64, - pub previous_process_position : i64, - awaiting_second_d : bool, - pub use_dot : bool, - pub show_help : bool, - pub is_frozen : bool, + pub process_sorting_type: processes::ProcessSorting, + pub process_sorting_reverse: bool, + pub to_be_resorted: bool, + pub currently_selected_process_position: i64, + pub currently_selected_disk_position: i64, + pub currently_selected_temperature_position: i64, + pub temperature_type: temperature::TemperatureType, + pub update_rate_in_milliseconds: u64, + pub show_average_cpu: bool, + pub current_application_position: ApplicationPosition, + pub current_zoom_level_percent: f64, // Make at most 200, least 50? + pub data: data_collection::Data, + pub scroll_direction: ScrollDirection, + pub previous_disk_position: i64, + pub previous_temp_position: i64, + pub previous_process_position: i64, + awaiting_second_d: bool, + pub use_dot: bool, + pub show_help: bool, + pub is_frozen: bool, } impl App { - pub fn new(show_average_cpu : bool, temperature_type : temperature::TemperatureType, update_rate_in_milliseconds : u64, use_dot : bool) -> App { + pub fn new(show_average_cpu: bool, temperature_type: temperature::TemperatureType, update_rate_in_milliseconds: u64, use_dot: bool) -> App { App { - process_sorting_type : processes::ProcessSorting::CPU, - process_sorting_reverse : true, - to_be_resorted : false, - currently_selected_process_position : 0, - currently_selected_disk_position : 0, - currently_selected_temperature_position : 0, + process_sorting_type: processes::ProcessSorting::CPU, + process_sorting_reverse: true, + to_be_resorted: false, + currently_selected_process_position: 0, + currently_selected_disk_position: 0, + currently_selected_temperature_position: 0, temperature_type, update_rate_in_milliseconds, show_average_cpu, - current_application_position : ApplicationPosition::PROCESS, - current_zoom_level_percent : 100.0, - data : data_collection::Data::default(), - scroll_direction : ScrollDirection::DOWN, - previous_process_position : 0, - previous_disk_position : 0, - previous_temp_position : 0, - awaiting_second_d : false, + current_application_position: ApplicationPosition::PROCESS, + current_zoom_level_percent: 100.0, + data: data_collection::Data::default(), + scroll_direction: ScrollDirection::DOWN, + previous_process_position: 0, + previous_disk_position: 0, + previous_temp_position: 0, + awaiting_second_d: false, use_dot, - show_help : false, - is_frozen : false, + show_help: false, + is_frozen: false, } } - pub fn on_enter(&mut self) { - } + pub fn on_enter(&mut self) {} pub fn on_esc(&mut self) { if self.show_help { @@ -79,15 +78,14 @@ impl App { } // TODO: How should we make it for process panel specific hotkeys? Only if we're on process panel? Or what? - pub fn on_key(&mut self, c : char) { + pub fn on_key(&mut self, c: char) { if !self.show_help { match c { 'd' => { if self.awaiting_second_d { self.awaiting_second_d = false; self.kill_highlighted_process().unwrap_or(()); - } - else { + } else { self.awaiting_second_d = true; } } @@ -223,7 +221,7 @@ impl App { self.scroll_direction = ScrollDirection::DOWN; } - fn change_process_position(&mut self, num_to_change_by : i64) { + fn change_process_position(&mut self, num_to_change_by: i64) { if self.currently_selected_process_position + num_to_change_by >= 0 && self.currently_selected_process_position + num_to_change_by < self.data.list_of_processes.len() as i64 { @@ -231,7 +229,7 @@ impl App { } } - fn change_temp_position(&mut self, num_to_change_by : i64) { + fn change_temp_position(&mut self, num_to_change_by: i64) { if self.currently_selected_temperature_position + num_to_change_by >= 0 && self.currently_selected_temperature_position + num_to_change_by < self.data.list_of_temperature_sensor.len() as i64 { @@ -239,7 +237,7 @@ impl App { } } - fn change_disk_position(&mut self, num_to_change_by : i64) { + fn change_disk_position(&mut self, num_to_change_by: i64) { if self.currently_selected_disk_position + num_to_change_by >= 0 && self.currently_selected_disk_position + num_to_change_by < self.data.list_of_disks.len() as i64 { diff --git a/src/app/data_collection.rs b/src/app/data_collection.rs index e89a7390..bb03deb1 100644 --- a/src/app/data_collection.rs +++ b/src/app/data_collection.rs @@ -11,13 +11,13 @@ pub mod network; pub mod processes; pub mod temperature; -fn set_if_valid(result : &Result, value_to_set : &mut T) { +fn set_if_valid(result: &Result, value_to_set: &mut T) { if let Ok(result) = result { *value_to_set = (*result).clone(); } } -fn push_if_valid(result : &Result, vector_to_push : &mut Vec) { +fn push_if_valid(result: &Result, vector_to_push: &mut Vec) { if let Ok(result) = result { vector_to_push.push(result.clone()); } @@ -25,47 +25,47 @@ fn push_if_valid(result : &Result, - pub list_of_io : Vec, - pub list_of_physical_io : Vec, - pub memory : Vec, - pub swap : Vec, - pub list_of_temperature_sensor : Vec, - pub network : Vec, - pub list_of_processes : Vec, // Only need to keep a list of processes... - pub list_of_disks : Vec, // Only need to keep a list of disks and their data + pub list_of_cpu_packages: Vec, + pub list_of_io: Vec, + pub list_of_physical_io: Vec, + pub memory: Vec, + pub swap: Vec, + pub list_of_temperature_sensor: Vec, + pub network: Vec, + pub list_of_processes: Vec, // Only need to keep a list of processes... + pub list_of_disks: Vec, // Only need to keep a list of disks and their data } pub struct DataState { - pub data : Data, - first_run : bool, - sys : System, - stale_max_seconds : u64, - prev_pid_stats : HashMap, - prev_idle : f64, - prev_non_idle : f64, - temperature_type : temperature::TemperatureType, - last_clean : Instant, // Last time stale data was cleared + pub data: Data, + first_run: bool, + sys: System, + stale_max_seconds: u64, + prev_pid_stats: HashMap, + prev_idle: f64, + prev_non_idle: f64, + temperature_type: temperature::TemperatureType, + last_clean: Instant, // Last time stale data was cleared } impl Default for DataState { fn default() -> Self { DataState { - data : Data::default(), - first_run : true, - sys : System::new(), - stale_max_seconds : constants::STALE_MAX_MILLISECONDS / 1000, - prev_pid_stats : HashMap::new(), - prev_idle : 0_f64, - prev_non_idle : 0_f64, - temperature_type : temperature::TemperatureType::Celsius, - last_clean : Instant::now(), + data: Data::default(), + first_run: true, + sys: System::new(), + stale_max_seconds: constants::STALE_MAX_MILLISECONDS / 1000, + prev_pid_stats: HashMap::new(), + prev_idle: 0_f64, + prev_non_idle: 0_f64, + temperature_type: temperature::TemperatureType::Celsius, + last_clean: Instant::now(), } } } impl DataState { - pub fn set_temperature_type(&mut self, temperature_type : temperature::TemperatureType) { + pub fn set_temperature_type(&mut self, temperature_type: temperature::TemperatureType) { self.temperature_type = temperature_type; } @@ -113,7 +113,7 @@ impl DataState { let current_instant = std::time::Instant::now(); if current_instant.duration_since(self.last_clean).as_secs() > self.stale_max_seconds { - let stale_list : Vec<_> = self + let stale_list: Vec<_> = self .prev_pid_stats .iter() .filter(|&(_, &v)| current_instant.duration_since(v.1).as_secs() > self.stale_max_seconds) diff --git a/src/app/data_collection/cpu.rs b/src/app/data_collection/cpu.rs index 0a44bac8..0fd5d233 100644 --- a/src/app/data_collection/cpu.rs +++ b/src/app/data_collection/cpu.rs @@ -3,29 +3,29 @@ use sysinfo::{ProcessorExt, System, SystemExt}; #[derive(Clone)] pub struct CPUData { - pub cpu_name : Box, - pub cpu_usage : f64, + pub cpu_name: Box, + pub cpu_usage: f64, } #[derive(Clone)] pub struct CPUPackage { - pub cpu_vec : Vec, - pub instant : Instant, + pub cpu_vec: Vec, + pub instant: Instant, } -pub fn get_cpu_data_list(sys : &System) -> crate::utils::error::Result { +pub fn get_cpu_data_list(sys: &System) -> crate::utils::error::Result { let cpu_data = sys.get_processor_list(); let mut cpu_vec = Vec::new(); for cpu in cpu_data { cpu_vec.push(CPUData { - cpu_name : Box::from(cpu.get_name()), - cpu_usage : f64::from(cpu.get_cpu_usage()) * 100_f64, + cpu_name: Box::from(cpu.get_name()), + cpu_usage: f64::from(cpu.get_cpu_usage()) * 100_f64, }) } Ok(CPUPackage { cpu_vec, - instant : Instant::now(), + instant: Instant::now(), }) } diff --git a/src/app/data_collection/mem.rs b/src/app/data_collection/mem.rs index 929ee326..f4a8be1a 100644 --- a/src/app/data_collection/mem.rs +++ b/src/app/data_collection/mem.rs @@ -3,18 +3,18 @@ use std::time::Instant; #[derive(Clone)] pub struct MemData { - pub mem_total_in_mb : u64, - pub mem_used_in_mb : u64, - pub instant : Instant, + pub mem_total_in_mb: u64, + pub mem_used_in_mb: u64, + pub instant: Instant, } pub async fn get_mem_data_list() -> crate::utils::error::Result { let memory = heim::memory::memory().await?; Ok(MemData { - mem_total_in_mb : memory.total().get::(), - mem_used_in_mb : memory.total().get::() - memory.available().get::(), - instant : Instant::now(), + mem_total_in_mb: memory.total().get::(), + mem_used_in_mb: memory.total().get::() - memory.available().get::(), + instant: Instant::now(), }) } @@ -22,8 +22,8 @@ pub async fn get_swap_data_list() -> crate::utils::error::Result { let memory = heim::memory::swap().await?; Ok(MemData { - mem_total_in_mb : memory.total().get::(), - mem_used_in_mb : memory.used().get::(), - instant : Instant::now(), + mem_total_in_mb: memory.total().get::(), + mem_used_in_mb: memory.used().get::(), + instant: Instant::now(), }) } diff --git a/src/app/data_collection/processes.rs b/src/app/data_collection/processes.rs index 7e020968..982ebfaa 100644 --- a/src/app/data_collection/processes.rs +++ b/src/app/data_collection/processes.rs @@ -18,14 +18,14 @@ impl Default for ProcessSorting { // Possible process info struct? #[derive(Clone, Default)] pub struct ProcessData { - pub pid : u32, - pub cpu_usage_percent : f64, - pub mem_usage_percent : Option, - pub mem_usage_kb : Option, - pub command : String, + pub pid: u32, + pub cpu_usage_percent: f64, + pub mem_usage_percent: Option, + pub mem_usage_kb: Option, + pub command: String, } -fn vangelis_cpu_usage_calculation(prev_idle : &mut f64, prev_non_idle : &mut f64) -> std::io::Result<(f64, f64)> { +fn vangelis_cpu_usage_calculation(prev_idle: &mut f64, prev_non_idle: &mut f64) -> std::io::Result<(f64, f64)> { // Named after this SO answer: https://stackoverflow.com/a/23376195 let mut path = std::path::PathBuf::new(); path.push("/proc"); @@ -43,15 +43,15 @@ fn vangelis_cpu_usage_calculation(prev_idle : &mut f64, prev_non_idle : &mut f64 return Ok((1.0, 0.0)); // TODO: This is not the greatest... } - let user : f64 = val[1].parse::<_>().unwrap_or(0_f64); - let nice : f64 = val[2].parse::<_>().unwrap_or(0_f64); - let system : f64 = val[3].parse::<_>().unwrap_or(0_f64); - let idle : f64 = val[4].parse::<_>().unwrap_or(0_f64); - let iowait : f64 = val[5].parse::<_>().unwrap_or(0_f64); - let irq : f64 = val[6].parse::<_>().unwrap_or(0_f64); - let softirq : f64 = val[7].parse::<_>().unwrap_or(0_f64); - let steal : f64 = val[8].parse::<_>().unwrap_or(0_f64); - let guest : f64 = val[9].parse::<_>().unwrap_or(0_f64); + let user: f64 = val[1].parse::<_>().unwrap_or(0_f64); + let nice: f64 = val[2].parse::<_>().unwrap_or(0_f64); + let system: f64 = val[3].parse::<_>().unwrap_or(0_f64); + let idle: f64 = val[4].parse::<_>().unwrap_or(0_f64); + let iowait: f64 = val[5].parse::<_>().unwrap_or(0_f64); + let irq: f64 = val[6].parse::<_>().unwrap_or(0_f64); + let softirq: f64 = val[7].parse::<_>().unwrap_or(0_f64); + let steal: f64 = val[8].parse::<_>().unwrap_or(0_f64); + let guest: f64 = val[9].parse::<_>().unwrap_or(0_f64); let idle = idle + iowait; let non_idle = user + nice + system + irq + softirq + steal + guest; @@ -59,8 +59,8 @@ fn vangelis_cpu_usage_calculation(prev_idle : &mut f64, prev_non_idle : &mut f64 let total = idle + non_idle; let prev_total = *prev_idle + *prev_non_idle; - let total_delta : f64 = total - prev_total; - let idle_delta : f64 = idle - *prev_idle; + let total_delta: f64 = total - prev_total; + let idle_delta: f64 = idle - *prev_idle; //debug!("Vangelis function: CPU PERCENT: {}", (total_delta - idle_delta) / total_delta * 100_f64); @@ -69,8 +69,7 @@ fn vangelis_cpu_usage_calculation(prev_idle : &mut f64, prev_non_idle : &mut f64 let result = if total_delta - idle_delta != 0_f64 { total_delta - idle_delta - } - else { + } else { 1_f64 }; @@ -79,29 +78,25 @@ fn vangelis_cpu_usage_calculation(prev_idle : &mut f64, prev_non_idle : &mut f64 Ok((result, cpu_percentage)) // This works, REALLY damn well. The percentage check is within like 2% of the sysinfo one. } -fn get_ordering(a_val : T, b_val : T, reverse_order : bool) -> std::cmp::Ordering { +fn get_ordering(a_val: T, b_val: T, reverse_order: bool) -> std::cmp::Ordering { if a_val > b_val { if reverse_order { std::cmp::Ordering::Less - } - else { + } else { std::cmp::Ordering::Greater } - } - else if a_val < b_val { + } else if a_val < b_val { if reverse_order { std::cmp::Ordering::Greater - } - else { + } else { std::cmp::Ordering::Less } - } - else { + } else { std::cmp::Ordering::Equal } } -fn get_process_cpu_stats(pid : u32) -> std::io::Result { +fn get_process_cpu_stats(pid: u32) -> std::io::Result { let mut path = std::path::PathBuf::new(); path.push("/proc"); path.push(&pid.to_string()); @@ -118,14 +113,11 @@ fn get_process_cpu_stats(pid : u32) -> std::io::Result { } /// Note that cpu_percentage should be represented WITHOUT the \times 100 factor! -fn linux_cpu_usage( - pid : u32, cpu_usage : f64, cpu_percentage : f64, previous_pid_stats : &mut HashMap, -) -> std::io::Result { +fn linux_cpu_usage(pid: u32, cpu_usage: f64, cpu_percentage: f64, previous_pid_stats: &mut HashMap) -> std::io::Result { // Based heavily on https://stackoverflow.com/a/23376195 and https://stackoverflow.com/a/1424556 - let before_proc_val : f64 = if previous_pid_stats.contains_key(&pid.to_string()) { + let before_proc_val: f64 = if previous_pid_stats.contains_key(&pid.to_string()) { previous_pid_stats.get(&pid.to_string()).unwrap_or(&(0_f64, Instant::now())).0 - } - else { + } else { 0_f64 }; let after_proc_val = get_process_cpu_stats(pid)?; @@ -145,15 +137,15 @@ fn linux_cpu_usage( } fn convert_ps( - process : &str, cpu_usage : f64, cpu_percentage : f64, prev_pid_stats : &mut HashMap, + process: &str, cpu_usage: f64, cpu_percentage: f64, prev_pid_stats: &mut HashMap, ) -> std::io::Result { if process.trim().to_string().is_empty() { return Ok(ProcessData { - pid : 0, - command : "".to_string(), - mem_usage_percent : None, - mem_usage_kb : None, - cpu_usage_percent : 0_f64, + pid: 0, + command: "".to_string(), + mem_usage_percent: None, + mem_usage_kb: None, + cpu_usage_percent: 0_f64, }); } @@ -165,15 +157,15 @@ fn convert_ps( pid, command, mem_usage_percent, - mem_usage_kb : None, - cpu_usage_percent : linux_cpu_usage(pid, cpu_usage, cpu_percentage, prev_pid_stats)?, + mem_usage_kb: None, + cpu_usage_percent: linux_cpu_usage(pid, cpu_usage, cpu_percentage, prev_pid_stats)?, }) } pub async fn get_sorted_processes_list( - sys : &System, prev_idle : &mut f64, prev_non_idle : &mut f64, prev_pid_stats : &mut std::collections::HashMap, + sys: &System, prev_idle: &mut f64, prev_non_idle: &mut f64, prev_pid_stats: &mut std::collections::HashMap, ) -> crate::utils::error::Result> { - let mut process_vector : Vec = Vec::new(); + let mut process_vector: Vec = Vec::new(); if cfg!(target_os = "linux") { // Linux specific - this is a massive pain... ugh. @@ -192,26 +184,23 @@ pub async fn get_sorted_processes_list( } } } - } - else if cfg!(target_os = "windows") { + } else if cfg!(target_os = "windows") { // Windows let process_hashmap = sys.get_process_list(); for process_val in process_hashmap.values() { process_vector.push(ProcessData { - pid : process_val.pid() as u32, - command : process_val.name().to_string(), - mem_usage_percent : None, - mem_usage_kb : Some(process_val.memory()), - cpu_usage_percent : f64::from(process_val.cpu_usage()), + pid: process_val.pid() as u32, + command: process_val.name().to_string(), + mem_usage_percent: None, + mem_usage_kb: Some(process_val.memory()), + cpu_usage_percent: f64::from(process_val.cpu_usage()), }); } - } - else if cfg!(target_os = "macos") { + } else if cfg!(target_os = "macos") { // TODO: macOS debug!("Mac"); - } - else { + } else { // TODO: Others? debug!("Else"); // Solaris: https://stackoverflow.com/a/4453581 @@ -220,7 +209,7 @@ pub async fn get_sorted_processes_list( Ok(process_vector) } -pub fn sort_processes(process_vector : &mut Vec, sorting_method : &ProcessSorting, reverse_order : bool) { +pub fn sort_processes(process_vector: &mut Vec, sorting_method: &ProcessSorting, reverse_order: bool) { match sorting_method { // Always sort alphabetically first! ProcessSorting::CPU => { diff --git a/src/app/process_killer.rs b/src/app/process_killer.rs index 06ebeb0e..46396a78 100644 --- a/src/app/process_killer.rs +++ b/src/app/process_killer.rs @@ -18,7 +18,7 @@ struct Process(HANDLE); #[cfg(target_os = "windows")] impl Process { - fn open(pid : DWORD) -> Result { + fn open(pid: DWORD) -> Result { let pc = unsafe { OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_TERMINATE, 0, pid) }; if pc == null_mut() { return Err("!OpenProcess".to_string()); @@ -33,23 +33,20 @@ impl Process { } /// Kills a process, given a PID. -pub fn kill_process_given_pid(pid : u64) -> crate::utils::error::Result<()> { +pub fn kill_process_given_pid(pid: u64) -> crate::utils::error::Result<()> { if cfg!(target_os = "linux") { // Linux Command::new("kill").arg(pid.to_string()).output()?; - } - else if cfg!(target_os = "windows") { + } else if cfg!(target_os = "windows") { #[cfg(target_os = "windows")] let process = Process::open(pid as DWORD)?; #[cfg(target_os = "windows")] process.kill()?; - } - else if cfg!(target_os = "macos") { + } else if cfg!(target_os = "macos") { // TODO: macOS // See how sysinfo does it... https://docs.rs/sysinfo/0.9.5/sysinfo/trait.ProcessExt.html debug!("Sorry, macOS support is not implemented yet!"); - } - else { + } else { // TODO: Others? debug!("Sorry, other support this is not implemented yet!"); } diff --git a/src/canvas.rs b/src/canvas.rs index f8c50577..ca16f1f1 100644 --- a/src/canvas.rs +++ b/src/canvas.rs @@ -1,5 +1,5 @@ use crate::{app, constants, utils::error}; -use tui_temp_fork::{ +use tui::{ backend, layout::{Alignment, Constraint, Direction, Layout}, style::{Color, Modifier, Style}, @@ -7,7 +7,7 @@ use tui_temp_fork::{ Terminal, }; -const COLOUR_LIST : [Color; 6] = [ +const COLOUR_LIST: [Color; 6] = [ Color::Red, Color::Green, Color::LightYellow, @@ -15,29 +15,29 @@ const COLOUR_LIST : [Color; 6] = [ Color::LightCyan, Color::LightMagenta, ]; -const TEXT_COLOUR : Color = Color::Gray; -const GRAPH_COLOUR : Color = Color::Gray; -const BORDER_STYLE_COLOUR : Color = Color::Gray; -const HIGHLIGHTED_BORDER_STYLE_COLOUR : Color = Color::LightBlue; +const TEXT_COLOUR: Color = Color::Gray; +const GRAPH_COLOUR: Color = Color::Gray; +const BORDER_STYLE_COLOUR: Color = Color::Gray; +const HIGHLIGHTED_BORDER_STYLE_COLOUR: Color = Color::LightBlue; #[derive(Default)] pub struct CanvasData { - pub rx_display : String, - pub tx_display : String, - pub network_data_rx : Vec<(f64, f64)>, - pub network_data_tx : Vec<(f64, f64)>, - pub disk_data : Vec>, - pub temp_sensor_data : Vec>, - pub process_data : Vec>, - pub mem_data : Vec<(f64, f64)>, - pub mem_values : Vec<(u64, u64)>, - pub swap_data : Vec<(f64, f64)>, - pub cpu_data : Vec<(String, Vec<(f64, f64)>)>, + pub rx_display: String, + pub tx_display: String, + pub network_data_rx: Vec<(f64, f64)>, + pub network_data_tx: Vec<(f64, f64)>, + pub disk_data: Vec>, + pub temp_sensor_data: Vec>, + pub process_data: Vec>, + pub mem_data: Vec<(f64, f64)>, + pub mem_values: Vec<(u64, u64)>, + pub swap_data: Vec<(f64, f64)>, + pub cpu_data: Vec<(String, Vec<(f64, f64)>)>, } -pub fn draw_data(terminal : &mut Terminal, app_state : &mut app::App, canvas_data : &CanvasData) -> error::Result<()> { - let border_style : Style = Style::default().fg(BORDER_STYLE_COLOUR); - let highlighted_border_style : Style = Style::default().fg(HIGHLIGHTED_BORDER_STYLE_COLOUR); +pub fn draw_data(terminal: &mut Terminal, app_state: &mut app::App, canvas_data: &CanvasData) -> error::Result<()> { + let border_style: Style = Style::default().fg(BORDER_STYLE_COLOUR); + let highlighted_border_style: Style = Style::default().fg(HIGHLIGHTED_BORDER_STYLE_COLOUR); terminal.autoresize()?; terminal.draw(|mut f| { @@ -80,8 +80,7 @@ pub fn draw_data(terminal : &mut Terminal, app_state : .alignment(Alignment::Left) .wrap(true) .render(&mut f, middle_dialog_chunk[1]); - } - else { + } else { let vertical_chunks = Layout::default() .direction(Direction::Vertical) .margin(1) @@ -109,7 +108,7 @@ pub fn draw_data(terminal : &mut Terminal, app_state : // Set up blocks and their components // CPU usage graph { - let x_axis : Axis = Axis::default() + let x_axis: Axis = Axis::default() .style(Style::default().fg(GRAPH_COLOUR)) .bounds([0.0, constants::TIME_STARTS_FROM as f64 * 10.0]); let y_axis = Axis::default() @@ -117,7 +116,7 @@ pub fn draw_data(terminal : &mut Terminal, app_state : .bounds([-0.5, 100.5]) .labels(&["0%", "100%"]); - let mut dataset_vector : Vec = Vec::new(); + let mut dataset_vector: Vec = Vec::new(); for (i, cpu) in canvas_data.cpu_data.iter().enumerate() { let mut avg_cpu_exist_offset = 0; @@ -125,8 +124,7 @@ pub fn draw_data(terminal : &mut Terminal, app_state : if i == 0 { // Skip, we want to render the average cpu last! continue; - } - else { + } else { avg_cpu_exist_offset = 1; } } @@ -168,7 +166,7 @@ pub fn draw_data(terminal : &mut Terminal, app_state : //Memory usage graph { - let x_axis : Axis = Axis::default() + let x_axis: Axis = Axis::default() .style(Style::default().fg(GRAPH_COLOUR)) .bounds([0.0, constants::TIME_STARTS_FROM as f64 * 10.0]); let y_axis = Axis::default() @@ -183,9 +181,9 @@ pub fn draw_data(terminal : &mut Terminal, app_state : canvas_data.mem_values[0].0 as f64 / 1024.0, canvas_data.mem_values[0].1 as f64 / 1024.0 ); - let swap_name : String; + let swap_name: String; - let mut mem_canvas_vec : Vec = vec![Dataset::default() + let mut mem_canvas_vec: Vec = vec![Dataset::default() .name(&mem_name) .marker(if app_state.use_dot { Marker::Dot } else { Marker::Braille }) .style(Style::default().fg(Color::LightBlue)) @@ -238,7 +236,7 @@ pub fn draw_data(terminal : &mut Terminal, app_state : &mut app_state.currently_selected_temperature_position, ); - let sliced_vec : Vec> = (&canvas_data.temp_sensor_data[start_position as usize..]).to_vec(); + let sliced_vec: Vec> = (&canvas_data.temp_sensor_data[start_position as usize..]).to_vec(); let mut disk_counter = 0; let temperature_rows = sliced_vec.iter().map(|disk| { @@ -247,8 +245,7 @@ pub fn draw_data(terminal : &mut Terminal, app_state : if disk_counter == app_state.currently_selected_temperature_position - start_position { disk_counter = -1; Style::default().fg(Color::Black).bg(Color::Cyan) - } - else { + } else { if disk_counter >= 0 { disk_counter += 1; } @@ -283,7 +280,7 @@ pub fn draw_data(terminal : &mut Terminal, app_state : &mut app_state.currently_selected_disk_position, ); - let sliced_vec : Vec> = (&canvas_data.disk_data[start_position as usize..]).to_vec(); + let sliced_vec: Vec> = (&canvas_data.disk_data[start_position as usize..]).to_vec(); let mut disk_counter = 0; let disk_rows = sliced_vec.iter().map(|disk| { @@ -292,8 +289,7 @@ pub fn draw_data(terminal : &mut Terminal, app_state : if disk_counter == app_state.currently_selected_disk_position - start_position { disk_counter = -1; Style::default().fg(Color::Black).bg(Color::Cyan) - } - else { + } else { if disk_counter >= 0 { disk_counter += 1; } @@ -329,7 +325,7 @@ pub fn draw_data(terminal : &mut Terminal, app_state : // Network graph { - let x_axis : Axis = Axis::default().style(Style::default().fg(GRAPH_COLOUR)).bounds([0.0, 600_000.0]); + let x_axis: Axis = Axis::default().style(Style::default().fg(GRAPH_COLOUR)).bounds([0.0, 600_000.0]); let y_axis = Axis::default() .style(Style::default().fg(GRAPH_COLOUR)) .bounds([-0.5, 1_000_000.5]) @@ -384,7 +380,7 @@ pub fn draw_data(terminal : &mut Terminal, app_state : start_position, app_state.previous_process_position, app_state.currently_selected_process_position, num_rows );*/ - let sliced_vec : Vec> = (&canvas_data.process_data[start_position as usize..]).to_vec(); + let sliced_vec: Vec> = (&canvas_data.process_data[start_position as usize..]).to_vec(); let mut process_counter = 0; let process_rows = sliced_vec.iter().map(|process| { @@ -393,8 +389,7 @@ pub fn draw_data(terminal : &mut Terminal, app_state : if process_counter == app_state.currently_selected_process_position - start_position { process_counter = -1; Style::default().fg(Color::Black).bg(Color::Cyan) - } - else { + } else { if process_counter >= 0 { process_counter += 1; } @@ -412,8 +407,7 @@ pub fn draw_data(terminal : &mut Terminal, app_state : let direction_val = if app_state.process_sorting_reverse { "⯆".to_string() - } - else { + } else { "⯅".to_string() }; @@ -453,17 +447,15 @@ pub fn draw_data(terminal : &mut Terminal, app_state : } fn get_start_position( - num_rows : i64, scroll_direction : &app::ScrollDirection, previous_position : &mut i64, currently_selected_position : &mut i64, + num_rows: i64, scroll_direction: &app::ScrollDirection, previous_position: &mut i64, currently_selected_position: &mut i64, ) -> i64 { match scroll_direction { app::ScrollDirection::DOWN => { if *currently_selected_position < num_rows { 0 - } - else if *currently_selected_position - num_rows < *previous_position { + } else if *currently_selected_position - num_rows < *previous_position { *previous_position - } - else { + } else { *previous_position = *currently_selected_position - num_rows + 1; *previous_position } @@ -472,8 +464,7 @@ fn get_start_position( if *currently_selected_position == *previous_position - 1 { *previous_position = if *previous_position > 0 { *previous_position - 1 } else { 0 }; *previous_position - } - else { + } else { *previous_position } } diff --git a/src/constants.rs b/src/constants.rs index 98ab6aaf..be32a841 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -1,5 +1,5 @@ // TODO: Store like three minutes of data, then change how much is shown based on scaling! -pub const STALE_MAX_MILLISECONDS : u64 = 180 * 1000; // We wish to store at most 60 seconds worth of data. This may change in the future, or be configurable. -pub const TIME_STARTS_FROM : u64 = 60 * 1000; // TODO: Fix this -pub const TICK_RATE_IN_MILLISECONDS : u64 = 200; // We use this as it's a good value to work with. -pub const DEFAULT_REFRESH_RATE_IN_MILLISECONDS : u128 = 1000; +pub const STALE_MAX_MILLISECONDS: u64 = 180 * 1000; // We wish to store at most 60 seconds worth of data. This may change in the future, or be configurable. +pub const TIME_STARTS_FROM: u64 = 60 * 1000; // TODO: Fix this +pub const TICK_RATE_IN_MILLISECONDS: u64 = 200; // We use this as it's a good value to work with. +pub const DEFAULT_REFRESH_RATE_IN_MILLISECONDS: u128 = 1000; diff --git a/src/convert_data.rs b/src/convert_data.rs index 28f280d4..864f68ba 100644 --- a/src/convert_data.rs +++ b/src/convert_data.rs @@ -1,13 +1,12 @@ use crate::{app::data_collection, constants}; use constants::*; -pub fn update_temp_row(app_data : &data_collection::Data, temp_type : &data_collection::temperature::TemperatureType) -> Vec> { - let mut sensor_vector : Vec> = Vec::new(); +pub fn update_temp_row(app_data: &data_collection::Data, temp_type: &data_collection::temperature::TemperatureType) -> Vec> { + let mut sensor_vector: Vec> = Vec::new(); if (&app_data.list_of_temperature_sensor).is_empty() { sensor_vector.push(vec!["No Sensors Found".to_string(), "".to_string()]) - } - else { + } else { for sensor in &app_data.list_of_temperature_sensor { sensor_vector.push(vec![ sensor.component_name.to_string(), @@ -24,8 +23,8 @@ pub fn update_temp_row(app_data : &data_collection::Data, temp_type : &data_coll sensor_vector } -pub fn update_disk_row(app_data : &data_collection::Data) -> Vec> { - let mut disk_vector : Vec> = Vec::new(); +pub fn update_disk_row(app_data: &data_collection::Data) -> Vec> { + let mut disk_vector: Vec> = Vec::new(); for disk in &app_data.list_of_disks { let io_activity = if app_data.list_of_io.len() > 2 { if let Some(io_package) = &app_data.list_of_io.last() { @@ -44,37 +43,29 @@ pub fn update_disk_row(app_data : &data_collection::Data) -> Vec> { ( if read_bytes_per_sec < 1024 { format!("{}B", read_bytes_per_sec) - } - else if read_bytes_per_sec < 1024 * 1024 { + } else if read_bytes_per_sec < 1024 * 1024 { format!("{}KB", read_bytes_per_sec / 1024) - } - else { + } else { format!("{}MB", read_bytes_per_sec / 1024 / 1024) }, if write_bytes_per_sec < 1024 { format!("{}B", write_bytes_per_sec) - } - else if write_bytes_per_sec < 1024 * 1024 { + } else if write_bytes_per_sec < 1024 * 1024 { format!("{}KB", write_bytes_per_sec / 1024) - } - else { + } else { format!("{}MB", write_bytes_per_sec / 1024 / 1024) }, ) - } - else { + } else { ("0B".to_string(), "0B".to_string()) } - } - else { + } else { ("0B".to_string(), "0B".to_string()) } - } - else { + } else { ("0B".to_string(), "0B".to_string()) } - } - else { + } else { ("0B".to_string(), "0B".to_string()) }; disk_vector.push(vec![ @@ -83,14 +74,12 @@ pub fn update_disk_row(app_data : &data_collection::Data) -> Vec> { format!("{:.0}%", disk.used_space as f64 / disk.total_space as f64 * 100_f64), if disk.free_space < 1024 { disk.free_space.to_string() + "MB" - } - else { + } else { (disk.free_space / 1024).to_string() + "GB" }, if disk.total_space < 1024 { disk.total_space.to_string() + "MB" - } - else { + } else { (disk.total_space / 1024).to_string() + "GB" }, io_activity.0, @@ -101,8 +90,8 @@ pub fn update_disk_row(app_data : &data_collection::Data) -> Vec> { disk_vector } -pub fn update_process_row(app_data : &data_collection::Data) -> Vec> { - let mut process_vector : Vec> = Vec::new(); +pub fn update_process_row(app_data: &data_collection::Data) -> Vec> { + let mut process_vector: Vec> = Vec::new(); for process in &app_data.list_of_processes { process_vector.push(vec![ @@ -113,16 +102,13 @@ pub fn update_process_row(app_data : &data_collection::Data) -> Vec> "{:.1}%", if let Some(mem_usage) = process.mem_usage_percent { mem_usage - } - else if let Some(mem_usage_kb) = process.mem_usage_kb { + } else if let Some(mem_usage_kb) = process.mem_usage_kb { if let Some(mem_data) = app_data.memory.last() { (mem_usage_kb / 1024) as f64 / mem_data.mem_total_in_mb as f64 * 100_f64 - } - else { + } else { 0_f64 } - } - else { + } else { 0_f64 } ), @@ -132,14 +118,14 @@ pub fn update_process_row(app_data : &data_collection::Data) -> Vec> process_vector } -pub fn update_cpu_data_points(show_avg_cpu : bool, app_data : &data_collection::Data) -> Vec<(String, Vec<(f64, f64)>)> { - let mut cpu_data_vector : Vec<(String, Vec<(f64, f64)>)> = Vec::new(); - let mut cpu_collection : Vec> = Vec::new(); +pub fn update_cpu_data_points(show_avg_cpu: bool, app_data: &data_collection::Data) -> Vec<(String, Vec<(f64, f64)>)> { + let mut cpu_data_vector: Vec<(String, Vec<(f64, f64)>)> = Vec::new(); + let mut cpu_collection: Vec> = Vec::new(); if !app_data.list_of_cpu_packages.is_empty() { // I'm sorry for the if statement but I couldn't be bothered here... for cpu_num in (if show_avg_cpu { 0 } else { 1 })..app_data.list_of_cpu_packages.last().unwrap().cpu_vec.len() { - let mut this_cpu_data : Vec<(f64, f64)> = Vec::new(); + let mut this_cpu_data: Vec<(f64, f64)> = Vec::new(); for data in &app_data.list_of_cpu_packages { let current_time = std::time::Instant::now(); @@ -186,24 +172,24 @@ pub fn update_cpu_data_points(show_avg_cpu : bool, app_data : &data_collection:: cpu_data_vector } -pub fn update_mem_data_points(app_data : &data_collection::Data) -> Vec<(f64, f64)> { +pub fn update_mem_data_points(app_data: &data_collection::Data) -> Vec<(f64, f64)> { convert_mem_data(&app_data.memory) } -pub fn update_swap_data_points(app_data : &data_collection::Data) -> Vec<(f64, f64)> { +pub fn update_swap_data_points(app_data: &data_collection::Data) -> Vec<(f64, f64)> { convert_mem_data(&app_data.swap) } -pub fn update_mem_data_values(app_data : &data_collection::Data) -> Vec<(u64, u64)> { - let mut result : Vec<(u64, u64)> = Vec::new(); +pub fn update_mem_data_values(app_data: &data_collection::Data) -> Vec<(u64, u64)> { + let mut result: Vec<(u64, u64)> = Vec::new(); result.push(get_most_recent_mem_values(&app_data.memory)); result.push(get_most_recent_mem_values(&app_data.swap)); result } -fn get_most_recent_mem_values(mem_data : &[data_collection::mem::MemData]) -> (u64, u64) { - let mut result : (u64, u64) = (0, 0); +fn get_most_recent_mem_values(mem_data: &[data_collection::mem::MemData]) -> (u64, u64) { + let mut result: (u64, u64) = (0, 0); if !mem_data.is_empty() { if let Some(most_recent) = mem_data.last() { @@ -215,8 +201,8 @@ fn get_most_recent_mem_values(mem_data : &[data_collection::mem::MemData]) -> (u result } -fn convert_mem_data(mem_data : &[data_collection::mem::MemData]) -> Vec<(f64, f64)> { - let mut result : Vec<(f64, f64)> = Vec::new(); +fn convert_mem_data(mem_data: &[data_collection::mem::MemData]) -> Vec<(f64, f64)> { + let mut result: Vec<(f64, f64)> = Vec::new(); for data in mem_data { let current_time = std::time::Instant::now(); @@ -224,8 +210,7 @@ fn convert_mem_data(mem_data : &[data_collection::mem::MemData]) -> Vec<(f64, f6 ((TIME_STARTS_FROM as f64 - current_time.duration_since(data.instant).as_millis() as f64) * 10_f64).floor(), if data.mem_total_in_mb == 0 { -1000.0 - } - else { + } else { data.mem_used_in_mb as f64 / data.mem_total_in_mb as f64 * 100_f64 }, ); @@ -248,19 +233,19 @@ fn convert_mem_data(mem_data : &[data_collection::mem::MemData]) -> Vec<(f64, f6 } pub struct ConvertedNetworkData { - pub rx : Vec<(f64, f64)>, - pub tx : Vec<(f64, f64)>, - pub rx_display : String, - pub tx_display : String, + pub rx: Vec<(f64, f64)>, + pub tx: Vec<(f64, f64)>, + pub rx_display: String, + pub tx_display: String, } -pub fn update_network_data_points(app_data : &data_collection::Data) -> ConvertedNetworkData { +pub fn update_network_data_points(app_data: &data_collection::Data) -> ConvertedNetworkData { convert_network_data_points(&app_data.network) } -pub fn convert_network_data_points(network_data : &[data_collection::network::NetworkData]) -> ConvertedNetworkData { - let mut rx : Vec<(f64, f64)> = Vec::new(); - let mut tx : Vec<(f64, f64)> = Vec::new(); +pub fn convert_network_data_points(network_data: &[data_collection::network::NetworkData]) -> ConvertedNetworkData { + let mut rx: Vec<(f64, f64)> = Vec::new(); + let mut tx: Vec<(f64, f64)> = Vec::new(); for data in network_data { let current_time = std::time::Instant::now(); @@ -303,18 +288,14 @@ pub fn convert_network_data_points(network_data : &[data_collection::network::Ne let num_bytes = last_num_bytes_entry.rx; if num_bytes < 1024 { format!("RX: {:4} B", num_bytes).to_string() - } - else if num_bytes < (1024 * 1024) { + } else if num_bytes < (1024 * 1024) { format!("RX: {:4}KB", num_bytes / 1024).to_string() - } - else if num_bytes < (1024 * 1024 * 1024) { + } else if num_bytes < (1024 * 1024 * 1024) { format!("RX: {:4}MB", num_bytes / 1024 / 1024).to_string() - } - else { + } else { format!("RX: {:4}GB", num_bytes / 1024 / 1024 / 1024).to_string() } - } - else { + } else { "0B".to_string() }; @@ -322,18 +303,14 @@ pub fn convert_network_data_points(network_data : &[data_collection::network::Ne let num_bytes = last_num_bytes_entry.tx; if num_bytes < 1024 { format!("TX: {:4} B", num_bytes).to_string() - } - else if num_bytes < (1024 * 1024) { + } else if num_bytes < (1024 * 1024) { format!("TX: {:4}KB", num_bytes / 1024).to_string() - } - else if num_bytes < (1024 * 1024 * 1024) { + } else if num_bytes < (1024 * 1024 * 1024) { format!("TX: {:4}MB", num_bytes / 1024 / 1024).to_string() - } - else { + } else { format!("TX: {:4}GB", num_bytes / 1024 / 1024 / 1024).to_string() } - } - else { + } else { "0B".to_string() }; diff --git a/src/main.rs b/src/main.rs index c9aa8a61..5b542fce 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,3 @@ -#![feature(async_closure)] - #[macro_use] extern crate log; #[macro_use] @@ -7,14 +5,17 @@ extern crate clap; #[macro_use] extern crate failure; -use crossterm::{input, AlternateScreen, InputEvent, KeyEvent, MouseButton, MouseEvent}; +use crossterm::{ + input::{input, InputEvent, KeyEvent, MouseButton, MouseEvent}, + screen::AlternateScreen, +}; use std::{ io::stdout, sync::mpsc, thread, time::{Duration, Instant}, }; -use tui_temp_fork::{backend::CrosstermBackend, Terminal}; +use tui::{backend::CrosstermBackend, Terminal}; pub mod app; mod utils { @@ -65,34 +66,30 @@ fn main() -> error::Result<()> { //.after_help("Themes:") // TODO: This and others disabled for now .get_matches(); - let update_rate_in_milliseconds : u128 = if matches.is_present("RATE_MILLIS") { + let update_rate_in_milliseconds: u128 = if matches.is_present("RATE_MILLIS") { matches .value_of("RATE_MILLIS") .unwrap_or(&constants::DEFAULT_REFRESH_RATE_IN_MILLISECONDS.to_string()) .parse::()? - } - else { + } else { constants::DEFAULT_REFRESH_RATE_IN_MILLISECONDS }; if update_rate_in_milliseconds < 250 { return Err(RustopError::InvalidArg { - message : "Please set your update rate to be greater than 250 milliseconds.".to_string(), + message: "Please set your update rate to be greater than 250 milliseconds.".to_string(), }); - } - else if update_rate_in_milliseconds > u128::from(std::u64::MAX) { + } else if update_rate_in_milliseconds > u128::from(std::u64::MAX) { return Err(RustopError::InvalidArg { - message : "Please set your update rate to be less than unsigned INT_MAX.".to_string(), + message: "Please set your update rate to be less than unsigned INT_MAX.".to_string(), }); } let temperature_type = if matches.is_present("FAHRENHEIT") { data_collection::temperature::TemperatureType::Fahrenheit - } - else if matches.is_present("KELVIN") { + } else if matches.is_present("KELVIN") { data_collection::temperature::TemperatureType::Kelvin - } - else { + } else { data_collection::temperature::TemperatureType::Celsius }; let show_average_cpu = matches.is_present("AVG_CPU"); @@ -144,8 +141,7 @@ fn main() -> error::Result<()> { _ => {} } } - } - else { + } else { let mut reader = input.read_async(); loop { if let Some(event) = reader.next() { @@ -200,8 +196,7 @@ fn main() -> error::Result<()> { // Fix for if you set a really long time for update periods (and just gives a faster first value) thread::sleep(Duration::from_millis(250)); first_run = false; - } - else { + } else { thread::sleep(Duration::from_millis(update_rate_in_milliseconds as u64)); } } diff --git a/src/utils/logging.rs b/src/utils/logging.rs index c9281109..b5e6f25f 100644 --- a/src/utils/logging.rs +++ b/src/utils/logging.rs @@ -9,14 +9,12 @@ pub fn init_logger() -> Result<(), fern::InitError> { message )) }) - .level(if cfg!(debug_assertions) { log::LevelFilter::Debug } else { log::LevelFilter::Info }) - .chain(if cfg!(debug_assertions) { - //std::fs::OpenOptions::new().write(true).create(true).append(false).open("debug.log")? - fern::log_file("debug.log")? - } - else { - fern::log_file("logging.log")? + .level(if cfg!(debug_assertions) { + log::LevelFilter::Debug + } else { + log::LevelFilter::Info }) + .chain(fern::log_file("debug.log")?) .apply()?; Ok(())