| 1 | use std::{ |
| 2 | borrow::Cow, |
| 3 | cmp::{Ordering, max}, |
| 4 | fmt::Display, |
| 5 | num::NonZeroU16, |
| 6 | ops::Add, |
| 7 | sync::Arc, |
| 8 | time::Duration, |
| 9 | }; |
| 10 | |
| 11 | use concat_string::concat_string; |
| 12 | use ratatui::widgets::Row; |
| 13 | |
| 14 | use super::process_columns::ProcColumn; |
| 15 | #[cfg(target_os = "linux")] |
| 16 | use crate::collection::processes::ProcessType; |
| 17 | use crate::{ |
| 18 | canvas::{ |
| 19 | Painter, |
| 20 | components::data_table::{DataTableColumn, DataToCell}, |
| 21 | }, |
| 22 | collection::processes::{Pid, ProcessHarvest}, |
| 23 | dec_bytes_per_second_string, |
| 24 | utils::data_units::{GIBI_LIMIT, GIGA_LIMIT, get_binary_bytes, get_decimal_bytes}, |
| 25 | }; |
| 26 | |
| 27 | #[derive(Clone, Debug)] |
| 28 | enum IdType { |
| 29 | Name(String), |
| 30 | Command(String), |
| 31 | } |
| 32 | |
| 33 | #[derive(Clone, Debug)] |
| 34 | pub struct Id { |
| 35 | id_type: IdType, |
| 36 | prefix: Option<String>, |
| 37 | } |
| 38 | |
| 39 | impl From<&'static str> for Id { |
| 40 | fn from(s: &'static str) -> Self { |
| 41 | Id { |
| 42 | id_type: IdType::Name(s.to_string()), |
| 43 | prefix: None, |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | impl Id { |
| 49 | /// Returns the ID as a lowercase [`String`], with no prefix. This is |
| 50 | /// primarily useful for cases like sorting where we treat everything as |
| 51 | /// the same case (e.g. `Discord` comes before `dkms`). |
| 52 | pub fn to_lowercase(&self) -> String { |
| 53 | match &self.id_type { |
| 54 | IdType::Name(name) => name.to_lowercase(), |
| 55 | IdType::Command(cmd) => cmd.to_lowercase(), |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | /// Return the ID as a borrowed [`str`] with no prefix. |
| 60 | pub fn as_str(&self) -> &str { |
| 61 | match &self.id_type { |
| 62 | IdType::Name(name) => name.as_str(), |
| 63 | IdType::Command(cmd) => cmd.as_str(), |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | /// Returns the ID as a [`String`] with prefix. |
| 68 | pub fn to_prefixed_string(&self) -> String { |
| 69 | if let Some(prefix) = &self.prefix { |
| 70 | concat_string!( |
| 71 | prefix, |
| 72 | match &self.id_type { |
| 73 | IdType::Name(name) => name, |
| 74 | IdType::Command(cmd) => cmd, |
| 75 | } |
| 76 | ) |
| 77 | } else { |
| 78 | match &self.id_type { |
| 79 | IdType::Name(name) => name.to_string(), |
| 80 | IdType::Command(cmd) => cmd.to_string(), |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | impl Display for Id { |
| 87 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 88 | f.write_str(self.as_str()) |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | #[derive(PartialEq, Clone, Debug, Copy)] |
| 93 | pub enum MemUsage { |
| 94 | Percent(f32), |
| 95 | Bytes(u64), |
| 96 | } |
| 97 | |
| 98 | impl Add for MemUsage { |
| 99 | type Output = Self; |
| 100 | |
| 101 | fn add(self, rhs: Self) -> Self::Output { |
| 102 | match (self, rhs) { |
| 103 | (MemUsage::Percent(a), MemUsage::Percent(b)) => MemUsage::Percent(a + b), |
| 104 | (MemUsage::Bytes(a), MemUsage::Bytes(b)) => MemUsage::Bytes(a + b), |
| 105 | (MemUsage::Bytes(_), MemUsage::Percent(_)) |
| 106 | | (MemUsage::Percent(_), MemUsage::Bytes(_)) => { |
| 107 | unreachable!("trying to add together two different memory usage types!") |
| 108 | } |
| 109 | } |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | impl PartialOrd for MemUsage { |
| 114 | fn partial_cmp(&self, other: &Self) -> Option<Ordering> { |
| 115 | match (self, other) { |
| 116 | (MemUsage::Percent(a), MemUsage::Percent(b)) => a.partial_cmp(b), |
| 117 | (MemUsage::Bytes(a), MemUsage::Bytes(b)) => a.partial_cmp(b), |
| 118 | _ => unreachable!(), |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | impl Display for MemUsage { |
| 124 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 125 | match self { |
| 126 | MemUsage::Percent(percent) => f.write_fmt(format_args!("{percent:.1}%")), |
| 127 | MemUsage::Bytes(bytes) => f.write_str(&binary_byte_string(*bytes)), |
| 128 | } |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | trait DurationExt { |
| 133 | fn num_days(&self) -> u64; |
| 134 | fn num_hours(&self) -> u64; |
| 135 | fn num_minutes(&self) -> u64; |
| 136 | } |
| 137 | |
| 138 | const SECS_PER_DAY: u64 = SECS_PER_HOUR * 24; |
| 139 | const SECS_PER_HOUR: u64 = SECS_PER_MINUTE * 60; |
| 140 | const SECS_PER_MINUTE: u64 = 60; |
| 141 | |
| 142 | impl DurationExt for Duration { |
| 143 | /// Number of full days in this duration. |
| 144 | #[inline] |
| 145 | fn num_days(&self) -> u64 { |
| 146 | self.as_secs() / SECS_PER_DAY |
| 147 | } |
| 148 | |
| 149 | /// Number of full hours in this duration. |
| 150 | #[inline] |
| 151 | fn num_hours(&self) -> u64 { |
| 152 | self.as_secs() / SECS_PER_HOUR |
| 153 | } |
| 154 | |
| 155 | /// Number of full minutes in this duration. |
| 156 | #[inline] |
| 157 | fn num_minutes(&self) -> u64 { |
| 158 | self.as_secs() / SECS_PER_MINUTE |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | fn format_time(dur: Duration) -> String { |
| 163 | if dur.num_days() > 0 { |
| 164 | format!( |
| 165 | "{}d {}h {}m", |
| 166 | dur.num_days(), |
| 167 | dur.num_hours() % 24, |
| 168 | dur.num_minutes() % 60 |
| 169 | ) |
| 170 | } else if dur.num_hours() > 0 { |
| 171 | format!( |
| 172 | "{}h {}m {}s", |
| 173 | dur.num_hours(), |
| 174 | dur.num_minutes() % 60, |
| 175 | dur.as_secs() % 60 |
| 176 | ) |
| 177 | } else if dur.num_minutes() > 0 { |
| 178 | format!( |
| 179 | "{}m {}.{:02}s", |
| 180 | dur.num_minutes(), |
| 181 | dur.as_secs() % 60, |
| 182 | dur.as_millis() % 1000 / 10 |
| 183 | ) |
| 184 | } else { |
| 185 | format!("{}.{:03}s", dur.as_secs(), dur.as_millis() % 1000) |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | /// Returns a string given a value that is converted to the closest binary |
| 190 | /// variant. If the value is greater than a gibibyte, then it will return a |
| 191 | /// decimal place. |
| 192 | #[inline] |
| 193 | fn binary_byte_string(value: u64) -> String { |
| 194 | let converted_values = get_binary_bytes(value); |
| 195 | if value >= GIBI_LIMIT { |
| 196 | format!("{:.1}{}", converted_values.0, converted_values.1) |
| 197 | } else { |
| 198 | format!("{:.0}{}", converted_values.0, converted_values.1) |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | /// Returns a string given a value that is converted to the closest SI-variant. |
| 203 | /// If the value is greater than a giga-X, then it will return a decimal place. |
| 204 | fn dec_bytes_string(value: u64) -> String { |
| 205 | let converted_values = get_decimal_bytes(value); |
| 206 | if value >= GIGA_LIMIT { |
| 207 | format!("{:.1}{}", converted_values.0, converted_values.1) |
| 208 | } else { |
| 209 | format!("{:.0}{}", converted_values.0, converted_values.1) |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | #[derive(Clone)] |
| 214 | pub struct ProcWidgetData { |
| 215 | pub pid: Pid, |
| 216 | #[allow(dead_code)] |
| 217 | pub ppid: Option<Pid>, |
| 218 | pub id: Id, |
| 219 | pub cpu_usage_percent: f32, |
| 220 | pub mem_usage: MemUsage, |
| 221 | pub virtual_mem: u64, |
| 222 | pub rps: u64, |
| 223 | pub wps: u64, |
| 224 | pub total_read: u64, |
| 225 | pub total_write: u64, |
| 226 | pub process_state: &'static str, |
| 227 | pub process_char: char, |
| 228 | pub user: Option<Arc<str>>, |
| 229 | pub num_similar: u64, |
| 230 | pub disabled: bool, |
| 231 | pub time: Duration, |
| 232 | #[cfg(feature = "gpu")] |
| 233 | pub gpu_mem_usage: MemUsage, |
| 234 | #[cfg(feature = "gpu")] |
| 235 | pub gpu_usage: u32, |
| 236 | /// The process "type". Used to colour things. |
| 237 | #[cfg(target_os = "linux")] |
| 238 | pub process_type: ProcessType, |
| 239 | #[cfg(unix)] |
| 240 | pub nice: i32, |
| 241 | pub priority: i32, |
| 242 | } |
| 243 | |
| 244 | impl ProcWidgetData { |
| 245 | pub fn from_data(process: &ProcessHarvest, is_command: bool, is_mem_percent: bool) -> Self { |
| 246 | let id = Id { |
| 247 | id_type: if is_command { |
| 248 | IdType::Command(process.command.clone()) |
| 249 | } else { |
| 250 | IdType::Name(process.name.clone()) |
| 251 | }, |
| 252 | prefix: None, |
| 253 | }; |
| 254 | |
| 255 | let mem_usage = if is_mem_percent { |
| 256 | MemUsage::Percent(process.mem_usage_percent) |
| 257 | } else { |
| 258 | MemUsage::Bytes(process.mem_usage) |
| 259 | }; |
| 260 | |
| 261 | Self { |
| 262 | pid: process.pid, |
| 263 | ppid: process.parent_pid, |
| 264 | id, |
| 265 | cpu_usage_percent: process.cpu_usage_percent, |
| 266 | mem_usage, |
| 267 | virtual_mem: process.virtual_mem, |
| 268 | rps: process.read_per_sec, |
| 269 | wps: process.write_per_sec, |
| 270 | total_read: process.total_read, |
| 271 | total_write: process.total_write, |
| 272 | process_state: process.process_state.0, |
| 273 | process_char: process.process_state.1, |
| 274 | user: process.user.clone(), |
| 275 | num_similar: 1, |
| 276 | disabled: false, |
| 277 | time: process.time, |
| 278 | #[cfg(feature = "gpu")] |
| 279 | gpu_mem_usage: if is_mem_percent { |
| 280 | MemUsage::Percent(process.gpu_mem_percent) |
| 281 | } else { |
| 282 | MemUsage::Bytes(process.gpu_mem) |
| 283 | }, |
| 284 | #[cfg(feature = "gpu")] |
| 285 | gpu_usage: process.gpu_util, |
| 286 | #[cfg(target_os = "linux")] |
| 287 | process_type: process.process_type, |
| 288 | #[cfg(unix)] |
| 289 | nice: process.nice, |
| 290 | priority: process.priority, |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | pub fn disabled(mut self, disabled: bool) -> Self { |
| 295 | self.disabled = disabled; |
| 296 | self |
| 297 | } |
| 298 | |
| 299 | pub fn prefix(mut self, prefix: Option<String>) -> Self { |
| 300 | self.id.prefix = prefix; |
| 301 | self |
| 302 | } |
| 303 | |
| 304 | pub fn add(&mut self, other: &Self) { |
| 305 | self.cpu_usage_percent += other.cpu_usage_percent; |
| 306 | self.mem_usage = self.mem_usage + other.mem_usage; |
| 307 | self.rps += other.rps; |
| 308 | self.wps += other.wps; |
| 309 | self.total_read += other.total_read; |
| 310 | self.total_write += other.total_write; |
| 311 | self.time = self.time.max(other.time); |
| 312 | #[cfg(feature = "gpu")] |
| 313 | { |
| 314 | self.gpu_mem_usage = self.gpu_mem_usage + other.gpu_mem_usage; |
| 315 | self.gpu_usage += other.gpu_usage; |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | fn to_string(&self, column: &ProcColumn) -> String { |
| 320 | match column { |
| 321 | &ProcColumn::Priority => self.priority.to_string(), |
| 322 | #[cfg(unix)] |
| 323 | ProcColumn::Nice => self.nice.to_string(), |
| 324 | ProcColumn::CpuPercent => format!("{:.1}%", self.cpu_usage_percent), |
| 325 | ProcColumn::MemValue | ProcColumn::MemPercent => self.mem_usage.to_string(), |
| 326 | ProcColumn::VirtualMem => binary_byte_string(self.virtual_mem), |
| 327 | ProcColumn::Pid => self.pid.to_string(), |
| 328 | ProcColumn::Count => self.num_similar.to_string(), |
| 329 | ProcColumn::Name | ProcColumn::Command => self.id.to_prefixed_string(), |
| 330 | ProcColumn::ReadPerSecond => dec_bytes_per_second_string(self.rps), |
| 331 | ProcColumn::WritePerSecond => dec_bytes_per_second_string(self.wps), |
| 332 | ProcColumn::TotalRead => dec_bytes_string(self.total_read), |
| 333 | ProcColumn::TotalWrite => dec_bytes_string(self.total_write), |
| 334 | ProcColumn::State => self.process_char.to_string(), |
| 335 | ProcColumn::User => self |
| 336 | .user |
| 337 | .as_ref() |
| 338 | .map(|user| user.to_string()) |
| 339 | .unwrap_or_else(|| "N/A".to_string()), |
| 340 | ProcColumn::Time => format_time(self.time), |
| 341 | #[cfg(feature = "gpu")] |
| 342 | ProcColumn::GpuMemValue | ProcColumn::GpuMemPercent => self.gpu_mem_usage.to_string(), |
| 343 | #[cfg(feature = "gpu")] |
| 344 | ProcColumn::GpuUtilPercent => format!("{:.1}%", self.gpu_usage), |
| 345 | } |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | impl DataToCell<ProcColumn> for ProcWidgetData { |
| 350 | fn to_cell_text( |
| 351 | &self, column: &ProcColumn, calculated_width: NonZeroU16, |
| 352 | ) -> Option<Cow<'static, str>> { |
| 353 | // TODO: Optimize the string allocations here... |
| 354 | // TODO: Also maybe just pull in the to_string call but add a variable for the |
| 355 | // differences. |
| 356 | Some(match column { |
| 357 | #[cfg(unix)] |
| 358 | ProcColumn::Nice => self.nice.to_string().into(), |
| 359 | &ProcColumn::Priority => self.priority.to_string().into(), |
| 360 | ProcColumn::CpuPercent => format!("{:.1}%", self.cpu_usage_percent).into(), |
| 361 | ProcColumn::MemValue | ProcColumn::MemPercent => self.mem_usage.to_string().into(), |
| 362 | ProcColumn::VirtualMem => binary_byte_string(self.virtual_mem).into(), |
| 363 | ProcColumn::Pid => self.pid.to_string().into(), |
| 364 | ProcColumn::Count => self.num_similar.to_string().into(), |
| 365 | ProcColumn::Name | ProcColumn::Command => self.id.to_prefixed_string().into(), |
| 366 | ProcColumn::ReadPerSecond => dec_bytes_per_second_string(self.rps).into(), |
| 367 | ProcColumn::WritePerSecond => dec_bytes_per_second_string(self.wps).into(), |
| 368 | ProcColumn::TotalRead => dec_bytes_string(self.total_read).into(), |
| 369 | ProcColumn::TotalWrite => dec_bytes_string(self.total_write).into(), |
| 370 | ProcColumn::State => { |
| 371 | if calculated_width.get() < 8 { |
| 372 | self.process_char.to_string().into() |
| 373 | } else { |
| 374 | self.process_state.into() |
| 375 | } |
| 376 | } |
| 377 | ProcColumn::User => self |
| 378 | .user |
| 379 | .as_ref() |
| 380 | .map(|user| user.to_string().into()) |
| 381 | .unwrap_or_else(|| "N/A".into()), |
| 382 | ProcColumn::Time => format_time(self.time).into(), |
| 383 | #[cfg(feature = "gpu")] |
| 384 | ProcColumn::GpuMemValue | ProcColumn::GpuMemPercent => { |
| 385 | self.gpu_mem_usage.to_string().into() |
| 386 | } |
| 387 | #[cfg(feature = "gpu")] |
| 388 | ProcColumn::GpuUtilPercent => format!("{:.1}%", self.gpu_usage).into(), |
| 389 | }) |
| 390 | } |
| 391 | |
| 392 | #[cfg(target_os = "linux")] |
| 393 | #[inline(always)] |
| 394 | fn style_cell(&self, column: &ProcColumn, painter: &Painter) -> Option<ratatui::style::Style> { |
| 395 | match column { |
| 396 | ProcColumn::Name | ProcColumn::Command if self.process_type.is_thread() => { |
| 397 | Some(painter.styles.thread_text_style) |
| 398 | } |
| 399 | _ => None, |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | #[inline(always)] |
| 404 | fn style_row<'a>(&self, row: Row<'a>, painter: &Painter) -> Row<'a> { |
| 405 | if self.disabled { |
| 406 | row.style(painter.styles.disabled_text_style) |
| 407 | } else { |
| 408 | row |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | fn column_widths<C: DataTableColumn<ProcColumn>>(data: &[Self], columns: &[C]) -> Vec<u16> |
| 413 | where |
| 414 | Self: Sized, |
| 415 | { |
| 416 | let mut widths = vec![0; columns.len()]; |
| 417 | |
| 418 | for d in data { |
| 419 | for (w, c) in widths.iter_mut().zip(columns) { |
| 420 | *w = max(*w, d.to_string(c.inner()).len() as u16); |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | widths |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | #[cfg(test)] |
| 429 | mod test { |
| 430 | use std::time::Duration; |
| 431 | |
| 432 | use super::*; |
| 433 | use crate::utils::data_units::*; |
| 434 | |
| 435 | #[test] |
| 436 | fn test_format_time() { |
| 437 | const ONE_DAY: u64 = 24 * 60 * 60; |
| 438 | |
| 439 | assert_eq!(format_time(Duration::from_millis(500)), "0.500s"); |
| 440 | assert_eq!(format_time(Duration::from_millis(900)), "0.900s"); |
| 441 | assert_eq!(format_time(Duration::from_secs(1)), "1.000s"); |
| 442 | assert_eq!(format_time(Duration::from_secs(10)), "10.000s"); |
| 443 | assert_eq!(format_time(Duration::from_secs(60)), "1m 0.00s"); |
| 444 | assert_eq!(format_time(Duration::from_secs(61)), "1m 1.00s"); |
| 445 | assert_eq!(format_time(Duration::from_secs(600)), "10m 0.00s"); |
| 446 | assert_eq!(format_time(Duration::from_secs(601)), "10m 1.00s"); |
| 447 | assert_eq!(format_time(Duration::from_secs(3600)), "1h 0m 0s"); |
| 448 | assert_eq!(format_time(Duration::from_secs(3601)), "1h 0m 1s"); |
| 449 | assert_eq!(format_time(Duration::from_secs(3660)), "1h 1m 0s"); |
| 450 | assert_eq!(format_time(Duration::from_secs(3661)), "1h 1m 1s"); |
| 451 | assert_eq!(format_time(Duration::from_secs(ONE_DAY - 1)), "23h 59m 59s"); |
| 452 | assert_eq!(format_time(Duration::from_secs(ONE_DAY)), "1d 0h 0m"); |
| 453 | assert_eq!(format_time(Duration::from_secs(ONE_DAY + 1)), "1d 0h 0m"); |
| 454 | assert_eq!(format_time(Duration::from_secs(ONE_DAY + 60)), "1d 0h 1m"); |
| 455 | assert_eq!( |
| 456 | format_time(Duration::from_secs(ONE_DAY + 3600 - 1)), |
| 457 | "1d 0h 59m" |
| 458 | ); |
| 459 | assert_eq!(format_time(Duration::from_secs(ONE_DAY + 3600)), "1d 1h 0m"); |
| 460 | assert_eq!( |
| 461 | format_time(Duration::from_secs(ONE_DAY * 365 - 1)), |
| 462 | "364d 23h 59m" |
| 463 | ); |
| 464 | } |
| 465 | |
| 466 | #[test] |
| 467 | fn test_binary_byte_string() { |
| 468 | assert_eq!(binary_byte_string(0), "0B".to_string()); |
| 469 | assert_eq!(binary_byte_string(1), "1B".to_string()); |
| 470 | assert_eq!(binary_byte_string(1000), "1000B".to_string()); |
| 471 | assert_eq!(binary_byte_string(1023), "1023B".to_string()); |
| 472 | assert_eq!(binary_byte_string(KIBI_LIMIT), "1KiB".to_string()); |
| 473 | assert_eq!(binary_byte_string(KIBI_LIMIT + 1), "1KiB".to_string()); |
| 474 | assert_eq!(binary_byte_string(MEBI_LIMIT), "1MiB".to_string()); |
| 475 | assert_eq!(binary_byte_string(GIBI_LIMIT), "1.0GiB".to_string()); |
| 476 | assert_eq!(binary_byte_string(2 * GIBI_LIMIT), "2.0GiB".to_string()); |
| 477 | assert_eq!( |
| 478 | binary_byte_string((2.5 * GIBI_LIMIT as f64) as u64), |
| 479 | "2.5GiB".to_string() |
| 480 | ); |
| 481 | assert_eq!( |
| 482 | binary_byte_string((10.34 * TEBI_LIMIT as f64) as u64), |
| 483 | "10.3TiB".to_string() |
| 484 | ); |
| 485 | assert_eq!( |
| 486 | binary_byte_string((10.36 * TEBI_LIMIT as f64) as u64), |
| 487 | "10.4TiB".to_string() |
| 488 | ); |
| 489 | } |
| 490 | } |