Debian Codegraph @

src/widgets/process_table.rs

raw symbols SCIP
1 pub mod process_columns;
2 pub mod process_data;
3 pub mod query;
4 mod sort_table;
5
6 use std::{borrow::Cow, collections::BTreeMap};
7
8 use indexmap::IndexSet;
9 use itertools::Itertools;
10 pub use process_columns::*;
11 pub use process_data::*;
12 use query::{ProcessQuery, parse_query};
13 use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
14 use sort_table::SortTableColumn;
15
16 use crate::{
17 app::{
18 AppConfigFields, AppSearchState,
19 data::{InnerData, ProcessData},
20 },
21 canvas::components::data_table::{
22 Column, ColumnHeader, ColumnWidthBounds, DataTable, DataTableColumn, DataTableProps,
23 DataTableStyling, SortColumn, SortDataTable, SortDataTableProps, SortOrder, SortsRow,
24 },
25 collection::processes::{Pid, ProcessHarvest},
26 options::config::style::Styles,
27 utils::int_hash::IntHashMap,
28 widgets::query::QueryOptions,
29 };
30
31 /// ProcessSearchState only deals with process' search's current settings and
32 /// state.
33 #[derive(Default)]
34 pub struct ProcessSearchState {
35 // TODO: Flatten AppSearchState as it's been generalized further.
36 pub search_state: AppSearchState,
37 pub query_options: QueryOptions,
38 }
39
40 impl ProcessSearchState {
41 pub fn search_toggle_ignore_case(&mut self) {
42 self.query_options.ignore_case = !self.query_options.ignore_case;
43 }
44
45 pub fn search_toggle_whole_word(&mut self) {
46 self.query_options.whole_word = !self.query_options.whole_word;
47 }
48
49 pub fn search_toggle_regex(&mut self) {
50 self.query_options.use_regex = !self.query_options.use_regex;
51 }
52 }
53
54 /// Whether to expand or collapse by default.
55 #[derive(Clone, Debug, Eq, PartialEq)]
56 pub(crate) enum TreeCollapsed {
57 DefaultCollapse { expanded_pids: HashSet<Pid> },
58 DefaultExpand { collapsed_pids: HashSet<Pid> },
59 }
60
61 impl TreeCollapsed {
62 /// Creates a new [`TreeCollapsed`].
63 pub(crate) fn new(default_collapsed: bool) -> Self {
64 if default_collapsed {
65 TreeCollapsed::DefaultCollapse {
66 expanded_pids: HashSet::default(),
67 }
68 } else {
69 TreeCollapsed::DefaultExpand {
70 collapsed_pids: HashSet::default(),
71 }
72 }
73 }
74
75 /// Check whether the given PID is collapsed.
76 pub(crate) fn is_collapsed(&self, pid: Pid) -> bool {
77 match self {
78 TreeCollapsed::DefaultCollapse { expanded_pids } => !expanded_pids.contains(&pid),
79 TreeCollapsed::DefaultExpand { collapsed_pids } => collapsed_pids.contains(&pid),
80 }
81 }
82
83 /// Collapse the given PID.
84 pub(crate) fn collapse(&mut self, pid: Pid) {
85 match self {
86 TreeCollapsed::DefaultCollapse { expanded_pids } => {
87 expanded_pids.remove(&pid);
88 }
89 TreeCollapsed::DefaultExpand { collapsed_pids } => {
90 collapsed_pids.insert(pid);
91 }
92 }
93 }
94
95 /// Expand the given PID.
96 pub(crate) fn expand(&mut self, pid: Pid) {
97 match self {
98 TreeCollapsed::DefaultCollapse { expanded_pids } => {
99 expanded_pids.insert(pid);
100 }
101 TreeCollapsed::DefaultExpand { collapsed_pids } => {
102 collapsed_pids.remove(&pid);
103 }
104 }
105 }
106
107 /// Toggle the given PID.
108 pub(crate) fn toggle(&mut self, pid: Pid) {
109 match self {
110 TreeCollapsed::DefaultCollapse { expanded_pids } => {
111 if expanded_pids.contains(&pid) {
112 expanded_pids.remove(&pid);
113 } else {
114 expanded_pids.insert(pid);
115 }
116 }
117 TreeCollapsed::DefaultExpand { collapsed_pids } => {
118 if collapsed_pids.contains(&pid) {
119 collapsed_pids.remove(&pid);
120 } else {
121 collapsed_pids.insert(pid);
122 }
123 }
124 }
125 }
126 }
127
128 #[derive(Clone, Debug, Eq, PartialEq)]
129 pub(crate) enum ProcWidgetMode {
130 Tree(TreeCollapsed),
131 Grouped,
132 Normal,
133 }
134
135 type ProcessTable = SortDataTable<ProcWidgetData, ProcColumn>;
136 type SortTable = DataTable<Cow<'static, str>, SortTableColumn>;
137 type StringPidMap = HashMap<String, Vec<Pid>>;
138
139 fn make_column(column: ProcColumn) -> SortColumn<ProcColumn> {
140 use ProcColumn::*;
141
142 match column {
143 CpuPercent => SortColumn::new(CpuPercent).default_descending(),
144 MemValue => SortColumn::new(MemValue).default_descending(),
145 MemPercent => SortColumn::new(MemPercent).default_descending(),
146 VirtualMem => SortColumn::new(VirtualMem).default_descending(),
147 Pid => SortColumn::new(Pid),
148 Count => SortColumn::new(Count),
149 Name => SortColumn::soft(Name, Some(0.3)),
150 Command => SortColumn::soft(Command, Some(0.3)),
151 ReadPerSecond => SortColumn::hard(ReadPerSecond, 8).default_descending(),
152 WritePerSecond => SortColumn::hard(WritePerSecond, 8).default_descending(),
153 TotalRead => SortColumn::hard(TotalRead, 8).default_descending(),
154 TotalWrite => SortColumn::hard(TotalWrite, 8).default_descending(),
155 User => SortColumn::soft(User, Some(0.05)),
156 State => SortColumn::hard(State, 9),
157 Time => SortColumn::new(Time),
158 Priority => SortColumn::new(Priority).default_descending(),
159 #[cfg(unix)]
160 Nice => SortColumn::new(Nice),
161 #[cfg(feature = "gpu")]
162 GpuMemValue => SortColumn::new(GpuMemValue).default_descending(),
163 #[cfg(feature = "gpu")]
164 GpuMemPercent => SortColumn::new(GpuMemPercent).default_descending(),
165 #[cfg(feature = "gpu")]
166 GpuUtilPercent => SortColumn::new(GpuUtilPercent).default_descending(),
167 }
168 }
169
170 #[derive(Clone, Copy, Default)]
171 pub struct ProcTableConfig {
172 pub is_case_sensitive: bool,
173 pub is_match_whole_word: bool,
174 pub is_use_regex: bool,
175 pub show_memory_as_values: bool,
176 pub is_command: bool,
177 pub default_sort: Option<ProcColumn>,
178 pub sort_order: Option<SortOrder>,
179 }
180
181 /// A hacky workaround for now.
182 #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
183 pub enum ProcWidgetColumn {
184 PidOrCount,
185 ProcNameOrCommand,
186 Cpu,
187 Mem,
188 VirtualMem,
189 ReadPerSecond,
190 WritePerSecond,
191 TotalRead,
192 TotalWrite,
193 User,
194 State,
195 Time,
196 Priority,
197 #[cfg(unix)]
198 Nice,
199 #[cfg(feature = "gpu")]
200 GpuMem,
201 #[cfg(feature = "gpu")]
202 GpuUtil,
203 }
204
205 // This is temporary. Switch back to `ProcColumn` later!
206
207 pub struct ProcWidgetState {
208 pub(crate) mode: ProcWidgetMode,
209
210 /// The state of the search box.
211 pub proc_search: ProcessSearchState,
212
213 /// The state of the main table.
214 pub table: ProcessTable,
215
216 /// The state of the togglable table that controls sorting.
217 pub sort_table: SortTable,
218
219 /// The internal column mapping as an [`IndexSet`], to allow us to do quick
220 /// mappings of column type -> index.
221 pub column_mapping: IndexSet<ProcWidgetColumn>,
222
223 /// A name-to-pid mapping.
224 pub id_pid_map: StringPidMap,
225
226 /// The default sort index.
227 default_sort_index: usize,
228
229 /// The default sort order.
230 default_sort_order: SortOrder,
231
232 pub is_sort_open: bool,
233 pub force_rerender: bool,
234 pub force_update_data: bool,
235 #[cfg(target_os = "linux")]
236 pub hide_k_threads: bool,
237 }
238
239 impl ProcWidgetState {
240 fn new_sort_table(config: &AppConfigFields, palette: &Styles) -> SortTable {
241 const COLUMNS: [Column<SortTableColumn>; 1] = [Column::hard(SortTableColumn, 7)];
242
243 let props = DataTableProps {
244 title: None,
245 table_gap: config.table_gap,
246 left_to_right: true,
247 is_basic: false,
248 show_table_scroll_position: false,
249 show_table_scroll_bar: false,
250 show_current_entry_when_unfocused: false,
251 };
252 let styling = DataTableStyling::from_palette(palette);
253
254 DataTable::new(COLUMNS, props, styling)
255 }
256
257 fn new_process_table(
258 config: &AppConfigFields, colours: &Styles, columns: Vec<SortColumn<ProcColumn>>,
259 default_index: usize, default_order: SortOrder,
260 ) -> ProcessTable {
261 let inner_props = DataTableProps {
262 title: Some(" Processes ".into()),
263 table_gap: config.table_gap,
264 left_to_right: true,
265 is_basic: config.use_basic_mode,
266 show_table_scroll_position: config.show_table_scroll_position,
267 show_table_scroll_bar: config.show_table_scroll_bar,
268 show_current_entry_when_unfocused: false,
269 };
270 let props = SortDataTableProps {
271 inner: inner_props,
272 sort_index: default_index,
273 order: default_order,
274 };
275 let styling = DataTableStyling::from_palette(colours);
276
277 DataTable::new_sortable(columns, props, styling)
278 }
279
280 pub(crate) fn new(
281 config: &AppConfigFields, mode: ProcWidgetMode, table_config: ProcTableConfig,
282 colours: &Styles, config_columns: &Option<IndexSet<ProcWidgetColumn>>,
283 ) -> Self {
284 let process_search_state = {
285 let mut pss = ProcessSearchState::default();
286
287 if table_config.is_case_sensitive {
288 // By default it's off.
289 pss.search_toggle_ignore_case();
290 }
291 if table_config.is_match_whole_word {
292 pss.search_toggle_whole_word();
293 }
294 if table_config.is_use_regex {
295 pss.search_toggle_regex();
296 }
297
298 pss
299 };
300
301 let columns: Vec<SortColumn<ProcColumn>> = {
302 use ProcColumn::*;
303
304 let is_count = matches!(mode, ProcWidgetMode::Grouped);
305 let is_command = table_config.is_command;
306 let mem_as_values = table_config.show_memory_as_values;
307
308 match config_columns {
309 Some(columns) if !columns.is_empty() => columns
310 .into_iter()
311 .map(|c| {
312 let col = match c {
313 ProcWidgetColumn::PidOrCount => {
314 if is_count {
315 Count
316 } else {
317 Pid
318 }
319 }
320 ProcWidgetColumn::ProcNameOrCommand => {
321 if is_command {
322 Command
323 } else {
324 Name
325 }
326 }
327 ProcWidgetColumn::Cpu => CpuPercent,
328 ProcWidgetColumn::Mem => {
329 if mem_as_values {
330 MemValue
331 } else {
332 MemPercent
333 }
334 }
335 ProcWidgetColumn::VirtualMem => VirtualMem,
336 ProcWidgetColumn::ReadPerSecond => ReadPerSecond,
337 ProcWidgetColumn::WritePerSecond => WritePerSecond,
338 ProcWidgetColumn::TotalRead => TotalRead,
339 ProcWidgetColumn::TotalWrite => TotalWrite,
340 ProcWidgetColumn::User => User,
341 ProcWidgetColumn::State => State,
342 ProcWidgetColumn::Time => Time,
343 ProcWidgetColumn::Priority => Priority,
344 #[cfg(unix)]
345 ProcWidgetColumn::Nice => Nice,
346 #[cfg(feature = "gpu")]
347 ProcWidgetColumn::GpuMem => {
348 if mem_as_values {
349 GpuMemValue
350 } else {
351 GpuMemPercent
352 }
353 }
354 #[cfg(feature = "gpu")]
355 ProcWidgetColumn::GpuUtil => GpuUtilPercent,
356 };
357
358 make_column(col)
359 })
360 .collect(),
361 _ => {
362 let default_columns = [
363 if is_count { Count } else { Pid },
364 if is_command { Command } else { Name },
365 CpuPercent,
366 if mem_as_values { MemValue } else { MemPercent },
367 ReadPerSecond,
368 WritePerSecond,
369 TotalRead,
370 TotalWrite,
371 User,
372 State,
373 Time,
374 Priority,
375 // Maybe add nice back as a default when I can figure out how to do the
376 // default configs better for Windows? As currently otherwise there's a
377 // mismatch.
378 ];
379
380 default_columns.into_iter().map(make_column).collect()
381 }
382 }
383 };
384
385 let column_mapping = columns
386 .iter()
387 .map(|col| {
388 use ProcColumn::*;
389
390 match col.inner() {
391 CpuPercent => ProcWidgetColumn::Cpu,
392 MemValue | MemPercent => ProcWidgetColumn::Mem,
393 VirtualMem => ProcWidgetColumn::VirtualMem,
394 Pid | Count => ProcWidgetColumn::PidOrCount,
395 Name | Command => ProcWidgetColumn::ProcNameOrCommand,
396 ReadPerSecond => ProcWidgetColumn::ReadPerSecond,
397 WritePerSecond => ProcWidgetColumn::WritePerSecond,
398 TotalRead => ProcWidgetColumn::TotalRead,
399 TotalWrite => ProcWidgetColumn::TotalWrite,
400 State => ProcWidgetColumn::State,
401 User => ProcWidgetColumn::User,
402 Time => ProcWidgetColumn::Time,
403 Priority => ProcWidgetColumn::Priority,
404 #[cfg(unix)]
405 Nice => ProcWidgetColumn::Nice,
406 #[cfg(feature = "gpu")]
407 GpuMemValue | GpuMemPercent => ProcWidgetColumn::GpuMem,
408 #[cfg(feature = "gpu")]
409 GpuUtilPercent => ProcWidgetColumn::GpuUtil,
410 }
411 })
412 .collect::<IndexSet<_>>();
413
414 let configured_default_sort = table_config.default_sort.and_then(|c| {
415 let widget_col = ProcWidgetColumn::from(&c);
416 column_mapping
417 .get_index_of(&widget_col)
418 .map(|index| (index, columns[index].default_order))
419 });
420
421 let (default_sort_index, mut default_sort_order) =
422 if let Some(pair) = configured_default_sort {
423 pair
424 } else if matches!(mode, ProcWidgetMode::Tree { .. }) {
425 if let Some(index) = column_mapping.get_index_of(&ProcWidgetColumn::PidOrCount) {
426 (index, columns[index].default_order)
427 } else {
428 (0, columns[0].default_order)
429 }
430 } else if let Some(index) = column_mapping.get_index_of(&ProcWidgetColumn::Cpu) {
431 (index, columns[index].default_order)
432 } else {
433 (0, columns[0].default_order)
434 };
435
436 // If configured, override it with this.
437 if let Some(order) = table_config.sort_order {
438 default_sort_order = order;
439 }
440
441 let sort_table = Self::new_sort_table(config, colours);
442 let table = Self::new_process_table(
443 config,
444 colours,
445 columns,
446 default_sort_index,
447 default_sort_order,
448 );
449
450 let id_pid_map = HashMap::default();
451
452 let mut table = ProcWidgetState {
453 proc_search: process_search_state,
454 table,
455 sort_table,
456 id_pid_map,
457 column_mapping,
458 is_sort_open: false,
459 mode,
460 force_rerender: true,
461 force_update_data: false,
462 default_sort_index,
463 default_sort_order,
464 #[cfg(target_os = "linux")]
465 hide_k_threads: config.hide_k_threads,
466 };
467 table.sort_table.set_data(table.column_text());
468
469 table
470 }
471
472 pub fn is_using_command(&self) -> bool {
473 self.column_mapping
474 .get_index_of(&ProcWidgetColumn::ProcNameOrCommand)
475 .and_then(|index| {
476 self.table
477 .columns
478 .get(index)
479 .map(|col| matches!(col.inner(), ProcColumn::Command))
480 })
481 .unwrap_or(false)
482 }
483
484 pub fn is_mem_percent(&self) -> bool {
485 self.column_mapping
486 .get_index_of(&ProcWidgetColumn::Mem)
487 .and_then(|index| self.table.columns.get(index))
488 .map(|col| matches!(col.inner(), ProcColumn::MemPercent))
489 .unwrap_or(false)
490 }
491
492 fn get_query(&self) -> &Option<ProcessQuery> {
493 if self.proc_search.search_state.is_invalid_or_blank_search() {
494 &None
495 } else {
496 &self.proc_search.search_state.query
497 }
498 }
499
500 /// Update the current table data.
501 ///
502 /// This function *only* updates the displayed process data. If there is a
503 /// need to update the actual *stored* data, call it before this
504 /// function.
505 pub fn set_table_data(&mut self, stored_data: &InnerData) {
506 let data = match &self.mode {
507 ProcWidgetMode::Grouped | ProcWidgetMode::Normal => {
508 self.get_normal_data(&stored_data.process_data.process_harvest)
509 }
510 ProcWidgetMode::Tree(collapse) => self.get_tree_data(collapse, stored_data),
511 };
512 self.table.set_data(data);
513 self.force_update_data = false;
514 }
515
516 fn get_tree_data(
517 &self, collapsed: &TreeCollapsed, stored_data: &InnerData,
518 ) -> Vec<ProcWidgetData> {
519 const BRANCH_END: char = 'â””';
520 const BRANCH_SPLIT: char = '├';
521 const BRANCH_HORIZONTAL: char = '─';
522 const SPACED_BRANCH_VERTICAL: &str = "│ ";
523
524 let search_query = self.get_query();
525 let is_using_command = self.is_using_command();
526 let is_mem_percent = self.is_mem_percent();
527
528 let ProcessData {
529 process_harvest,
530 process_parent_mapping,
531 orphan_pids,
532 ..
533 } = &stored_data.process_data;
534
535 // Only keep a set of the kept PIDs.
536 let kept_pids = stored_data
537 .process_data
538 .process_harvest
539 .iter()
540 .filter_map(|(pid, process)| {
541 if search_query
542 .as_ref()
543 .map(|q| q.check(process, is_using_command))
544 .unwrap_or(true)
545 {
546 #[cfg(target_os = "linux")]
547 if self.hide_k_threads && process.process_type.is_kernel() {
548 return None;
549 }
550
551 Some(*pid)
552 } else {
553 None
554 }
555 })
556 .collect::<HashSet<_>>();
557
558 #[inline]
559 fn is_ancestor_shown(
560 current_process: &ProcessHarvest, kept_pids: &HashSet<Pid>,
561 process_harvest: &BTreeMap<Pid, ProcessHarvest>,
562 ) -> bool {
563 if let Some(ppid) = current_process.parent_pid {
564 if kept_pids.contains(&ppid) {
565 true
566 } else if let Some(parent) = process_harvest.get(&ppid) {
567 is_ancestor_shown(parent, kept_pids, process_harvest)
568 } else {
569 false
570 }
571 } else {
572 false
573 }
574 }
575
576 // A process is shown under the filtered tree if at least one of these
577 // conditions hold:
578 // - The process itself matches.
579 // - The process contains some descendant that matches.
580 // - The process's parent (and only parent, not any ancestor) matches.
581 let filtered_tree = {
582 let mut filtered_tree: IntHashMap<Pid, Vec<Pid>> = IntHashMap::default();
583
584 // We do a simple DFS traversal to build our filtered parent-to-tree mappings.
585 let mut visited_pids: IntHashMap<Pid, bool> = IntHashMap::default();
586 let mut stack = orphan_pids
587 .iter()
588 .filter_map(|process| process_harvest.get(process))
589 .collect_vec();
590
591 while let Some(process) = stack.last() {
592 let is_process_matching = kept_pids.contains(&process.pid);
593
594 if let Some(children_pids) = process_parent_mapping.get(&process.pid) {
595 if children_pids
596 .iter()
597 .all(|pid| visited_pids.contains_key(pid))
598 {
599 let shown_children = children_pids
600 .iter()
601 .filter(|pid| visited_pids.get(*pid).copied().unwrap_or(false))
602 .collect_vec();
603
604 // Show the entry if it is:
605 // - Matches the filter.
606 // - Has at least one child (doesn't have to be direct) that matches the
607 // filter.
608 // - Is the child of a shown process.
609 let is_shown = is_process_matching
610 || !shown_children.is_empty()
611 || is_ancestor_shown(process, &kept_pids, process_harvest);
612 visited_pids.insert(process.pid, is_shown);
613
614 if is_shown {
615 filtered_tree.insert(
616 process.pid,
617 shown_children
618 .into_iter()
619 .filter_map(|pid| {
620 process_harvest.get(pid).map(|process| process.pid)
621 })
622 .collect_vec(),
623 );
624 }
625
626 stack.pop();
627 } else {
628 children_pids
629 .iter()
630 .filter_map(|process| process_harvest.get(process))
631 .rev()
632 .for_each(|process| {
633 stack.push(process);
634 });
635 }
636 } else {
637 let is_shown = is_process_matching
638 || is_ancestor_shown(process, &kept_pids, process_harvest);
639
640 if is_shown {
641 filtered_tree.insert(process.pid, vec![]);
642 }
643
644 visited_pids.insert(process.pid, is_shown);
645 stack.pop();
646 }
647 }
648
649 filtered_tree
650 };
651
652 let mut data = vec![];
653 let mut prefixes = vec![];
654 let mut stack = orphan_pids
655 .iter()
656 .filter_map(|pid| {
657 if filtered_tree.contains_key(pid) {
658 process_harvest.get(pid).map(|process| {
659 ProcWidgetData::from_data(process, is_using_command, is_mem_percent)
660 })
661 } else {
662 None
663 }
664 })
665 .collect_vec();
666
667 stack.sort_unstable_by_key(|p| p.pid);
668
669 let column = self
670 .table
671 .columns
672 .get(self.table.sort_index())
673 .expect("columns should contain the current sort index");
674 sort_skip_pid_asc(column.inner(), &mut stack, self.table.order());
675
676 let mut length_stack = vec![stack.len()];
677 stack.reverse();
678
679 while let (Some(process), Some(siblings_left)) = (stack.pop(), length_stack.last_mut()) {
680 *siblings_left -= 1;
681
682 let disabled = !kept_pids.contains(&process.pid);
683 let is_last = *siblings_left == 0;
684
685 if collapsed.is_collapsed(process.pid) {
686 let mut summed_process = process.clone();
687 let mut has_children = false;
688
689 if let Some(children_pids) = filtered_tree.get(&process.pid) {
690 let mut sum_queue = children_pids
691 .iter()
692 .filter_map(|child| {
693 process_harvest.get(child).map(|p| {
694 ProcWidgetData::from_data(p, is_using_command, is_mem_percent)
695 })
696 })
697 .collect_vec();
698
699 while let Some(process) = sum_queue.pop() {
700 summed_process.add(&process);
701
702 if let Some(pids) = filtered_tree.get(&process.pid) {
703 sum_queue.extend(pids.iter().filter_map(|child| {
704 process_harvest.get(child).map(|p| {
705 ProcWidgetData::from_data(p, is_using_command, is_mem_percent)
706 })
707 }));
708 }
709 }
710
711 has_children = !children_pids.is_empty();
712 }
713
714 // This is so that if an entry is "collapsed" but there are no children, avoid
715 // drawing the "+".
716 let prefix = if has_children {
717 if prefixes.is_empty() {
718 "+ ".to_string()
719 } else {
720 format!(
721 "{}{}{} + ",
722 prefixes.join(""),
723 if is_last { BRANCH_END } else { BRANCH_SPLIT },
724 BRANCH_HORIZONTAL
725 )
726 }
727 } else if prefixes.is_empty() {
728 String::default()
729 } else {
730 format!(
731 "{}{}{} ",
732 prefixes.join(""),
733 if is_last { BRANCH_END } else { BRANCH_SPLIT },
734 BRANCH_HORIZONTAL
735 )
736 };
737
738 data.push(summed_process.prefix(Some(prefix)).disabled(disabled));
739 } else {
740 let prefix = if prefixes.is_empty() {
741 String::default()
742 } else {
743 format!(
744 "{}{}{} ",
745 prefixes.join(""),
746 if is_last { BRANCH_END } else { BRANCH_SPLIT },
747 BRANCH_HORIZONTAL
748 )
749 };
750 let pid = process.pid;
751 data.push(process.prefix(Some(prefix)).disabled(disabled));
752
753 if let Some(children_pids) = filtered_tree.get(&pid) {
754 if prefixes.is_empty() {
755 prefixes.push("");
756 } else {
757 prefixes.push(if is_last {
758 " "
759 } else {
760 SPACED_BRANCH_VERTICAL
761 });
762 }
763
764 let mut children = children_pids
765 .iter()
766 .filter_map(|child_pid| {
767 process_harvest.get(child_pid).map(|p| {
768 ProcWidgetData::from_data(p, is_using_command, is_mem_percent)
769 })
770 })
771 .collect_vec();
772
773 column.sort_by(&mut children, self.table.order().rev());
774
775 length_stack.push(children.len());
776 stack.extend(children);
777 }
778 }
779
780 while let Some(children_left) = length_stack.last() {
781 if *children_left == 0 {
782 length_stack.pop();
783 prefixes.pop();
784 } else {
785 break;
786 }
787 }
788 }
789
790 data
791 }
792
793 fn get_normal_data(
794 &mut self, process_harvest: &BTreeMap<Pid, ProcessHarvest>,
795 ) -> Vec<ProcWidgetData> {
796 let search_query = self.get_query();
797 let is_using_command = self.is_using_command();
798 let is_mem_percent = self.is_mem_percent();
799
800 let filtered_iter = process_harvest.values().filter(|process| {
801 #[cfg(target_os = "linux")]
802 if self.hide_k_threads && process.process_type.is_kernel() {
803 return false;
804 }
805
806 search_query
807 .as_ref()
808 .map(|query| query.check(process, is_using_command))
809 .unwrap_or(true)
810 });
811
812 let mut id_pid_map: HashMap<String, Vec<Pid>> = HashMap::default();
813 let mut filtered_data: Vec<ProcWidgetData> = if let ProcWidgetMode::Grouped = self.mode {
814 let mut id_process_mapping: HashMap<&String, ProcWidgetData> = HashMap::default();
815
816 for process in filtered_iter {
817 let id = if is_using_command {
818 &process.command
819 } else {
820 &process.name
821 };
822 let pid = process.pid;
823
824 if let Some(entry) = id_pid_map.get_mut(id) {
825 entry.push(pid);
826 } else {
827 id_pid_map.insert(id.clone(), vec![pid]);
828 }
829
830 if let Some(pwd) = id_process_mapping.get_mut(id) {
831 pwd.cpu_usage_percent += process.cpu_usage_percent;
832
833 match &mut pwd.mem_usage {
834 MemUsage::Percent(usage) => {
835 *usage += process.mem_usage_percent;
836 }
837 MemUsage::Bytes(usage) => {
838 *usage += process.mem_usage;
839 }
840 }
841
842 pwd.rps += process.read_per_sec;
843 pwd.wps += process.write_per_sec;
844 pwd.total_read += process.total_read;
845 pwd.total_write += process.total_write;
846 pwd.time = pwd.time.max(process.time);
847 #[cfg(feature = "gpu")]
848 {
849 pwd.gpu_usage += process.gpu_util;
850 match &mut pwd.gpu_mem_usage {
851 MemUsage::Percent(usage) => {
852 *usage += process.gpu_mem_percent;
853 }
854 MemUsage::Bytes(usage) => {
855 *usage += process.gpu_mem;
856 }
857 }
858 }
859
860 pwd.num_similar += 1;
861 } else {
862 id_process_mapping.insert(
863 id,
864 ProcWidgetData::from_data(process, is_using_command, is_mem_percent),
865 );
866 }
867 }
868
869 id_process_mapping.into_values().collect()
870 } else {
871 filtered_iter
872 .map(|process| ProcWidgetData::from_data(process, is_using_command, is_mem_percent))
873 .collect()
874 };
875
876 self.id_pid_map = id_pid_map;
877
878 if let Some(column) = self.table.columns.get(self.table.sort_index()) {
879 sort_skip_pid_asc(column.inner(), &mut filtered_data, self.table.order());
880 }
881
882 filtered_data
883 }
884
885 #[inline(always)]
886 fn get_mut_proc_col(&mut self, index: usize) -> Option<&mut ProcColumn> {
887 self.table.columns.get_mut(index).map(|col| col.inner_mut())
888 }
889
890 pub fn toggle_mem_percentage(&mut self) {
891 if let Some(index) = self.column_mapping.get_index_of(&ProcWidgetColumn::Mem)
892 && let Some(mem) = self.get_mut_proc_col(index)
893 {
894 match mem {
895 ProcColumn::MemValue => {
896 *mem = ProcColumn::MemPercent;
897 }
898 ProcColumn::MemPercent => {
899 *mem = ProcColumn::MemValue;
900 }
901 _ => unreachable!(),
902 }
903
904 self.sort_table.set_data(self.column_text());
905 self.force_data_update();
906 }
907 #[cfg(feature = "gpu")]
908 if let Some(index) = self.column_mapping.get_index_of(&ProcWidgetColumn::GpuMem)
909 && let Some(mem) = self.get_mut_proc_col(index)
910 {
911 match mem {
912 ProcColumn::GpuMemValue => {
913 *mem = ProcColumn::GpuMemPercent;
914 }
915 ProcColumn::GpuMemPercent => {
916 *mem = ProcColumn::GpuMemValue;
917 }
918 _ => unreachable!(),
919 }
920
921 self.sort_table.set_data(self.column_text());
922 self.force_data_update();
923 }
924 }
925
926 /// Forces an update of the data stored.
927 #[inline]
928 pub fn force_data_update(&mut self) {
929 self.force_update_data = true;
930 }
931
932 /// Forces an entire rerender and update of the data stored.
933 #[inline]
934 pub fn force_rerender_and_update(&mut self) {
935 self.force_rerender = true;
936 self.force_update_data = true;
937 }
938
939 #[cfg(target_os = "linux")]
940 pub fn toggle_k_thread(&mut self) {
941 self.hide_k_threads = !self.hide_k_threads;
942 self.force_rerender_and_update();
943 }
944
945 /// Marks the selected column as hidden, and automatically resets the
946 /// selected column to the default sort index and order.
947 fn hide_column(&mut self, column: ProcWidgetColumn) {
948 if let Some(index) = self.column_mapping.get_index_of(&column)
949 && let Some(col) = self.table.columns.get_mut(index)
950 {
951 col.set_hidden(true);
952
953 if self.table.sort_index() == index {
954 self.table.set_sort_index(self.default_sort_index);
955 self.table.set_order(self.default_sort_order);
956 }
957 }
958 }
959
960 /// Marks the selected column as shown.
961 fn show_column(&mut self, column: ProcWidgetColumn) {
962 if let Some(index) = self.column_mapping.get_index_of(&column)
963 && let Some(col) = self.table.columns.get_mut(index)
964 {
965 col.set_hidden(false);
966 }
967 }
968
969 /// Select a column. If the column is already selected, then just toggle the
970 /// sort order.
971 pub fn select_column(&mut self, column: ProcWidgetColumn) {
972 if let Some(index) = self.column_mapping.get_index_of(&column) {
973 self.table.set_sort_index(index);
974 self.force_data_update();
975 }
976 }
977
978 pub fn collapse_current_tree_branch_entry(&mut self) {
979 if let ProcWidgetMode::Tree(collapsed) = &mut self.mode
980 && let Some(process) = self.table.current_item()
981 {
982 collapsed.collapse(process.pid);
983 self.force_data_update();
984 }
985 }
986
987 pub fn expand_current_tree_branch_entry(&mut self) {
988 if let ProcWidgetMode::Tree(collapsed) = &mut self.mode
989 && let Some(process) = self.table.current_item()
990 {
991 collapsed.expand(process.pid);
992 self.force_data_update();
993 }
994 }
995
996 pub fn toggle_current_tree_branch_entry(&mut self) {
997 if let ProcWidgetMode::Tree(collapsed) = &mut self.mode
998 && let Some(process) = self.table.current_item()
999 {
1000 collapsed.toggle(process.pid);
1001 self.force_data_update();
1002 }
1003 }
1004
1005 pub fn toggle_command(&mut self) {
1006 if let Some(index) = self
1007 .column_mapping
1008 .get_index_of(&ProcWidgetColumn::ProcNameOrCommand)
1009 && let Some(col) = self.table.columns.get_mut(index)
1010 {
1011 let inner = col.inner_mut();
1012 match inner {
1013 ProcColumn::Name => {
1014 *inner = ProcColumn::Command;
1015 if let ColumnWidthBounds::Soft { max_percentage, .. } = col.bounds_mut() {
1016 *max_percentage = Some(0.5);
1017 }
1018 }
1019 ProcColumn::Command => {
1020 *inner = ProcColumn::Name;
1021 if let ColumnWidthBounds::Soft { max_percentage, .. } = col.bounds_mut() {
1022 *max_percentage = match self.mode {
1023 ProcWidgetMode::Tree { .. } => Some(0.5),
1024 ProcWidgetMode::Grouped | ProcWidgetMode::Normal => Some(0.3),
1025 };
1026 }
1027 }
1028 _ => unreachable!(),
1029 }
1030 self.sort_table.set_data(self.column_text());
1031 self.force_rerender_and_update();
1032 }
1033 }
1034
1035 /// Toggles the appropriate columns/settings when tab is pressed.
1036 ///
1037 /// If count is enabled, we should set the mode to
1038 /// [`ProcWidgetMode::Grouped`], and switch off the User and State
1039 /// columns. We should also move the user off of the columns if they were
1040 /// selected, as those columns are now hidden (handled by internal
1041 /// method calls), and go back to the "defaults".
1042 ///
1043 /// Otherwise, if count is disabled, then if the columns exist, the User and
1044 /// State columns should be re-enabled, and the mode switched to
1045 /// [`ProcWidgetMode::Normal`].
1046 pub(crate) fn toggle_tab(&mut self) {
1047 if !matches!(self.mode, ProcWidgetMode::Tree { .. })
1048 && let Some(index) = self
1049 .column_mapping
1050 .get_index_of(&ProcWidgetColumn::PidOrCount)
1051 && let Some(sort_col) = self.table.columns.get_mut(index)
1052 {
1053 let col = sort_col.inner_mut();
1054 match col {
1055 ProcColumn::Pid => {
1056 *col = ProcColumn::Count;
1057 sort_col.default_order = SortOrder::Descending;
1058
1059 self.hide_column(ProcWidgetColumn::User);
1060 self.hide_column(ProcWidgetColumn::State);
1061 self.mode = ProcWidgetMode::Grouped;
1062 }
1063 ProcColumn::Count => {
1064 *col = ProcColumn::Pid;
1065 sort_col.default_order = SortOrder::Ascending;
1066
1067 self.show_column(ProcWidgetColumn::User);
1068 self.show_column(ProcWidgetColumn::State);
1069 self.mode = ProcWidgetMode::Normal;
1070 }
1071 _ => unreachable!(),
1072 }
1073
1074 self.sort_table.set_data(self.column_text());
1075 self.force_rerender_and_update();
1076 }
1077 }
1078
1079 pub fn column_text(&self) -> Vec<Cow<'static, str>> {
1080 self.table
1081 .columns
1082 .iter()
1083 .filter(|c| !c.is_hidden())
1084 .map(|c| c.inner().text())
1085 .collect::<Vec<_>>()
1086 }
1087
1088 pub fn is_search_enabled(&self) -> bool {
1089 self.proc_search.search_state.is_enabled
1090 }
1091
1092 /// Update the current search query.
1093 ///
1094 /// TODO: Maybe debounce this.
1095 pub fn update_query(&mut self) {
1096 let current_query = self
1097 .proc_search
1098 .search_state
1099 .input_field_state
1100 .current_query();
1101
1102 if current_query.is_empty() {
1103 self.proc_search.search_state.is_invalid_search = false;
1104 self.proc_search.search_state.error_message = None;
1105 } else {
1106 match parse_query(current_query, &self.proc_search.query_options) {
1107 Ok(parsed_query) => {
1108 self.proc_search.search_state.query = Some(parsed_query);
1109 self.proc_search.search_state.is_invalid_search = false;
1110 self.proc_search.search_state.error_message = None;
1111 }
1112 Err(err) => {
1113 self.proc_search.search_state.is_invalid_search = true;
1114 self.proc_search.search_state.error_message = Some(err.to_string());
1115 }
1116 }
1117 }
1118 self.table.state.display_start_index = 0;
1119 self.table.state.current_index = 0;
1120
1121 self.force_data_update();
1122 }
1123
1124 pub fn clear_search(&mut self) {
1125 self.proc_search.search_state.reset();
1126 self.force_data_update();
1127 }
1128
1129 /// Sets the [`ProcWidgetState`]'s current sort index to whatever was in the
1130 /// sort table if possible, then closes the sort table.
1131 pub(crate) fn use_sort_table_value(&mut self) {
1132 self.table.set_sort_index(self.sort_table.current_index());
1133 self.is_sort_open = false;
1134 self.force_rerender_and_update();
1135 }
1136
1137 #[cfg(test)]
1138 pub(crate) fn test_equality(&self, other: &Self) -> bool {
1139 self.mode == other.mode
1140 && self.proc_search.query_options == other.proc_search.query_options
1141 && self
1142 .table
1143 .columns
1144 .iter()
1145 .map(|c| c.header())
1146 .collect::<Vec<_>>()
1147 == other
1148 .table
1149 .columns
1150 .iter()
1151 .map(|c| c.header())
1152 .collect::<Vec<_>>()
1153 }
1154 }
1155
1156 #[inline]
1157 fn sort_skip_pid_asc(column: &ProcColumn, data: &mut [ProcWidgetData], order: SortOrder) {
1158 let descending = matches!(order, SortOrder::Descending);
1159 match column {
1160 ProcColumn::Pid if !descending => {}
1161 _ => {
1162 column.sort_data(data, descending);
1163 }
1164 }
1165 }
1166
1167 #[cfg(test)]
1168 mod test {
1169 use std::time::Duration;
1170
1171 use super::*;
1172 #[cfg(target_os = "linux")]
1173 use crate::collection::processes::ProcessType;
1174 use crate::widgets::MemUsage;
1175
1176 #[test]
1177 fn test_proc_sort() {
1178 let a = ProcWidgetData {
1179 pid: 1,
1180 ppid: None,
1181 id: "A".into(),
1182 cpu_usage_percent: 0.0,
1183 mem_usage: MemUsage::Percent(1.1),
1184 virtual_mem: 100,
1185 rps: 0,
1186 wps: 0,
1187 total_read: 0,
1188 total_write: 0,
1189 process_state: "N/A",
1190 process_char: '?',
1191 #[cfg(unix)]
1192 user: Some("root".into()),
1193 #[cfg(not(target_family = "unix"))]
1194 user: Some("N/A".into()),
1195 num_similar: 0,
1196 disabled: false,
1197 time: Duration::from_secs(0),
1198 #[cfg(feature = "gpu")]
1199 gpu_mem_usage: MemUsage::Percent(1.1),
1200 #[cfg(feature = "gpu")]
1201 gpu_usage: 0,
1202 #[cfg(target_os = "linux")]
1203 process_type: crate::collection::processes::ProcessType::Regular,
1204 #[cfg(unix)]
1205 nice: 0,
1206 priority: -20,
1207 };
1208
1209 let b = ProcWidgetData {
1210 pid: 2,
1211 ppid: Some(1),
1212 id: "B".into(),
1213 cpu_usage_percent: 1.1,
1214 mem_usage: MemUsage::Percent(2.2),
1215 ..(a.clone())
1216 };
1217
1218 let c = ProcWidgetData {
1219 pid: 3,
1220 ppid: Some(1),
1221 id: "C".into(),
1222 cpu_usage_percent: 2.2,
1223 mem_usage: MemUsage::Percent(0.0),
1224 ..(a.clone())
1225 };
1226
1227 let d = ProcWidgetData {
1228 pid: 4,
1229 ppid: Some(2),
1230 id: "D".into(),
1231 cpu_usage_percent: 0.0,
1232 mem_usage: MemUsage::Percent(0.0),
1233 ..(a.clone())
1234 };
1235 let mut data = vec![d.clone(), b.clone(), c.clone(), a.clone()];
1236
1237 // Assume we had sorted over by pid.
1238 data.sort_by_key(|p| p.pid);
1239 sort_skip_pid_asc(&ProcColumn::CpuPercent, &mut data, SortOrder::Descending);
1240 assert_eq!(
1241 [&c, &b, &a, &d].iter().map(|d| d.pid).collect::<Vec<_>>(),
1242 data.iter().map(|d| d.pid).collect::<Vec<_>>(),
1243 );
1244
1245 // Note that the PID ordering for ties is still ascending.
1246 data.sort_by_key(|p| p.pid);
1247 sort_skip_pid_asc(&ProcColumn::CpuPercent, &mut data, SortOrder::Ascending);
1248 assert_eq!(
1249 [&a, &d, &b, &c].iter().map(|d| d.pid).collect::<Vec<_>>(),
1250 data.iter().map(|d| d.pid).collect::<Vec<_>>(),
1251 );
1252
1253 data.sort_by_key(|p| p.pid);
1254 sort_skip_pid_asc(&ProcColumn::MemPercent, &mut data, SortOrder::Descending);
1255 assert_eq!(
1256 [&b, &a, &c, &d].iter().map(|d| d.pid).collect::<Vec<_>>(),
1257 data.iter().map(|d| d.pid).collect::<Vec<_>>(),
1258 );
1259
1260 // Note that the PID ordering for ties is still ascending.
1261 data.sort_by_key(|p| p.pid);
1262 sort_skip_pid_asc(&ProcColumn::MemPercent, &mut data, SortOrder::Ascending);
1263 assert_eq!(
1264 [&c, &d, &a, &b].iter().map(|d| d.pid).collect::<Vec<_>>(),
1265 data.iter().map(|d| d.pid).collect::<Vec<_>>(),
1266 );
1267 }
1268
1269 fn get_columns(table: &ProcessTable) -> Vec<ProcColumn> {
1270 table
1271 .columns
1272 .iter()
1273 .filter_map(|c| {
1274 if c.is_hidden() {
1275 None
1276 } else {
1277 Some(*c.inner())
1278 }
1279 })
1280 .collect::<Vec<_>>()
1281 }
1282
1283 fn init_state(table_config: ProcTableConfig, columns: &[ProcWidgetColumn]) -> ProcWidgetState {
1284 let config = AppConfigFields::default();
1285 let styling = Styles::default();
1286 let columns = Some(columns.iter().cloned().collect());
1287
1288 ProcWidgetState::new(
1289 &config,
1290 ProcWidgetMode::Normal,
1291 table_config,
1292 &styling,
1293 &columns,
1294 )
1295 }
1296
1297 fn init_default_state(columns: &[ProcWidgetColumn]) -> ProcWidgetState {
1298 init_state(ProcTableConfig::default(), columns)
1299 }
1300
1301 #[test]
1302 fn default_sort_honoured() {
1303 let init_columns = [
1304 ProcWidgetColumn::PidOrCount,
1305 ProcWidgetColumn::ProcNameOrCommand,
1306 ProcWidgetColumn::Cpu,
1307 ProcWidgetColumn::Mem,
1308 ];
1309
1310 let state_default = init_default_state(&init_columns);
1311 assert_eq!(
1312 state_default.table.sort_index(),
1313 2,
1314 "default sort should be CPU (index 2 in init_columns)"
1315 );
1316
1317 let table_config = ProcTableConfig {
1318 default_sort: Some(ProcColumn::MemPercent),
1319 ..Default::default()
1320 };
1321 let state_mem = init_state(table_config, &init_columns);
1322 assert_eq!(state_mem.table.sort_index(), 3);
1323
1324 let table_config = ProcTableConfig {
1325 default_sort: Some(ProcColumn::Pid),
1326 ..Default::default()
1327 };
1328 let state_pid = init_state(table_config, &init_columns);
1329 assert_eq!(state_pid.table.sort_index(), 0);
1330 }
1331
1332 #[test]
1333 fn default_sort_falls_back_when_column_absent() {
1334 // `default_sort` points at a column the user didn't include. We should
1335 // fall back to the built-in default rather than panic or pick column 0.
1336 let init_columns = [
1337 ProcWidgetColumn::PidOrCount,
1338 ProcWidgetColumn::ProcNameOrCommand,
1339 ProcWidgetColumn::Cpu,
1340 ];
1341
1342 let table_config = ProcTableConfig {
1343 default_sort: Some(ProcColumn::MemPercent),
1344 ..Default::default()
1345 };
1346 let state = init_state(table_config, &init_columns);
1347 assert_eq!(state.table.sort_index(), 2);
1348 }
1349
1350 #[test]
1351 fn custom_columns() {
1352 let init_columns = vec![
1353 ProcWidgetColumn::PidOrCount,
1354 ProcWidgetColumn::ProcNameOrCommand,
1355 ProcWidgetColumn::Mem,
1356 ProcWidgetColumn::State,
1357 ];
1358 let columns = vec![
1359 ProcColumn::Pid,
1360 ProcColumn::Name,
1361 ProcColumn::MemPercent,
1362 ProcColumn::State,
1363 ];
1364 let state = init_default_state(&init_columns);
1365 assert_eq!(get_columns(&state.table), columns);
1366 }
1367
1368 #[test]
1369 fn toggle_count_pid() {
1370 let init_columns = [
1371 ProcWidgetColumn::PidOrCount,
1372 ProcWidgetColumn::ProcNameOrCommand,
1373 ProcWidgetColumn::Mem,
1374 ProcWidgetColumn::State,
1375 ];
1376 let original_columns = vec![
1377 ProcColumn::Pid,
1378 ProcColumn::Name,
1379 ProcColumn::MemPercent,
1380 ProcColumn::State,
1381 ];
1382 let new_columns = vec![ProcColumn::Count, ProcColumn::Name, ProcColumn::MemPercent];
1383
1384 let mut state = init_default_state(&init_columns);
1385 assert_eq!(get_columns(&state.table), original_columns);
1386
1387 // This should hide the state.
1388 state.toggle_tab();
1389 assert_eq!(get_columns(&state.table), new_columns);
1390
1391 // This should re-reveal the state.
1392 state.toggle_tab();
1393 assert_eq!(get_columns(&state.table), original_columns);
1394 }
1395
1396 #[test]
1397 fn toggle_count_pid_2() {
1398 let init_columns = [
1399 ProcWidgetColumn::ProcNameOrCommand,
1400 ProcWidgetColumn::Mem,
1401 ProcWidgetColumn::User,
1402 ProcWidgetColumn::State,
1403 ProcWidgetColumn::PidOrCount,
1404 ];
1405 let original_columns = vec![
1406 ProcColumn::Name,
1407 ProcColumn::MemPercent,
1408 ProcColumn::User,
1409 ProcColumn::State,
1410 ProcColumn::Pid,
1411 ];
1412 let new_columns = vec![ProcColumn::Name, ProcColumn::MemPercent, ProcColumn::Count];
1413
1414 let mut state = init_default_state(&init_columns);
1415 assert_eq!(get_columns(&state.table), original_columns);
1416
1417 // This should hide the state.
1418 state.toggle_tab();
1419 assert_eq!(get_columns(&state.table), new_columns);
1420
1421 // This should re-reveal the state.
1422 state.toggle_tab();
1423 assert_eq!(get_columns(&state.table), original_columns);
1424 }
1425
1426 #[test]
1427 fn toggle_command() {
1428 let init_columns = [
1429 ProcWidgetColumn::PidOrCount,
1430 ProcWidgetColumn::State,
1431 ProcWidgetColumn::Mem,
1432 ProcWidgetColumn::ProcNameOrCommand,
1433 ];
1434 let original_columns = vec![
1435 ProcColumn::Pid,
1436 ProcColumn::State,
1437 ProcColumn::MemPercent,
1438 ProcColumn::Command,
1439 ];
1440 let new_columns = vec![
1441 ProcColumn::Pid,
1442 ProcColumn::State,
1443 ProcColumn::MemPercent,
1444 ProcColumn::Name,
1445 ];
1446
1447 let table_config = ProcTableConfig {
1448 is_command: true,
1449 ..Default::default()
1450 };
1451 let mut state = init_state(table_config, &init_columns);
1452 assert_eq!(get_columns(&state.table), original_columns);
1453
1454 state.toggle_command();
1455 assert_eq!(get_columns(&state.table), new_columns);
1456
1457 state.toggle_command();
1458 assert_eq!(get_columns(&state.table), original_columns);
1459 }
1460
1461 #[test]
1462 fn toggle_mem_percentage() {
1463 let init_columns = [
1464 ProcWidgetColumn::PidOrCount,
1465 ProcWidgetColumn::Mem,
1466 ProcWidgetColumn::State,
1467 ProcWidgetColumn::ProcNameOrCommand,
1468 ];
1469 let original_columns = vec![
1470 ProcColumn::Pid,
1471 ProcColumn::MemPercent,
1472 ProcColumn::State,
1473 ProcColumn::Name,
1474 ];
1475 let new_columns = vec![
1476 ProcColumn::Pid,
1477 ProcColumn::MemValue,
1478 ProcColumn::State,
1479 ProcColumn::Name,
1480 ];
1481
1482 let mut state = init_default_state(&init_columns);
1483 assert_eq!(get_columns(&state.table), original_columns);
1484
1485 state.toggle_mem_percentage();
1486 assert_eq!(get_columns(&state.table), new_columns);
1487
1488 state.toggle_mem_percentage();
1489 assert_eq!(get_columns(&state.table), original_columns);
1490 }
1491
1492 #[test]
1493 fn toggle_mem_percentage_2() {
1494 let init_columns = [
1495 ProcWidgetColumn::PidOrCount,
1496 ProcWidgetColumn::Mem,
1497 ProcWidgetColumn::State,
1498 ProcWidgetColumn::ProcNameOrCommand,
1499 ];
1500 let original_columns = vec![
1501 ProcColumn::Pid,
1502 ProcColumn::MemValue,
1503 ProcColumn::State,
1504 ProcColumn::Name,
1505 ];
1506 let new_columns = vec![
1507 ProcColumn::Pid,
1508 ProcColumn::MemPercent,
1509 ProcColumn::State,
1510 ProcColumn::Name,
1511 ];
1512
1513 let table_config = ProcTableConfig {
1514 show_memory_as_values: true,
1515 ..Default::default()
1516 };
1517 let mut state = init_state(table_config, &init_columns);
1518 assert_eq!(get_columns(&state.table), original_columns);
1519
1520 state.toggle_mem_percentage();
1521 assert_eq!(get_columns(&state.table), new_columns);
1522
1523 state.toggle_mem_percentage();
1524 assert_eq!(get_columns(&state.table), original_columns);
1525 }
1526
1527 #[test]
1528 fn columns_and_is_using_command() {
1529 let init_columns = [
1530 ProcWidgetColumn::PidOrCount,
1531 ProcWidgetColumn::Mem,
1532 ProcWidgetColumn::State,
1533 ProcWidgetColumn::ProcNameOrCommand,
1534 ];
1535 let original_columns = vec![
1536 ProcColumn::Pid,
1537 ProcColumn::MemPercent,
1538 ProcColumn::State,
1539 ProcColumn::Command,
1540 ];
1541
1542 let table_config = ProcTableConfig {
1543 is_command: true,
1544 ..Default::default()
1545 };
1546 let mut state = init_state(table_config, &init_columns);
1547 assert_eq!(get_columns(&state.table), original_columns);
1548 assert!(state.is_using_command());
1549
1550 state.toggle_command();
1551 assert!(!state.is_using_command());
1552
1553 state.toggle_command();
1554 assert!(state.is_using_command());
1555 }
1556
1557 #[test]
1558 fn columns_and_is_memory() {
1559 let init_columns = [
1560 ProcWidgetColumn::PidOrCount,
1561 ProcWidgetColumn::Mem,
1562 ProcWidgetColumn::State,
1563 ProcWidgetColumn::ProcNameOrCommand,
1564 ];
1565 let original_columns = vec![
1566 ProcColumn::Pid,
1567 ProcColumn::MemValue,
1568 ProcColumn::State,
1569 ProcColumn::Name,
1570 ];
1571
1572 let table_config = ProcTableConfig {
1573 show_memory_as_values: true,
1574 ..Default::default()
1575 };
1576 let mut state = init_state(table_config, &init_columns);
1577 assert_eq!(get_columns(&state.table), original_columns);
1578 assert!(!state.is_mem_percent());
1579
1580 state.toggle_mem_percentage();
1581 assert!(state.is_mem_percent());
1582
1583 state.toggle_mem_percentage();
1584 assert!(!state.is_mem_percent());
1585 }
1586
1587 /// Tests toggling if both mem and mem% columns are configured.
1588 ///
1589 /// Currently, this test doesn't really do much, since we treat these two
1590 /// columns as the same - this test is intended for use later when we
1591 /// might allow both at the same time.
1592 #[test]
1593 fn double_memory_sim_toggle() {
1594 let init_columns = [
1595 ProcWidgetColumn::Mem,
1596 ProcWidgetColumn::PidOrCount,
1597 ProcWidgetColumn::State,
1598 ProcWidgetColumn::ProcNameOrCommand,
1599 ProcWidgetColumn::Mem,
1600 ];
1601 let original_columns = vec![
1602 ProcColumn::MemPercent,
1603 ProcColumn::Pid,
1604 ProcColumn::State,
1605 ProcColumn::Name,
1606 ];
1607 let new_columns = vec![
1608 ProcColumn::MemValue,
1609 ProcColumn::Pid,
1610 ProcColumn::State,
1611 ProcColumn::Name,
1612 ];
1613
1614 let mut state = init_default_state(&init_columns);
1615 assert_eq!(get_columns(&state.table), original_columns);
1616
1617 state.toggle_mem_percentage();
1618 assert_eq!(get_columns(&state.table), new_columns);
1619
1620 state.toggle_mem_percentage();
1621 assert_eq!(get_columns(&state.table), original_columns);
1622 }
1623
1624 /// Tests toggling if both pid and count columns are configured.
1625 ///
1626 /// Currently, this test doesn't really do much, since we treat these two
1627 /// columns as the same - this test is intended for use later when we
1628 /// might allow both at the same time.
1629 #[test]
1630 fn pid_and_count_sim_toggle() {
1631 let init_columns = [
1632 ProcWidgetColumn::ProcNameOrCommand,
1633 ProcWidgetColumn::PidOrCount,
1634 ProcWidgetColumn::Mem,
1635 ProcWidgetColumn::State,
1636 ProcWidgetColumn::PidOrCount,
1637 ];
1638 let original_columns = vec![
1639 ProcColumn::Name,
1640 ProcColumn::Pid,
1641 ProcColumn::MemPercent,
1642 ProcColumn::State,
1643 ];
1644 let new_columns = vec![ProcColumn::Name, ProcColumn::Count, ProcColumn::MemPercent];
1645
1646 let mut state = init_default_state(&init_columns);
1647 assert_eq!(get_columns(&state.table), original_columns);
1648
1649 // This should hide the state.
1650 state.toggle_tab();
1651 assert_eq!(get_columns(&state.table), new_columns);
1652
1653 // This should re-reveal the state.
1654 state.toggle_tab();
1655 assert_eq!(get_columns(&state.table), original_columns);
1656 }
1657
1658 /// Tests toggling if both command and name columns are configured.
1659 ///
1660 /// Currently, this test doesn't really do much, since we treat these two
1661 /// columns as the same - this test is intended for use later when we
1662 /// might allow both at the same time.
1663 #[test]
1664 fn command_name_sim_toggle() {
1665 let init_columns = [
1666 ProcWidgetColumn::ProcNameOrCommand,
1667 ProcWidgetColumn::PidOrCount,
1668 ProcWidgetColumn::State,
1669 ProcWidgetColumn::Mem,
1670 ProcWidgetColumn::ProcNameOrCommand,
1671 ];
1672 let original_columns = vec![
1673 ProcColumn::Command,
1674 ProcColumn::Pid,
1675 ProcColumn::State,
1676 ProcColumn::MemPercent,
1677 ];
1678 let new_columns = vec![
1679 ProcColumn::Name,
1680 ProcColumn::Pid,
1681 ProcColumn::State,
1682 ProcColumn::MemPercent,
1683 ];
1684
1685 let table_config = ProcTableConfig {
1686 is_command: true,
1687 ..Default::default()
1688 };
1689 let mut state = init_state(table_config, &init_columns);
1690 assert_eq!(get_columns(&state.table), original_columns);
1691
1692 state.toggle_command();
1693 assert_eq!(get_columns(&state.table), new_columns);
1694
1695 state.toggle_command();
1696 assert_eq!(get_columns(&state.table), original_columns);
1697 }
1698
1699 /// Sanity test to ensure tree collapse logic works, both when
1700 /// enabled-by-default or disabled-by-default.
1701 #[test]
1702 fn test_tree_collapse() {
1703 {
1704 let mut collapsed_by_default = TreeCollapsed::new(true);
1705
1706 assert!(collapsed_by_default.is_collapsed(1));
1707
1708 collapsed_by_default.collapse(1);
1709 assert!(collapsed_by_default.is_collapsed(1));
1710
1711 collapsed_by_default.expand(1);
1712 assert!(!collapsed_by_default.is_collapsed(1));
1713
1714 collapsed_by_default.toggle(1);
1715 assert!(collapsed_by_default.is_collapsed(1));
1716
1717 collapsed_by_default.toggle(1);
1718 assert!(!collapsed_by_default.is_collapsed(1));
1719 }
1720
1721 {
1722 let mut expanded_by_default = TreeCollapsed::new(false);
1723
1724 assert!(!expanded_by_default.is_collapsed(1));
1725
1726 expanded_by_default.collapse(1);
1727 assert!(expanded_by_default.is_collapsed(1));
1728
1729 expanded_by_default.expand(1);
1730 assert!(!expanded_by_default.is_collapsed(1));
1731
1732 expanded_by_default.toggle(1);
1733 assert!(expanded_by_default.is_collapsed(1));
1734
1735 expanded_by_default.toggle(1);
1736 assert!(!expanded_by_default.is_collapsed(1));
1737 }
1738 }
1739 #[cfg(target_os = "linux")]
1740 /// Sanity test to ensure kernel thread processes are toggled
1741 #[test]
1742 fn test_toggle_k_threads() {
1743 let init_columns = [
1744 ProcWidgetColumn::ProcNameOrCommand,
1745 ProcWidgetColumn::PidOrCount,
1746 ProcWidgetColumn::State,
1747 ProcWidgetColumn::Mem,
1748 ProcWidgetColumn::ProcNameOrCommand,
1749 ];
1750 let mut state = init_default_state(&init_columns);
1751 let process_harvest = ProcessHarvest {
1752 pid: 1,
1753 ..Default::default()
1754 };
1755 let k_process_harvest = ProcessHarvest {
1756 pid: 2,
1757 process_type: ProcessType::Kernel,
1758 ..Default::default()
1759 };
1760 // test get_normal_data default is filtered by toggle_k_thread
1761 let mut normal_proc_harvest: BTreeMap<Pid, ProcessHarvest> = BTreeMap::new();
1762 normal_proc_harvest.insert(1, process_harvest.clone());
1763 normal_proc_harvest.insert(2, k_process_harvest.clone());
1764 let default_normal_results = state.get_normal_data(&normal_proc_harvest).len();
1765 assert!(default_normal_results == 2);
1766 state.toggle_k_thread();
1767 let filtered_normal_results = state.get_normal_data(&normal_proc_harvest).len();
1768 assert!(filtered_normal_results == 1);
1769 // test that get_normal_data in grouped mode is still filtered
1770 state.mode = ProcWidgetMode::Grouped;
1771 let filtered_grouped_results = state.get_normal_data(&normal_proc_harvest).len();
1772 assert!(filtered_grouped_results == 1);
1773 // test that get_tree_data is filtered on toggle_k_thread
1774 let tree_collapsed = TreeCollapsed::new(false);
1775 state.mode = ProcWidgetMode::Tree(tree_collapsed.clone());
1776 state.hide_k_threads = false;
1777 let mut tree_proc_data = ProcessData::default();
1778 tree_proc_data.process_harvest.insert(1, process_harvest);
1779 tree_proc_data.process_harvest.insert(2, k_process_harvest);
1780 tree_proc_data.orphan_pids = vec![1, 2];
1781 let mut tree_stored_data = InnerData::default();
1782 tree_stored_data.process_data = tree_proc_data;
1783 let default_tree_results = state
1784 .get_tree_data(&tree_collapsed, &tree_stored_data)
1785 .len();
1786 assert!(default_tree_results == 2);
1787 state.toggle_k_thread();
1788 let filtered_tree_results = state
1789 .get_tree_data(&tree_collapsed, &tree_stored_data)
1790 .len();
1791 assert!(filtered_tree_results == 1);
1792 }
1793 }