Update tui version... legends aren't showing up yet, will have to fork again.

This commit is contained in:
ClementTsang 2019-12-06 00:57:04 -05:00
parent 078cca4100
commit e7477ce517
13 changed files with 257 additions and 313 deletions

View File

@ -17,7 +17,7 @@ path = "src/main.rs"
[dependencies] [dependencies]
chrono = "0.4.9" chrono = "0.4.9"
clap = "2.33.0" clap = "2.33.0"
crossterm = "^0.10" crossterm = "0.13"
failure = "0.1.5" failure = "0.1.5"
futures-preview = "0.3.0-alpha.18" futures-preview = "0.3.0-alpha.18"
fern = "0.5" fern = "0.5"
@ -32,10 +32,8 @@ sysinfo = "0.9.4"
tokio = "0.2.0-alpha.4" tokio = "0.2.0-alpha.4"
winapi = "0.3.8" winapi = "0.3.8"
[dependencies.tui-temp-fork] [dependencies.tui]
#git = "https://github.com/ClementTsang/tui-rs" version = "0.7"
path = "../tui-rs"
version = "0.6"
default-features = false default-features = false
features = ['crossterm'] features = ['crossterm']

View File

@ -1,4 +1,5 @@
max_width = 150 max_width = 150
newline_style = "Unix"
reorder_imports = true reorder_imports = true
control_brace_style = "ClosingNextLine" control_brace_style = "ClosingNextLine"
fn_args_layout = "Compressed" fn_args_layout = "Compressed"

View File

@ -21,56 +21,55 @@ pub enum ScrollDirection {
} }
pub struct App { pub struct App {
pub process_sorting_type : processes::ProcessSorting, pub process_sorting_type: processes::ProcessSorting,
pub process_sorting_reverse : bool, pub process_sorting_reverse: bool,
pub to_be_resorted : bool, pub to_be_resorted: bool,
pub currently_selected_process_position : i64, pub currently_selected_process_position: i64,
pub currently_selected_disk_position : i64, pub currently_selected_disk_position: i64,
pub currently_selected_temperature_position : i64, pub currently_selected_temperature_position: i64,
pub temperature_type : temperature::TemperatureType, pub temperature_type: temperature::TemperatureType,
pub update_rate_in_milliseconds : u64, pub update_rate_in_milliseconds: u64,
pub show_average_cpu : bool, pub show_average_cpu: bool,
pub current_application_position : ApplicationPosition, pub current_application_position: ApplicationPosition,
pub current_zoom_level_percent : f64, // Make at most 200, least 50? pub current_zoom_level_percent: f64, // Make at most 200, least 50?
pub data : data_collection::Data, pub data: data_collection::Data,
pub scroll_direction : ScrollDirection, pub scroll_direction: ScrollDirection,
pub previous_disk_position : i64, pub previous_disk_position: i64,
pub previous_temp_position : i64, pub previous_temp_position: i64,
pub previous_process_position : i64, pub previous_process_position: i64,
awaiting_second_d : bool, awaiting_second_d: bool,
pub use_dot : bool, pub use_dot: bool,
pub show_help : bool, pub show_help: bool,
pub is_frozen : bool, pub is_frozen: bool,
} }
impl App { 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 { App {
process_sorting_type : processes::ProcessSorting::CPU, process_sorting_type: processes::ProcessSorting::CPU,
process_sorting_reverse : true, process_sorting_reverse: true,
to_be_resorted : false, to_be_resorted: false,
currently_selected_process_position : 0, currently_selected_process_position: 0,
currently_selected_disk_position : 0, currently_selected_disk_position: 0,
currently_selected_temperature_position : 0, currently_selected_temperature_position: 0,
temperature_type, temperature_type,
update_rate_in_milliseconds, update_rate_in_milliseconds,
show_average_cpu, show_average_cpu,
current_application_position : ApplicationPosition::PROCESS, current_application_position: ApplicationPosition::PROCESS,
current_zoom_level_percent : 100.0, current_zoom_level_percent: 100.0,
data : data_collection::Data::default(), data: data_collection::Data::default(),
scroll_direction : ScrollDirection::DOWN, scroll_direction: ScrollDirection::DOWN,
previous_process_position : 0, previous_process_position: 0,
previous_disk_position : 0, previous_disk_position: 0,
previous_temp_position : 0, previous_temp_position: 0,
awaiting_second_d : false, awaiting_second_d: false,
use_dot, use_dot,
show_help : false, show_help: false,
is_frozen : false, is_frozen: false,
} }
} }
pub fn on_enter(&mut self) { pub fn on_enter(&mut self) {}
}
pub fn on_esc(&mut self) { pub fn on_esc(&mut self) {
if self.show_help { 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? // 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 { if !self.show_help {
match c { match c {
'd' => { 'd' => {
if self.awaiting_second_d { if self.awaiting_second_d {
self.awaiting_second_d = false; self.awaiting_second_d = false;
self.kill_highlighted_process().unwrap_or(()); self.kill_highlighted_process().unwrap_or(());
} } else {
else {
self.awaiting_second_d = true; self.awaiting_second_d = true;
} }
} }
@ -223,7 +221,7 @@ impl App {
self.scroll_direction = ScrollDirection::DOWN; 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 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 && 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 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 && 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 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 && self.currently_selected_disk_position + num_to_change_by < self.data.list_of_disks.len() as i64
{ {

View File

@ -11,13 +11,13 @@ pub mod network;
pub mod processes; pub mod processes;
pub mod temperature; pub mod temperature;
fn set_if_valid<T : std::clone::Clone>(result : &Result<T, crate::utils::error::RustopError>, value_to_set : &mut T) { fn set_if_valid<T: std::clone::Clone>(result: &Result<T, crate::utils::error::RustopError>, value_to_set: &mut T) {
if let Ok(result) = result { if let Ok(result) = result {
*value_to_set = (*result).clone(); *value_to_set = (*result).clone();
} }
} }
fn push_if_valid<T : std::clone::Clone>(result : &Result<T, crate::utils::error::RustopError>, vector_to_push : &mut Vec<T>) { fn push_if_valid<T: std::clone::Clone>(result: &Result<T, crate::utils::error::RustopError>, vector_to_push: &mut Vec<T>) {
if let Ok(result) = result { if let Ok(result) = result {
vector_to_push.push(result.clone()); vector_to_push.push(result.clone());
} }
@ -25,47 +25,47 @@ fn push_if_valid<T : std::clone::Clone>(result : &Result<T, crate::utils::error:
#[derive(Default, Clone)] #[derive(Default, Clone)]
pub struct Data { pub struct Data {
pub list_of_cpu_packages : Vec<cpu::CPUPackage>, pub list_of_cpu_packages: Vec<cpu::CPUPackage>,
pub list_of_io : Vec<disks::IOPackage>, pub list_of_io: Vec<disks::IOPackage>,
pub list_of_physical_io : Vec<disks::IOPackage>, pub list_of_physical_io: Vec<disks::IOPackage>,
pub memory : Vec<mem::MemData>, pub memory: Vec<mem::MemData>,
pub swap : Vec<mem::MemData>, pub swap: Vec<mem::MemData>,
pub list_of_temperature_sensor : Vec<temperature::TempData>, pub list_of_temperature_sensor: Vec<temperature::TempData>,
pub network : Vec<network::NetworkData>, pub network: Vec<network::NetworkData>,
pub list_of_processes : Vec<processes::ProcessData>, // Only need to keep a list of processes... pub list_of_processes: Vec<processes::ProcessData>, // Only need to keep a list of processes...
pub list_of_disks : Vec<disks::DiskData>, // Only need to keep a list of disks and their data pub list_of_disks: Vec<disks::DiskData>, // Only need to keep a list of disks and their data
} }
pub struct DataState { pub struct DataState {
pub data : Data, pub data: Data,
first_run : bool, first_run: bool,
sys : System, sys: System,
stale_max_seconds : u64, stale_max_seconds: u64,
prev_pid_stats : HashMap<String, (f64, Instant)>, prev_pid_stats: HashMap<String, (f64, Instant)>,
prev_idle : f64, prev_idle: f64,
prev_non_idle : f64, prev_non_idle: f64,
temperature_type : temperature::TemperatureType, temperature_type: temperature::TemperatureType,
last_clean : Instant, // Last time stale data was cleared last_clean: Instant, // Last time stale data was cleared
} }
impl Default for DataState { impl Default for DataState {
fn default() -> Self { fn default() -> Self {
DataState { DataState {
data : Data::default(), data: Data::default(),
first_run : true, first_run: true,
sys : System::new(), sys: System::new(),
stale_max_seconds : constants::STALE_MAX_MILLISECONDS / 1000, stale_max_seconds: constants::STALE_MAX_MILLISECONDS / 1000,
prev_pid_stats : HashMap::new(), prev_pid_stats: HashMap::new(),
prev_idle : 0_f64, prev_idle: 0_f64,
prev_non_idle : 0_f64, prev_non_idle: 0_f64,
temperature_type : temperature::TemperatureType::Celsius, temperature_type: temperature::TemperatureType::Celsius,
last_clean : Instant::now(), last_clean: Instant::now(),
} }
} }
} }
impl DataState { 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; self.temperature_type = temperature_type;
} }
@ -113,7 +113,7 @@ impl DataState {
let current_instant = std::time::Instant::now(); let current_instant = std::time::Instant::now();
if current_instant.duration_since(self.last_clean).as_secs() > self.stale_max_seconds { 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 .prev_pid_stats
.iter() .iter()
.filter(|&(_, &v)| current_instant.duration_since(v.1).as_secs() > self.stale_max_seconds) .filter(|&(_, &v)| current_instant.duration_since(v.1).as_secs() > self.stale_max_seconds)

View File

@ -3,29 +3,29 @@ use sysinfo::{ProcessorExt, System, SystemExt};
#[derive(Clone)] #[derive(Clone)]
pub struct CPUData { pub struct CPUData {
pub cpu_name : Box<str>, pub cpu_name: Box<str>,
pub cpu_usage : f64, pub cpu_usage: f64,
} }
#[derive(Clone)] #[derive(Clone)]
pub struct CPUPackage { pub struct CPUPackage {
pub cpu_vec : Vec<CPUData>, pub cpu_vec: Vec<CPUData>,
pub instant : Instant, pub instant: Instant,
} }
pub fn get_cpu_data_list(sys : &System) -> crate::utils::error::Result<CPUPackage> { pub fn get_cpu_data_list(sys: &System) -> crate::utils::error::Result<CPUPackage> {
let cpu_data = sys.get_processor_list(); let cpu_data = sys.get_processor_list();
let mut cpu_vec = Vec::new(); let mut cpu_vec = Vec::new();
for cpu in cpu_data { for cpu in cpu_data {
cpu_vec.push(CPUData { cpu_vec.push(CPUData {
cpu_name : Box::from(cpu.get_name()), cpu_name: Box::from(cpu.get_name()),
cpu_usage : f64::from(cpu.get_cpu_usage()) * 100_f64, cpu_usage: f64::from(cpu.get_cpu_usage()) * 100_f64,
}) })
} }
Ok(CPUPackage { Ok(CPUPackage {
cpu_vec, cpu_vec,
instant : Instant::now(), instant: Instant::now(),
}) })
} }

View File

@ -3,18 +3,18 @@ use std::time::Instant;
#[derive(Clone)] #[derive(Clone)]
pub struct MemData { pub struct MemData {
pub mem_total_in_mb : u64, pub mem_total_in_mb: u64,
pub mem_used_in_mb : u64, pub mem_used_in_mb: u64,
pub instant : Instant, pub instant: Instant,
} }
pub async fn get_mem_data_list() -> crate::utils::error::Result<MemData> { pub async fn get_mem_data_list() -> crate::utils::error::Result<MemData> {
let memory = heim::memory::memory().await?; let memory = heim::memory::memory().await?;
Ok(MemData { Ok(MemData {
mem_total_in_mb : memory.total().get::<information::megabyte>(), mem_total_in_mb: memory.total().get::<information::megabyte>(),
mem_used_in_mb : memory.total().get::<information::megabyte>() - memory.available().get::<information::megabyte>(), mem_used_in_mb: memory.total().get::<information::megabyte>() - memory.available().get::<information::megabyte>(),
instant : Instant::now(), instant: Instant::now(),
}) })
} }
@ -22,8 +22,8 @@ pub async fn get_swap_data_list() -> crate::utils::error::Result<MemData> {
let memory = heim::memory::swap().await?; let memory = heim::memory::swap().await?;
Ok(MemData { Ok(MemData {
mem_total_in_mb : memory.total().get::<information::megabyte>(), mem_total_in_mb: memory.total().get::<information::megabyte>(),
mem_used_in_mb : memory.used().get::<information::megabyte>(), mem_used_in_mb: memory.used().get::<information::megabyte>(),
instant : Instant::now(), instant: Instant::now(),
}) })
} }

View File

@ -18,14 +18,14 @@ impl Default for ProcessSorting {
// Possible process info struct? // Possible process info struct?
#[derive(Clone, Default)] #[derive(Clone, Default)]
pub struct ProcessData { pub struct ProcessData {
pub pid : u32, pub pid: u32,
pub cpu_usage_percent : f64, pub cpu_usage_percent: f64,
pub mem_usage_percent : Option<f64>, pub mem_usage_percent: Option<f64>,
pub mem_usage_kb : Option<u64>, pub mem_usage_kb: Option<u64>,
pub command : String, 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 // Named after this SO answer: https://stackoverflow.com/a/23376195
let mut path = std::path::PathBuf::new(); let mut path = std::path::PathBuf::new();
path.push("/proc"); 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... return Ok((1.0, 0.0)); // TODO: This is not the greatest...
} }
let user : f64 = val[1].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 nice: f64 = val[2].parse::<_>().unwrap_or(0_f64);
let system : f64 = val[3].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 idle: f64 = val[4].parse::<_>().unwrap_or(0_f64);
let iowait : f64 = val[5].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 irq: f64 = val[6].parse::<_>().unwrap_or(0_f64);
let softirq : f64 = val[7].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 steal: f64 = val[8].parse::<_>().unwrap_or(0_f64);
let guest : f64 = val[9].parse::<_>().unwrap_or(0_f64); let guest: f64 = val[9].parse::<_>().unwrap_or(0_f64);
let idle = idle + iowait; let idle = idle + iowait;
let non_idle = user + nice + system + irq + softirq + steal + guest; 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 total = idle + non_idle;
let prev_total = *prev_idle + *prev_non_idle; let prev_total = *prev_idle + *prev_non_idle;
let total_delta : f64 = total - prev_total; let total_delta: f64 = total - prev_total;
let idle_delta : f64 = idle - *prev_idle; let idle_delta: f64 = idle - *prev_idle;
//debug!("Vangelis function: CPU PERCENT: {}", (total_delta - idle_delta) / total_delta * 100_f64); //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 { let result = if total_delta - idle_delta != 0_f64 {
total_delta - idle_delta total_delta - idle_delta
} } else {
else {
1_f64 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. Ok((result, cpu_percentage)) // This works, REALLY damn well. The percentage check is within like 2% of the sysinfo one.
} }
fn get_ordering<T : std::cmp::PartialOrd>(a_val : T, b_val : T, reverse_order : bool) -> std::cmp::Ordering { fn get_ordering<T: std::cmp::PartialOrd>(a_val: T, b_val: T, reverse_order: bool) -> std::cmp::Ordering {
if a_val > b_val { if a_val > b_val {
if reverse_order { if reverse_order {
std::cmp::Ordering::Less std::cmp::Ordering::Less
} } else {
else {
std::cmp::Ordering::Greater std::cmp::Ordering::Greater
} }
} } else if a_val < b_val {
else if a_val < b_val {
if reverse_order { if reverse_order {
std::cmp::Ordering::Greater std::cmp::Ordering::Greater
} } else {
else {
std::cmp::Ordering::Less std::cmp::Ordering::Less
} }
} } else {
else {
std::cmp::Ordering::Equal std::cmp::Ordering::Equal
} }
} }
fn get_process_cpu_stats(pid : u32) -> std::io::Result<f64> { fn get_process_cpu_stats(pid: u32) -> std::io::Result<f64> {
let mut path = std::path::PathBuf::new(); let mut path = std::path::PathBuf::new();
path.push("/proc"); path.push("/proc");
path.push(&pid.to_string()); path.push(&pid.to_string());
@ -118,14 +113,11 @@ fn get_process_cpu_stats(pid : u32) -> std::io::Result<f64> {
} }
/// Note that cpu_percentage should be represented WITHOUT the \times 100 factor! /// Note that cpu_percentage should be represented WITHOUT the \times 100 factor!
fn linux_cpu_usage( fn linux_cpu_usage(pid: u32, cpu_usage: f64, cpu_percentage: f64, previous_pid_stats: &mut HashMap<String, (f64, Instant)>) -> std::io::Result<f64> {
pid : u32, cpu_usage : f64, cpu_percentage : f64, previous_pid_stats : &mut HashMap<String, (f64, Instant)>,
) -> std::io::Result<f64> {
// Based heavily on https://stackoverflow.com/a/23376195 and https://stackoverflow.com/a/1424556 // 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 previous_pid_stats.get(&pid.to_string()).unwrap_or(&(0_f64, Instant::now())).0
} } else {
else {
0_f64 0_f64
}; };
let after_proc_val = get_process_cpu_stats(pid)?; let after_proc_val = get_process_cpu_stats(pid)?;
@ -145,15 +137,15 @@ fn linux_cpu_usage(
} }
fn convert_ps( fn convert_ps(
process : &str, cpu_usage : f64, cpu_percentage : f64, prev_pid_stats : &mut HashMap<String, (f64, Instant)>, process: &str, cpu_usage: f64, cpu_percentage: f64, prev_pid_stats: &mut HashMap<String, (f64, Instant)>,
) -> std::io::Result<ProcessData> { ) -> std::io::Result<ProcessData> {
if process.trim().to_string().is_empty() { if process.trim().to_string().is_empty() {
return Ok(ProcessData { return Ok(ProcessData {
pid : 0, pid: 0,
command : "".to_string(), command: "".to_string(),
mem_usage_percent : None, mem_usage_percent: None,
mem_usage_kb : None, mem_usage_kb: None,
cpu_usage_percent : 0_f64, cpu_usage_percent: 0_f64,
}); });
} }
@ -165,15 +157,15 @@ fn convert_ps(
pid, pid,
command, command,
mem_usage_percent, mem_usage_percent,
mem_usage_kb : None, mem_usage_kb: None,
cpu_usage_percent : linux_cpu_usage(pid, cpu_usage, cpu_percentage, prev_pid_stats)?, cpu_usage_percent: linux_cpu_usage(pid, cpu_usage, cpu_percentage, prev_pid_stats)?,
}) })
} }
pub async fn get_sorted_processes_list( 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<String, (f64, Instant)>, sys: &System, prev_idle: &mut f64, prev_non_idle: &mut f64, prev_pid_stats: &mut std::collections::HashMap<String, (f64, Instant)>,
) -> crate::utils::error::Result<Vec<ProcessData>> { ) -> crate::utils::error::Result<Vec<ProcessData>> {
let mut process_vector : Vec<ProcessData> = Vec::new(); let mut process_vector: Vec<ProcessData> = Vec::new();
if cfg!(target_os = "linux") { if cfg!(target_os = "linux") {
// Linux specific - this is a massive pain... ugh. // 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 // Windows
let process_hashmap = sys.get_process_list(); let process_hashmap = sys.get_process_list();
for process_val in process_hashmap.values() { for process_val in process_hashmap.values() {
process_vector.push(ProcessData { process_vector.push(ProcessData {
pid : process_val.pid() as u32, pid: process_val.pid() as u32,
command : process_val.name().to_string(), command: process_val.name().to_string(),
mem_usage_percent : None, mem_usage_percent: None,
mem_usage_kb : Some(process_val.memory()), mem_usage_kb: Some(process_val.memory()),
cpu_usage_percent : f64::from(process_val.cpu_usage()), cpu_usage_percent: f64::from(process_val.cpu_usage()),
}); });
} }
} } else if cfg!(target_os = "macos") {
else if cfg!(target_os = "macos") {
// TODO: macOS // TODO: macOS
debug!("Mac"); debug!("Mac");
} } else {
else {
// TODO: Others? // TODO: Others?
debug!("Else"); debug!("Else");
// Solaris: https://stackoverflow.com/a/4453581 // Solaris: https://stackoverflow.com/a/4453581
@ -220,7 +209,7 @@ pub async fn get_sorted_processes_list(
Ok(process_vector) Ok(process_vector)
} }
pub fn sort_processes(process_vector : &mut Vec<ProcessData>, sorting_method : &ProcessSorting, reverse_order : bool) { pub fn sort_processes(process_vector: &mut Vec<ProcessData>, sorting_method: &ProcessSorting, reverse_order: bool) {
match sorting_method { match sorting_method {
// Always sort alphabetically first! // Always sort alphabetically first!
ProcessSorting::CPU => { ProcessSorting::CPU => {

View File

@ -18,7 +18,7 @@ struct Process(HANDLE);
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
impl Process { impl Process {
fn open(pid : DWORD) -> Result<Process, String> { fn open(pid: DWORD) -> Result<Process, String> {
let pc = unsafe { OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_TERMINATE, 0, pid) }; let pc = unsafe { OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_TERMINATE, 0, pid) };
if pc == null_mut() { if pc == null_mut() {
return Err("!OpenProcess".to_string()); return Err("!OpenProcess".to_string());
@ -33,23 +33,20 @@ impl Process {
} }
/// Kills a process, given a PID. /// 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") { if cfg!(target_os = "linux") {
// Linux // Linux
Command::new("kill").arg(pid.to_string()).output()?; Command::new("kill").arg(pid.to_string()).output()?;
} } else if cfg!(target_os = "windows") {
else if cfg!(target_os = "windows") {
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
let process = Process::open(pid as DWORD)?; let process = Process::open(pid as DWORD)?;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
process.kill()?; process.kill()?;
} } else if cfg!(target_os = "macos") {
else if cfg!(target_os = "macos") {
// TODO: macOS // TODO: macOS
// See how sysinfo does it... https://docs.rs/sysinfo/0.9.5/sysinfo/trait.ProcessExt.html // See how sysinfo does it... https://docs.rs/sysinfo/0.9.5/sysinfo/trait.ProcessExt.html
debug!("Sorry, macOS support is not implemented yet!"); debug!("Sorry, macOS support is not implemented yet!");
} } else {
else {
// TODO: Others? // TODO: Others?
debug!("Sorry, other support this is not implemented yet!"); debug!("Sorry, other support this is not implemented yet!");
} }

View File

@ -1,5 +1,5 @@
use crate::{app, constants, utils::error}; use crate::{app, constants, utils::error};
use tui_temp_fork::{ use tui::{
backend, backend,
layout::{Alignment, Constraint, Direction, Layout}, layout::{Alignment, Constraint, Direction, Layout},
style::{Color, Modifier, Style}, style::{Color, Modifier, Style},
@ -7,7 +7,7 @@ use tui_temp_fork::{
Terminal, Terminal,
}; };
const COLOUR_LIST : [Color; 6] = [ const COLOUR_LIST: [Color; 6] = [
Color::Red, Color::Red,
Color::Green, Color::Green,
Color::LightYellow, Color::LightYellow,
@ -15,29 +15,29 @@ const COLOUR_LIST : [Color; 6] = [
Color::LightCyan, Color::LightCyan,
Color::LightMagenta, Color::LightMagenta,
]; ];
const TEXT_COLOUR : Color = Color::Gray; const TEXT_COLOUR: Color = Color::Gray;
const GRAPH_COLOUR : Color = Color::Gray; const GRAPH_COLOUR: Color = Color::Gray;
const BORDER_STYLE_COLOUR : Color = Color::Gray; const BORDER_STYLE_COLOUR: Color = Color::Gray;
const HIGHLIGHTED_BORDER_STYLE_COLOUR : Color = Color::LightBlue; const HIGHLIGHTED_BORDER_STYLE_COLOUR: Color = Color::LightBlue;
#[derive(Default)] #[derive(Default)]
pub struct CanvasData { pub struct CanvasData {
pub rx_display : String, pub rx_display: String,
pub tx_display : String, pub tx_display: String,
pub network_data_rx : Vec<(f64, f64)>, pub network_data_rx: Vec<(f64, f64)>,
pub network_data_tx : Vec<(f64, f64)>, pub network_data_tx: Vec<(f64, f64)>,
pub disk_data : Vec<Vec<String>>, pub disk_data: Vec<Vec<String>>,
pub temp_sensor_data : Vec<Vec<String>>, pub temp_sensor_data: Vec<Vec<String>>,
pub process_data : Vec<Vec<String>>, pub process_data: Vec<Vec<String>>,
pub mem_data : Vec<(f64, f64)>, pub mem_data: Vec<(f64, f64)>,
pub mem_values : Vec<(u64, u64)>, pub mem_values: Vec<(u64, u64)>,
pub swap_data : Vec<(f64, f64)>, pub swap_data: Vec<(f64, f64)>,
pub cpu_data : Vec<(String, Vec<(f64, f64)>)>, pub cpu_data: Vec<(String, Vec<(f64, f64)>)>,
} }
pub fn draw_data<B : backend::Backend>(terminal : &mut Terminal<B>, app_state : &mut app::App, canvas_data : &CanvasData) -> error::Result<()> { pub fn draw_data<B: backend::Backend>(terminal: &mut Terminal<B>, app_state: &mut app::App, canvas_data: &CanvasData) -> error::Result<()> {
let border_style : Style = Style::default().fg(BORDER_STYLE_COLOUR); let border_style: Style = Style::default().fg(BORDER_STYLE_COLOUR);
let highlighted_border_style : Style = Style::default().fg(HIGHLIGHTED_BORDER_STYLE_COLOUR); let highlighted_border_style: Style = Style::default().fg(HIGHLIGHTED_BORDER_STYLE_COLOUR);
terminal.autoresize()?; terminal.autoresize()?;
terminal.draw(|mut f| { terminal.draw(|mut f| {
@ -80,8 +80,7 @@ pub fn draw_data<B : backend::Backend>(terminal : &mut Terminal<B>, app_state :
.alignment(Alignment::Left) .alignment(Alignment::Left)
.wrap(true) .wrap(true)
.render(&mut f, middle_dialog_chunk[1]); .render(&mut f, middle_dialog_chunk[1]);
} } else {
else {
let vertical_chunks = Layout::default() let vertical_chunks = Layout::default()
.direction(Direction::Vertical) .direction(Direction::Vertical)
.margin(1) .margin(1)
@ -109,7 +108,7 @@ pub fn draw_data<B : backend::Backend>(terminal : &mut Terminal<B>, app_state :
// Set up blocks and their components // Set up blocks and their components
// CPU usage graph // CPU usage graph
{ {
let x_axis : Axis<String> = Axis::default() let x_axis: Axis<String> = Axis::default()
.style(Style::default().fg(GRAPH_COLOUR)) .style(Style::default().fg(GRAPH_COLOUR))
.bounds([0.0, constants::TIME_STARTS_FROM as f64 * 10.0]); .bounds([0.0, constants::TIME_STARTS_FROM as f64 * 10.0]);
let y_axis = Axis::default() let y_axis = Axis::default()
@ -117,7 +116,7 @@ pub fn draw_data<B : backend::Backend>(terminal : &mut Terminal<B>, app_state :
.bounds([-0.5, 100.5]) .bounds([-0.5, 100.5])
.labels(&["0%", "100%"]); .labels(&["0%", "100%"]);
let mut dataset_vector : Vec<Dataset> = Vec::new(); let mut dataset_vector: Vec<Dataset> = Vec::new();
for (i, cpu) in canvas_data.cpu_data.iter().enumerate() { for (i, cpu) in canvas_data.cpu_data.iter().enumerate() {
let mut avg_cpu_exist_offset = 0; let mut avg_cpu_exist_offset = 0;
@ -125,8 +124,7 @@ pub fn draw_data<B : backend::Backend>(terminal : &mut Terminal<B>, app_state :
if i == 0 { if i == 0 {
// Skip, we want to render the average cpu last! // Skip, we want to render the average cpu last!
continue; continue;
} } else {
else {
avg_cpu_exist_offset = 1; avg_cpu_exist_offset = 1;
} }
} }
@ -168,7 +166,7 @@ pub fn draw_data<B : backend::Backend>(terminal : &mut Terminal<B>, app_state :
//Memory usage graph //Memory usage graph
{ {
let x_axis : Axis<String> = Axis::default() let x_axis: Axis<String> = Axis::default()
.style(Style::default().fg(GRAPH_COLOUR)) .style(Style::default().fg(GRAPH_COLOUR))
.bounds([0.0, constants::TIME_STARTS_FROM as f64 * 10.0]); .bounds([0.0, constants::TIME_STARTS_FROM as f64 * 10.0]);
let y_axis = Axis::default() let y_axis = Axis::default()
@ -183,9 +181,9 @@ pub fn draw_data<B : backend::Backend>(terminal : &mut Terminal<B>, app_state :
canvas_data.mem_values[0].0 as f64 / 1024.0, canvas_data.mem_values[0].0 as f64 / 1024.0,
canvas_data.mem_values[0].1 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<Dataset> = vec![Dataset::default() let mut mem_canvas_vec: Vec<Dataset> = vec![Dataset::default()
.name(&mem_name) .name(&mem_name)
.marker(if app_state.use_dot { Marker::Dot } else { Marker::Braille }) .marker(if app_state.use_dot { Marker::Dot } else { Marker::Braille })
.style(Style::default().fg(Color::LightBlue)) .style(Style::default().fg(Color::LightBlue))
@ -238,7 +236,7 @@ pub fn draw_data<B : backend::Backend>(terminal : &mut Terminal<B>, app_state :
&mut app_state.currently_selected_temperature_position, &mut app_state.currently_selected_temperature_position,
); );
let sliced_vec : Vec<Vec<String>> = (&canvas_data.temp_sensor_data[start_position as usize..]).to_vec(); let sliced_vec: Vec<Vec<String>> = (&canvas_data.temp_sensor_data[start_position as usize..]).to_vec();
let mut disk_counter = 0; let mut disk_counter = 0;
let temperature_rows = sliced_vec.iter().map(|disk| { let temperature_rows = sliced_vec.iter().map(|disk| {
@ -247,8 +245,7 @@ pub fn draw_data<B : backend::Backend>(terminal : &mut Terminal<B>, app_state :
if disk_counter == app_state.currently_selected_temperature_position - start_position { if disk_counter == app_state.currently_selected_temperature_position - start_position {
disk_counter = -1; disk_counter = -1;
Style::default().fg(Color::Black).bg(Color::Cyan) Style::default().fg(Color::Black).bg(Color::Cyan)
} } else {
else {
if disk_counter >= 0 { if disk_counter >= 0 {
disk_counter += 1; disk_counter += 1;
} }
@ -283,7 +280,7 @@ pub fn draw_data<B : backend::Backend>(terminal : &mut Terminal<B>, app_state :
&mut app_state.currently_selected_disk_position, &mut app_state.currently_selected_disk_position,
); );
let sliced_vec : Vec<Vec<String>> = (&canvas_data.disk_data[start_position as usize..]).to_vec(); let sliced_vec: Vec<Vec<String>> = (&canvas_data.disk_data[start_position as usize..]).to_vec();
let mut disk_counter = 0; let mut disk_counter = 0;
let disk_rows = sliced_vec.iter().map(|disk| { let disk_rows = sliced_vec.iter().map(|disk| {
@ -292,8 +289,7 @@ pub fn draw_data<B : backend::Backend>(terminal : &mut Terminal<B>, app_state :
if disk_counter == app_state.currently_selected_disk_position - start_position { if disk_counter == app_state.currently_selected_disk_position - start_position {
disk_counter = -1; disk_counter = -1;
Style::default().fg(Color::Black).bg(Color::Cyan) Style::default().fg(Color::Black).bg(Color::Cyan)
} } else {
else {
if disk_counter >= 0 { if disk_counter >= 0 {
disk_counter += 1; disk_counter += 1;
} }
@ -329,7 +325,7 @@ pub fn draw_data<B : backend::Backend>(terminal : &mut Terminal<B>, app_state :
// Network graph // Network graph
{ {
let x_axis : Axis<String> = Axis::default().style(Style::default().fg(GRAPH_COLOUR)).bounds([0.0, 600_000.0]); let x_axis: Axis<String> = Axis::default().style(Style::default().fg(GRAPH_COLOUR)).bounds([0.0, 600_000.0]);
let y_axis = Axis::default() let y_axis = Axis::default()
.style(Style::default().fg(GRAPH_COLOUR)) .style(Style::default().fg(GRAPH_COLOUR))
.bounds([-0.5, 1_000_000.5]) .bounds([-0.5, 1_000_000.5])
@ -384,7 +380,7 @@ pub fn draw_data<B : backend::Backend>(terminal : &mut Terminal<B>, app_state :
start_position, app_state.previous_process_position, app_state.currently_selected_process_position, num_rows start_position, app_state.previous_process_position, app_state.currently_selected_process_position, num_rows
);*/ );*/
let sliced_vec : Vec<Vec<String>> = (&canvas_data.process_data[start_position as usize..]).to_vec(); let sliced_vec: Vec<Vec<String>> = (&canvas_data.process_data[start_position as usize..]).to_vec();
let mut process_counter = 0; let mut process_counter = 0;
let process_rows = sliced_vec.iter().map(|process| { let process_rows = sliced_vec.iter().map(|process| {
@ -393,8 +389,7 @@ pub fn draw_data<B : backend::Backend>(terminal : &mut Terminal<B>, app_state :
if process_counter == app_state.currently_selected_process_position - start_position { if process_counter == app_state.currently_selected_process_position - start_position {
process_counter = -1; process_counter = -1;
Style::default().fg(Color::Black).bg(Color::Cyan) Style::default().fg(Color::Black).bg(Color::Cyan)
} } else {
else {
if process_counter >= 0 { if process_counter >= 0 {
process_counter += 1; process_counter += 1;
} }
@ -412,8 +407,7 @@ pub fn draw_data<B : backend::Backend>(terminal : &mut Terminal<B>, app_state :
let direction_val = if app_state.process_sorting_reverse { let direction_val = if app_state.process_sorting_reverse {
"".to_string() "".to_string()
} } else {
else {
"".to_string() "".to_string()
}; };
@ -453,17 +447,15 @@ pub fn draw_data<B : backend::Backend>(terminal : &mut Terminal<B>, app_state :
} }
fn get_start_position( 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 { ) -> i64 {
match scroll_direction { match scroll_direction {
app::ScrollDirection::DOWN => { app::ScrollDirection::DOWN => {
if *currently_selected_position < num_rows { if *currently_selected_position < num_rows {
0 0
} } else if *currently_selected_position - num_rows < *previous_position {
else if *currently_selected_position - num_rows < *previous_position {
*previous_position *previous_position
} } else {
else {
*previous_position = *currently_selected_position - num_rows + 1; *previous_position = *currently_selected_position - num_rows + 1;
*previous_position *previous_position
} }
@ -472,8 +464,7 @@ fn get_start_position(
if *currently_selected_position == *previous_position - 1 { if *currently_selected_position == *previous_position - 1 {
*previous_position = if *previous_position > 0 { *previous_position - 1 } else { 0 }; *previous_position = if *previous_position > 0 { *previous_position - 1 } else { 0 };
*previous_position *previous_position
} } else {
else {
*previous_position *previous_position
} }
} }

View File

@ -1,5 +1,5 @@
// TODO: Store like three minutes of data, then change how much is shown based on scaling! // 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 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 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 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 DEFAULT_REFRESH_RATE_IN_MILLISECONDS: u128 = 1000;

View File

@ -1,13 +1,12 @@
use crate::{app::data_collection, constants}; use crate::{app::data_collection, constants};
use constants::*; use constants::*;
pub fn update_temp_row(app_data : &data_collection::Data, temp_type : &data_collection::temperature::TemperatureType) -> Vec<Vec<String>> { pub fn update_temp_row(app_data: &data_collection::Data, temp_type: &data_collection::temperature::TemperatureType) -> Vec<Vec<String>> {
let mut sensor_vector : Vec<Vec<String>> = Vec::new(); let mut sensor_vector: Vec<Vec<String>> = Vec::new();
if (&app_data.list_of_temperature_sensor).is_empty() { if (&app_data.list_of_temperature_sensor).is_empty() {
sensor_vector.push(vec!["No Sensors Found".to_string(), "".to_string()]) sensor_vector.push(vec!["No Sensors Found".to_string(), "".to_string()])
} } else {
else {
for sensor in &app_data.list_of_temperature_sensor { for sensor in &app_data.list_of_temperature_sensor {
sensor_vector.push(vec![ sensor_vector.push(vec![
sensor.component_name.to_string(), 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 sensor_vector
} }
pub fn update_disk_row(app_data : &data_collection::Data) -> Vec<Vec<String>> { pub fn update_disk_row(app_data: &data_collection::Data) -> Vec<Vec<String>> {
let mut disk_vector : Vec<Vec<String>> = Vec::new(); let mut disk_vector: Vec<Vec<String>> = Vec::new();
for disk in &app_data.list_of_disks { for disk in &app_data.list_of_disks {
let io_activity = if app_data.list_of_io.len() > 2 { let io_activity = if app_data.list_of_io.len() > 2 {
if let Some(io_package) = &app_data.list_of_io.last() { 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<Vec<String>> {
( (
if read_bytes_per_sec < 1024 { if read_bytes_per_sec < 1024 {
format!("{}B", read_bytes_per_sec) 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) format!("{}KB", read_bytes_per_sec / 1024)
} } else {
else {
format!("{}MB", read_bytes_per_sec / 1024 / 1024) format!("{}MB", read_bytes_per_sec / 1024 / 1024)
}, },
if write_bytes_per_sec < 1024 { if write_bytes_per_sec < 1024 {
format!("{}B", write_bytes_per_sec) 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) format!("{}KB", write_bytes_per_sec / 1024)
} } else {
else {
format!("{}MB", write_bytes_per_sec / 1024 / 1024) format!("{}MB", write_bytes_per_sec / 1024 / 1024)
}, },
) )
} } else {
else {
("0B".to_string(), "0B".to_string()) ("0B".to_string(), "0B".to_string())
} }
} } else {
else {
("0B".to_string(), "0B".to_string()) ("0B".to_string(), "0B".to_string())
} }
} } else {
else {
("0B".to_string(), "0B".to_string()) ("0B".to_string(), "0B".to_string())
} }
} } else {
else {
("0B".to_string(), "0B".to_string()) ("0B".to_string(), "0B".to_string())
}; };
disk_vector.push(vec![ disk_vector.push(vec![
@ -83,14 +74,12 @@ pub fn update_disk_row(app_data : &data_collection::Data) -> Vec<Vec<String>> {
format!("{:.0}%", disk.used_space as f64 / disk.total_space as f64 * 100_f64), format!("{:.0}%", disk.used_space as f64 / disk.total_space as f64 * 100_f64),
if disk.free_space < 1024 { if disk.free_space < 1024 {
disk.free_space.to_string() + "MB" disk.free_space.to_string() + "MB"
} } else {
else {
(disk.free_space / 1024).to_string() + "GB" (disk.free_space / 1024).to_string() + "GB"
}, },
if disk.total_space < 1024 { if disk.total_space < 1024 {
disk.total_space.to_string() + "MB" disk.total_space.to_string() + "MB"
} } else {
else {
(disk.total_space / 1024).to_string() + "GB" (disk.total_space / 1024).to_string() + "GB"
}, },
io_activity.0, io_activity.0,
@ -101,8 +90,8 @@ pub fn update_disk_row(app_data : &data_collection::Data) -> Vec<Vec<String>> {
disk_vector disk_vector
} }
pub fn update_process_row(app_data : &data_collection::Data) -> Vec<Vec<String>> { pub fn update_process_row(app_data: &data_collection::Data) -> Vec<Vec<String>> {
let mut process_vector : Vec<Vec<String>> = Vec::new(); let mut process_vector: Vec<Vec<String>> = Vec::new();
for process in &app_data.list_of_processes { for process in &app_data.list_of_processes {
process_vector.push(vec![ process_vector.push(vec![
@ -113,16 +102,13 @@ pub fn update_process_row(app_data : &data_collection::Data) -> Vec<Vec<String>>
"{:.1}%", "{:.1}%",
if let Some(mem_usage) = process.mem_usage_percent { if let Some(mem_usage) = process.mem_usage_percent {
mem_usage 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() { 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 (mem_usage_kb / 1024) as f64 / mem_data.mem_total_in_mb as f64 * 100_f64
} } else {
else {
0_f64 0_f64
} }
} } else {
else {
0_f64 0_f64
} }
), ),
@ -132,14 +118,14 @@ pub fn update_process_row(app_data : &data_collection::Data) -> Vec<Vec<String>>
process_vector process_vector
} }
pub fn update_cpu_data_points(show_avg_cpu : bool, app_data : &data_collection::Data) -> Vec<(String, Vec<(f64, f64)>)> { 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_data_vector: Vec<(String, Vec<(f64, f64)>)> = Vec::new();
let mut cpu_collection : Vec<Vec<(f64, f64)>> = Vec::new(); let mut cpu_collection: Vec<Vec<(f64, f64)>> = Vec::new();
if !app_data.list_of_cpu_packages.is_empty() { if !app_data.list_of_cpu_packages.is_empty() {
// I'm sorry for the if statement but I couldn't be bothered here... // 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() { 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 { for data in &app_data.list_of_cpu_packages {
let current_time = std::time::Instant::now(); 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 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) 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) convert_mem_data(&app_data.swap)
} }
pub fn update_mem_data_values(app_data : &data_collection::Data) -> Vec<(u64, u64)> { pub fn update_mem_data_values(app_data: &data_collection::Data) -> Vec<(u64, u64)> {
let mut result : Vec<(u64, u64)> = Vec::new(); 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.memory));
result.push(get_most_recent_mem_values(&app_data.swap)); result.push(get_most_recent_mem_values(&app_data.swap));
result result
} }
fn get_most_recent_mem_values(mem_data : &[data_collection::mem::MemData]) -> (u64, u64) { fn get_most_recent_mem_values(mem_data: &[data_collection::mem::MemData]) -> (u64, u64) {
let mut result : (u64, u64) = (0, 0); let mut result: (u64, u64) = (0, 0);
if !mem_data.is_empty() { if !mem_data.is_empty() {
if let Some(most_recent) = mem_data.last() { 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 result
} }
fn convert_mem_data(mem_data : &[data_collection::mem::MemData]) -> Vec<(f64, f64)> { fn convert_mem_data(mem_data: &[data_collection::mem::MemData]) -> Vec<(f64, f64)> {
let mut result : Vec<(f64, f64)> = Vec::new(); let mut result: Vec<(f64, f64)> = Vec::new();
for data in mem_data { for data in mem_data {
let current_time = std::time::Instant::now(); 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(), ((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 { if data.mem_total_in_mb == 0 {
-1000.0 -1000.0
} } else {
else {
data.mem_used_in_mb as f64 / data.mem_total_in_mb as f64 * 100_f64 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 struct ConvertedNetworkData {
pub rx : Vec<(f64, f64)>, pub rx: Vec<(f64, f64)>,
pub tx : Vec<(f64, f64)>, pub tx: Vec<(f64, f64)>,
pub rx_display : String, pub rx_display: String,
pub tx_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) convert_network_data_points(&app_data.network)
} }
pub fn convert_network_data_points(network_data : &[data_collection::network::NetworkData]) -> ConvertedNetworkData { pub fn convert_network_data_points(network_data: &[data_collection::network::NetworkData]) -> ConvertedNetworkData {
let mut rx : Vec<(f64, f64)> = Vec::new(); let mut rx: Vec<(f64, f64)> = Vec::new();
let mut tx : Vec<(f64, f64)> = Vec::new(); let mut tx: Vec<(f64, f64)> = Vec::new();
for data in network_data { for data in network_data {
let current_time = std::time::Instant::now(); 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; let num_bytes = last_num_bytes_entry.rx;
if num_bytes < 1024 { if num_bytes < 1024 {
format!("RX: {:4} B", num_bytes).to_string() 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() 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() format!("RX: {:4}MB", num_bytes / 1024 / 1024).to_string()
} } else {
else {
format!("RX: {:4}GB", num_bytes / 1024 / 1024 / 1024).to_string() format!("RX: {:4}GB", num_bytes / 1024 / 1024 / 1024).to_string()
} }
} } else {
else {
"0B".to_string() "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; let num_bytes = last_num_bytes_entry.tx;
if num_bytes < 1024 { if num_bytes < 1024 {
format!("TX: {:4} B", num_bytes).to_string() 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() 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() format!("TX: {:4}MB", num_bytes / 1024 / 1024).to_string()
} } else {
else {
format!("TX: {:4}GB", num_bytes / 1024 / 1024 / 1024).to_string() format!("TX: {:4}GB", num_bytes / 1024 / 1024 / 1024).to_string()
} }
} } else {
else {
"0B".to_string() "0B".to_string()
}; };

View File

@ -1,5 +1,3 @@
#![feature(async_closure)]
#[macro_use] #[macro_use]
extern crate log; extern crate log;
#[macro_use] #[macro_use]
@ -7,14 +5,17 @@ extern crate clap;
#[macro_use] #[macro_use]
extern crate failure; extern crate failure;
use crossterm::{input, AlternateScreen, InputEvent, KeyEvent, MouseButton, MouseEvent}; use crossterm::{
input::{input, InputEvent, KeyEvent, MouseButton, MouseEvent},
screen::AlternateScreen,
};
use std::{ use std::{
io::stdout, io::stdout,
sync::mpsc, sync::mpsc,
thread, thread,
time::{Duration, Instant}, time::{Duration, Instant},
}; };
use tui_temp_fork::{backend::CrosstermBackend, Terminal}; use tui::{backend::CrosstermBackend, Terminal};
pub mod app; pub mod app;
mod utils { mod utils {
@ -65,34 +66,30 @@ fn main() -> error::Result<()> {
//.after_help("Themes:") // TODO: This and others disabled for now //.after_help("Themes:") // TODO: This and others disabled for now
.get_matches(); .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 matches
.value_of("RATE_MILLIS") .value_of("RATE_MILLIS")
.unwrap_or(&constants::DEFAULT_REFRESH_RATE_IN_MILLISECONDS.to_string()) .unwrap_or(&constants::DEFAULT_REFRESH_RATE_IN_MILLISECONDS.to_string())
.parse::<u128>()? .parse::<u128>()?
} } else {
else {
constants::DEFAULT_REFRESH_RATE_IN_MILLISECONDS constants::DEFAULT_REFRESH_RATE_IN_MILLISECONDS
}; };
if update_rate_in_milliseconds < 250 { if update_rate_in_milliseconds < 250 {
return Err(RustopError::InvalidArg { 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 { 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") { let temperature_type = if matches.is_present("FAHRENHEIT") {
data_collection::temperature::TemperatureType::Fahrenheit data_collection::temperature::TemperatureType::Fahrenheit
} } else if matches.is_present("KELVIN") {
else if matches.is_present("KELVIN") {
data_collection::temperature::TemperatureType::Kelvin data_collection::temperature::TemperatureType::Kelvin
} } else {
else {
data_collection::temperature::TemperatureType::Celsius data_collection::temperature::TemperatureType::Celsius
}; };
let show_average_cpu = matches.is_present("AVG_CPU"); 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(); let mut reader = input.read_async();
loop { loop {
if let Some(event) = reader.next() { 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) // 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)); thread::sleep(Duration::from_millis(250));
first_run = false; first_run = false;
} } else {
else {
thread::sleep(Duration::from_millis(update_rate_in_milliseconds as u64)); thread::sleep(Duration::from_millis(update_rate_in_milliseconds as u64));
} }
} }

View File

@ -9,14 +9,12 @@ pub fn init_logger() -> Result<(), fern::InitError> {
message message
)) ))
}) })
.level(if cfg!(debug_assertions) { log::LevelFilter::Debug } else { log::LevelFilter::Info }) .level(if cfg!(debug_assertions) {
.chain(if cfg!(debug_assertions) { log::LevelFilter::Debug
//std::fs::OpenOptions::new().write(true).create(true).append(false).open("debug.log")? } else {
fern::log_file("debug.log")? log::LevelFilter::Info
}
else {
fern::log_file("logging.log")?
}) })
.chain(fern::log_file("debug.log")?)
.apply()?; .apply()?;
Ok(()) Ok(())